diff --git a/.agents/skills/macios-ci-postmortem/SKILL.md b/.agents/skills/macios-ci-postmortem/SKILL.md new file mode 100644 index 000000000000..dca092ad0e4a --- /dev/null +++ b/.agents/skills/macios-ci-postmortem/SKILL.md @@ -0,0 +1,727 @@ +--- +name: macios-ci-postmortem +description: Post-mortem analysis of CI failures across recent PRs in dotnet/macios. Identifies flaky tests, infrastructure issues, and shared regressions by analyzing builds from the last week. Files or updates GitHub issues for failures unrelated to any specific PR. Use when asked to "find flaky tests", "CI post-mortem", "what's been failing in CI", or "file issues for flaky failures". +--- + +# macios CI Post-Mortem + +Analyze CI failures across recent PRs to identify flaky tests, infrastructure issues, and shared regressions that are not caused by any specific PR. File or update GitHub issues for these. + +## References + +Read these as needed during investigation: + +- `references/azure-devops-cli.md` — az CLI commands, artifact naming conventions, and JSON parsing caveats. + +## Overview + +This skill operates in four phases: + +1. **Discovery** — collect all recent PR-validation builds from AzDO +2. **Extraction** — for failed builds, extract normalized failure records +3. **Classification** — categorize failures as flaky, infrastructure, shared regression, or PR-specific +4. **Issue Actions** — propose GitHub issues, get user confirmation, then file/update + +## Phase 1: Discovery — Collect Recent Builds + +**Start from builds, not PRs.** This is faster, gives access to commit SHAs for rerun detection, and captures builds for PRs that may already be closed. + +### Step 1.1: List recent PR-validation builds + +Use the `az` CLI to get builds from the last 7 days. The macios CI runs on `devdiv.visualstudio.com/DevDiv`. + +```bash +# Get the date 7 days ago in ISO format +SINCE=$(python3 -c "from datetime import datetime, timedelta; print((datetime.utcnow() - timedelta(days=7)).strftime('%Y-%m-%dT%H:%M:%SZ'))") + +# List recent builds for the PR pipeline +az pipelines build list \ + --org https://devdiv.visualstudio.com \ + --project DevDiv \ + --reason pullRequest \ + --result failed \ + --top 200 \ + -o json > /tmp/postmortem_builds.json +``` + +Also fetch partially succeeded builds (these contain test failures): + +```bash +az pipelines build list \ + --org https://devdiv.visualstudio.com \ + --project DevDiv \ + --reason pullRequest \ + --result partiallySucceeded \ + --top 200 \ + -o json > /tmp/postmortem_builds_partial.json +``` + +### Step 1.2: Parse and filter builds + +```python +import json +from datetime import datetime, timedelta, timezone + +since = datetime.now(timezone.utc) - timedelta(days=7) + +def load_builds(path): + with open(path) as f: + content = f.read() + return json.JSONDecoder().raw_decode(content)[0] + +builds = load_builds('/tmp/postmortem_builds.json') + load_builds('/tmp/postmortem_builds_partial.json') + +# Filter to last 7 days and macios pipelines +recent = [] +for b in builds: + finish = b.get('finishTime', '') + if not finish: + continue + ft = datetime.fromisoformat(finish.replace('Z', '+00:00')) + if ft < since: + continue + # Only include macios pipelines + defn = b.get('definition', {}).get('name', '') + if 'macios' not in defn.lower() and 'xamarin-macios' not in defn.lower(): + continue + recent.append({ + 'id': b['id'], + 'result': b['result'], + 'pr': b.get('triggerInfo', {}).get('pr.number', ''), + 'sourceBranch': b.get('sourceBranch', ''), + 'sourceVersion': b.get('sourceVersion', ''), # commit SHA — critical for rerun detection + 'pipeline': defn, + 'finishTime': finish, + }) + +print(f"Found {len(recent)} builds from {len(set(b['pr'] for b in recent if b['pr']))} PRs") +``` + +### Step 1.3: Group builds for rerun detection + +Group by `(pr, pipeline, sourceVersion)`. Multiple builds with the same commit SHA for the same PR/pipeline are reruns. + +```python +from collections import defaultdict + +# Group: (pr, pipeline, commitSHA) -> [builds] +groups = defaultdict(list) +for b in recent: + key = (b['pr'], b['pipeline'], b['sourceVersion']) + groups[key].append(b) + +# Also group by just (pr, pipeline) to see if new commits fixed things +pr_pipeline = defaultdict(list) +for b in recent: + key = (b['pr'], b['pipeline']) + pr_pipeline[key].append(b) +``` + +## Phase 2: Extraction — Get Failure Details + +For each failed/partiallySucceeded build, extract failure information. Use a SQL database to track failures across builds. + +### Step 2.1: Set up failure tracking + +```sql +CREATE TABLE IF NOT EXISTS ci_failures ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + build_id INTEGER, + pr TEXT, + pipeline TEXT, + commit_sha TEXT, + finish_time TEXT, + job_name TEXT, + failure_type TEXT, -- 'TestFailure', 'BuildFailure', 'TimedOut', 'Crashed', 'Infrastructure' + test_fullname TEXT, -- e.g. 'MonoTouchFixtures.SomeTest.TestMethod' + platform TEXT, -- e.g. 'ios', 'tvos', 'macos', 'maccatalyst' + config TEXT, -- e.g. 'Debug (ARM64)', 'Release (x64)' + error_signature TEXT, -- normalized error message / top stack frame + raw_message TEXT +); +``` + +### Step 2.2: For each build, get the timeline and TestSummary artifacts + +Only process builds with failures. For efficiency, first check the timeline for failed jobs, then only download artifacts for those jobs. + +```bash +# Get timeline +az devops invoke --area build --resource timeline \ + --route-parameters project=DevDiv buildId= \ + --org https://devdiv.visualstudio.com -o json > /tmp/timeline_.json +``` + +Parse the timeline to find failed jobs: + +```python +import json + +with open(f'/tmp/timeline_{build_id}.json') as f: + data = json.JSONDecoder().raw_decode(f.read())[0] + +failed_jobs = [] +for r in data.get('records', []): + if r.get('type') == 'Job' and r.get('result') == 'failed': + failed_jobs.append({ + 'name': r['name'], + 'id': r['id'], + 'logId': r.get('log', {}).get('id'), + }) +``` + +### Step 2.3: Download TestSummary artifacts (fast triage) + +TestSummary artifacts are small and quick to download. Use them first to identify which jobs failed: + +```bash +artifact="TestSummary-simulator_tests-1" +mkdir -p "/tmp/postmortem/${build_id}/${artifact}" +az pipelines runs artifact download \ + --artifact-name "$artifact" \ + --path "/tmp/postmortem/${build_id}/${artifact}" \ + --run-id \ + --org https://devdiv.visualstudio.com --project DevDiv +``` + +Parse the TestSummary.md to determine which jobs have test failures. This is the first-pass filter. + +### Step 2.4: Download HtmlReport artifacts (deep analysis) + +**This is the most time-consuming step — minimize downloads aggressively.** + +Each test run produces an HtmlReport artifact (60-140MB zip) containing: +- `tests/index.html` — Main report with all test configurations, pass/fail, inline failure details +- `tests///test--.xml` — NUnit XML with individual test-case results +- `tests///results-.xml` — NUnit results for dotnettests + +**CRITICAL: Only download HtmlReport zips for jobs where TestSummary shows TEST failures (❌ markers).** Do NOT download HtmlReports for: +- Build failures (no test results exist — the build didn't get far enough to run tests) +- Infrastructure failures (bot provisioning, timeout, etc.) +- Jobs where TestSummary shows all tests passed (the job may have failed for other reasons) + +To find exact artifact names, first list artifacts for the build: +```bash +az pipelines runs artifact list --run-id \ + --org https://devdiv.visualstudio.com --project DevDiv -o json +``` + +Then download only matching HtmlReport artifacts for jobs with test failures: +```bash +az pipelines runs artifact download \ + --artifact-name "HtmlReport--1" \ + --path "/tmp/postmortem_deep/" \ + --run-id \ + --org https://devdiv.visualstudio.com --project DevDiv +``` + +**Performance note:** Each download takes 1-3 minutes (sequential, no parallelism in az CLI). Downloading 500 artifacts takes ~2 hours. By filtering with TestSummary first, you can typically reduce this to 50-100 artifacts. + +### Step 2.5: Parse NUnit XML for individual test failures + +Extract individual test failures from the NUnit XML files inside the HtmlReport zips: + +```python +import zipfile, xml.etree.ElementTree as ET, html + +def extract_failures_from_nunit_xml(xml_content): + """Parse NUnit XML to extract individual failing test cases.""" + root = ET.fromstring(xml_content) + failures = [] + for tc in root.iter('test-case'): + if tc.get('result') == 'Failed': + name = tc.get('fullname', 'Unknown') + msg_el = tc.find('.//failure/message') + stack_el = tc.find('.//failure/stack-trace') + failures.append({ + 'test': name, + 'message': msg_el.text if msg_el is not None else '', + 'stack': stack_el.text[:500] if stack_el is not None else '', + }) + return failures + +# Process a zip file +with zipfile.ZipFile('/tmp/postmortem_deep/html_BUILDID_JOB.zip') as zf: + for name in zf.namelist(): + if name.endswith('.xml') and 'test-' in name and '-clean' not in name: + xml_content = zf.read(name).decode('utf-8', errors='replace') + failures = extract_failures_from_nunit_xml(xml_content) +``` + +**Important**: Skip files ending in `-clean.xml` (these are filtered versions). The root XML tag is `TouchUnitTestRun` (not standard NUnit format, but `test-case` elements follow standard structure). + +For **dotnettests**, individual test failures are listed inline in `
  • ` tags in the HTML (not in separate XML). Parse these from `tests/index.html`: + +```python +import re +# Pattern for inline test failures in dotnettests HTML +failures_in_html = re.findall(r']*>([^<]*(?:Failed|Error)[^<]*)
  • ', html_content) +``` + +### Step 2.6: Handle crashes and build failures + +When a test runner crashes (exit code 134, etc.) or a build fails before tests run, there will be **no NUnit XML results**. These appear in the HTML as: +- `Test run crashed (exit code: NNN)` +- `BuildFailure` + +Capture these from the HTML and record them as separate failure types (CRASH, BUILD_FAILURE). + +### Step 2.6a: Collect detailed information for build failures + +For any failure that involves a **build error** (a test suite that fails to build, or a unit test that builds something and the build fails), collect as much detail as possible: + +#### 1. Extract specific build error messages + +When the NUnit failure message says something like `'dotnet build' failed with exit code 1`, that alone is not useful. Look for the actual compiler/linker/MSBuild errors in: +- The NUnit failure `message` and `stack-trace` elements (sometimes the full build output is captured there) +- The HtmlReport `index.html` — build errors are often shown inline +- The build step log (download via `az devops invoke --area build --resource logs`) + +Look for patterns like: +- `error CS####:` (C# compiler errors) +- `error MT####:` / `error MM####:` (mtouch/mmp errors) +- `error MSB####:` (MSBuild errors) +- `error IL####:` (ILLink/trimmer errors) +- `error NETSDK####:` (SDK errors) + +#### 2. Collect binlogs when available + +Binlog files (`.binlog`) contain the full MSBuild log and are invaluable for diagnosing build failures. They are often available as build artifacts. + +```bash +# List artifacts to find binlog-related ones +az pipelines runs artifact list --run-id \ + --org https://devdiv.visualstudio.com --project DevDiv -o json \ + | python3 -c "import json,sys; [print(a['name']) for a in json.load(sys.stdin) if 'binlog' in a['name'].lower() or 'Binlog' in a['name']]" +``` + +If binlogs are inside the HtmlReport zip (common path: `tests///*.binlog` or referenced in test output), extract them. + +Binlogs may also be embedded in test failure messages or stack traces as file paths — note these paths for reference. + +#### 3. Attach binlogs to issues + +When filing an issue for a build failure: +- Download the relevant binlog file +- Zip it (GitHub doesn't allow `.binlog` attachments, but `.zip` is fine) +- Attach the zipped binlog to the issue using `gh issue comment` with the `--attach` flag, or by uploading via the GitHub API + +```bash +# Download a binlog artifact +az pipelines runs artifact download \ + --artifact-name "" \ + --path "/tmp/postmortem_binlogs/" \ + --run-id \ + --org https://devdiv.visualstudio.com --project DevDiv + +# Zip it for attachment +zip /tmp/postmortem_binlogs/build_.binlog.zip /tmp/postmortem_binlogs/*.binlog + +# Attach to issue (if the gh CLI version supports --attach, otherwise note the link) +``` + +#### 4. Include build errors in the issue body + +Always include the specific build error messages in the issue body. Example: + +```markdown +### Build Errors + +The `dotnet build` step failed with the following errors: + +``` +error CS8602: Dereference of a possibly null reference. [src/Foo/Bar.csproj] +error MT0099: No platform assembly! [src/Baz/Qux.csproj] +``` + +**Binlog:** [build_14017033.binlog.zip](link-to-attachment) (attached) +``` + +This makes the issue actionable without requiring the reader to navigate through AzDO build logs. + +### Step 2.7: For infrastructure/setup failures without TestSummary + +Check the timeline for failed tasks in setup/provisioning stages. Extract error info from task log lines: + +```bash +az devops invoke --area build --resource logs \ + --route-parameters project=DevDiv buildId= logId= \ + --org https://devdiv.visualstudio.com -o json > /tmp/log__.json +``` + +Search for infrastructure-related errors: +- "Provision" failures +- "Reserve bot" failures +- Network/timeout errors +- Xcode installation issues + +### Step 2.8: Normalize failure signatures + +Create a normalized signature for deduplication. **Important:** HTML entities in test names (e.g., `"` vs `"`) must be normalized to avoid duplicate entries: + +```python +import html as html_lib + +def normalize_signature(failure_type, test_fullname, error_msg, platform): + """Create a stable key for grouping the same logical failure.""" + # Normalize HTML entities + if test_fullname: + test_fullname = html_lib.unescape(test_fullname) + return f"{failure_type}|{platform}|{test_fullname}" + elif error_msg: + error_msg = html_lib.unescape(error_msg) + import re + normalized = re.sub(r'/[^\s:]+/', '.../', error_msg) + normalized = re.sub(r'line \d+', 'line N', normalized) + normalized = re.sub(r'\d{4}-\d{2}-\d{2}T[\d:.]+Z?', 'TIMESTAMP', normalized) + return f"{failure_type}|{platform}|{normalized[:200]}" + return f"{failure_type}|{platform}|unknown" +``` + +## Phase 3: Classification + +Query the failure database to classify each unique failure. + +### Step 3.1: Identify flaky tests (same commit, different outcomes) + +A failure is **flaky** if the same PR + pipeline + commit SHA has both failing and succeeding builds, OR if a rerun of the exact same configuration passes. + +```sql +-- Find failures where the same commit had a passing build too +-- (builds that aren't in our failure DB were successful) +SELECT DISTINCT error_signature, test_fullname, platform, + COUNT(DISTINCT build_id) as fail_count, + COUNT(DISTINCT pr) as pr_count, + GROUP_CONCAT(DISTINCT pr) as prs +FROM ci_failures +GROUP BY error_signature +HAVING COUNT(DISTINCT build_id) > 0; +``` + +Cross-reference with the build groups from Phase 1: if a `(pr, pipeline, commitSHA)` group has multiple builds and at least one succeeded (not in the failure DB), then failures in the failing builds for that group are flaky. + +### Step 3.2: Identify shared regressions (same failure across unrelated PRs) + +```sql +-- Failures appearing across 2+ unrelated PRs +SELECT error_signature, test_fullname, platform, failure_type, + COUNT(DISTINCT pr) as pr_count, + COUNT(DISTINCT build_id) as build_count, + GROUP_CONCAT(DISTINCT pr) as affected_prs +FROM ci_failures +WHERE pr != '' +GROUP BY error_signature +HAVING COUNT(DISTINCT pr) >= 2 +ORDER BY pr_count DESC; +``` + +If the failure is NOT also identified as flaky (i.e., it doesn't go away on rerun), classify it as a **shared regression**. + +### Step 3.3: Identify infrastructure failures and bot-specific issues + +#### 3.3a: Extract worker/bot info from timelines + +The timeline records contain `workerName` for each Job. Extract this to correlate failures with specific bots: + +```python +for record in timeline['records']: + if record['type'] == 'Job': + worker = record.get('workerName', '') + # Windows bots: "VSM-XAM-126" (no dot suffix) + # macOS bots: "VSM-XAM-56.Sequoia.arm64", "VSCXSDKs-MINI-042.Tahoe.arm64" +``` + +#### 3.3b: Identify bot-specific failures + +Group failures by worker and compute failure rates. A bot is problematic if: +- It has a disproportionate failure rate compared to other bots running the same job type +- The same error message appears on the same bot across multiple unrelated PRs + +```python +# Example: if VSM-XAM-126 has 8/18 failed jobs (44%) while other bots average 5-10%, +# that bot has a specific problem worth filing an issue for. +``` + +#### 3.3c: Windows integration stage — identify the macOS bot + +The 'Windows integration' stage has three jobs that work together: +1. **Reserve macOS bot for tests** — reserves a macOS bot and records its name +2. **Dotnet tests** — runs on a Windows bot, connecting to the reserved macOS bot via ssh +3. **Re-enable macOS bot for tests** — releases the macOS bot + +If **any** job in this stage fails, always extract the macOS bot name from the 'Reserve macOS bot for tests' job's `workerName` and include it in the issue. This is critical because: +- A 'Verify ssh connection' failure on the Windows bot is really a problem with the **macOS bot** it's trying to reach +- A 'Download secrets' failure on the macOS bot is specific to that bot +- Correlating the macOS bot name across issues reveals patterns (e.g., VSM-XAM-13 having persistent problems) + +```python +# For any failure in the Windows integration stage: +# 1. Find the 'Reserve macOS bot for tests' job in the timeline +# 2. Extract its workerName — this is the macOS bot +# 3. Include "macOS bot: " in the issue, even if the +# failure is in the 'Dotnet tests' job running on a Windows bot +for record in timeline['records']: + if record['type'] == 'Job' and 'Reserve' in record.get('name', '') and 'macOS' in record.get('name', ''): + macos_bot = record.get('workerName', 'unknown') + break +``` + +#### 3.3d: Identify infrastructure failure patterns + +Also look for cross-bot patterns that affect many PRs: +- **Timeouts**: jobs that time out on multiple different bots across unrelated PRs +- **REST API failures**: `Intermittent failure attempting to call the restapis` across many PRs +- **Provisioning failures**: `Reserve bot`, `provision` errors +- **Workload install failures**: `Install dotnet workloads` failing + +**CRITICAL: Always identify the FIRST failed step as the root cause.** In any failed job, only the first step with `result == 'failed'` (and without `continueOnError: true`) is the root cause. All subsequent failures in the same job are cascading effects and must NOT be reported as separate issues. Common cascading patterns: +- `Publish Artifact: TestSummary/HtmlReport` → reports `Path does not exist` because tests never ran +- `Prepare tests results and Html Report` → fails because earlier steps didn't produce results +- Any step after a failed `Checkout`, `Verify ssh connection`, `Download secrets`, or `Install dotnet workloads` + +To find the actual root cause in a failed job: +1. List all Task records under the job sorted by execution order +2. Find the **first** task with `result == 'failed'` +3. Verify this task does NOT have `continueOnError: true` — if it does, skip it and check the next failed task +4. That task is the root cause; all later failures in the same job are cascading +5. **Never file an issue for a cascading failure** — always file for the root cause step + +```sql +SELECT error_signature, failure_type, raw_message, + COUNT(DISTINCT build_id) as occurrences +FROM ci_failures +WHERE failure_type = 'Infrastructure' + OR raw_message LIKE '%provision%' + OR raw_message LIKE '%reserve bot%' + OR raw_message LIKE '%timeout%' + OR raw_message LIKE '%Intermittent failure%' + OR raw_message LIKE '%Path does not exist%' +GROUP BY error_signature +ORDER BY occurrences DESC; +``` + +### Step 3.4: Exclude known-noisy and PR-specific failures + +**Always exclude these tests** — they are expected to fail across many PRs and are not actionable: +- `Xamarin.Tests.AppSizeTest.*` — sensitive to any API change, expected cross-PR failures + +A failure is PR-specific if: +- It appears in only 1 PR +- It persists across commits within that PR (not a rerun flake) +- It is consistent (never passes on rerun) + +These should be **excluded** from issue filing — they are the PR author's problem. + +### Step 3.5: File one issue per test + +**Always create separate issues for separate unit tests.** It is easier to merge issues than to split them up. Do not group multiple unrelated test failures into a single issue. + +### Step 3.5: Produce classification summary + +Create a summary table for user review: + +``` +| Category | Signature (truncated) | Test/Error | Platform | PRs Affected | Occurrences | +|--------------------|--------------------------------|---------------------|-------------|-------------- |-------------| +| Flaky | TestFailure|ios|Mono...Test | SomeTest.Method | ios | 5 | 8 | +| Shared Regression | BuildFailure|macos|error CS... | (build error) | macos | 3 | 3 | +| Infrastructure | Infrastructure|*|provision... | Bot provisioning | all | 4 | 4 | +``` + +## Phase 4: Issue Actions + +### Step 4.1: Search for existing issues + +For each classified failure, search for an existing GitHub issue: + +```bash +# Search by test name or error signature in issue title +gh issue list --repo dotnet/macios --state open \ + --search "" \ + --label "ci-postmortem" --json number,title,labels,url +``` + +Also search closed issues (may need reopening): + +```bash +gh issue list --repo dotnet/macios --state closed \ + --search "" \ + --label "ci-postmortem" --json number,title,labels,url +``` + +### Step 4.2: Decide whether to reopen closed issues + +When a matching **closed** issue is found, apply these rules to decide whether to reopen it: + +1. **Check the close reason.** Read the issue body/comments to determine *why* it was closed: + - **Fix merged** — a code change was merged to fix the problem. + - **Lack of information** — closed because there wasn't enough data to act on. + - **Debug instrumentation merged** — a PR was merged to gather more diagnostic info. + +2. **If closed because a fix was merged:** + - **Do NOT reopen if the issue was closed less than 2 weeks ago.** The failing builds in the analysis window likely predate the fix. Comment on the closed issue with the analysis results and note why it's not being reopened. + - **Do NOT reopen unless the new failing build is from the `main` branch** (or targets `main` via a PR that incorporates the fix commit). Builds from older branches or PRs that branched before the fix don't count. + - **After 2 weeks**, if the failure is still appearing in builds that incorporate the fix, reopen the issue. + +3. **If closed for lack of information:** reopen if the new analysis provides that missing information. + +4. **If closed because debug instrumentation was merged:** reopen if any of the failing builds provide the additional diagnostic data that was being collected. + +5. **Always OK to comment** on a closed issue with analysis data, even if not reopening. Include a note explaining why the issue is not being reopened (e.g., "Not reopening — the fix in #NNNN was merged on DATE, and all failing builds predate that fix."). + +### Step 4.3: Propose actions to the user + +Present a list of proposed actions **before executing any**. Use `ask_user` to get confirmation. + +For each failure, propose one of: +- **Create new issue** — no existing issue found +- **Comment on existing issue** — matching open issue found, add recent occurrence data +- **Reopen issue** — matching closed issue found, failure confirmed post-fix (see Step 4.2) +- **Comment on closed issue (no reopen)** — matching closed issue found, but reopen criteria not met +- **Skip** — user decides this isn't worth tracking + +Format the proposal clearly: + +``` +## Proposed Issue Actions + +### 1. Flaky: MonoTouchFixtures.NetworkTest.TestReachability (iOS) + - Seen in 5 PRs, 8 builds over the past week + - Disappears on rerun → flaky + - Existing issue: #12345 (open) — will add comment with recent data + - **Proposed action:** Comment on #12345 + +### 2. Shared Regression: error CS1234 in SomeFile.cs (macOS) + - Seen in 3 PRs, consistent (no rerun recovery) + - No existing issue found + - **Proposed action:** Create new issue + +### 3. Infrastructure: Bot provisioning timeout + - Seen in 4 builds across 4 PRs + - Existing issue: #11111 (closed) — last closed 2 months ago + - **Proposed action:** Reopen #11111 + +Proceed with these actions? [Confirm / Edit / Skip] +``` + +### Step 4.3: Execute confirmed actions + +#### Create new issue + +```bash +gh issue create --repo dotnet/macios \ + --title "[CI] Flaky: on " \ + --label "bug,CI,ci-postmortem,copilot,flaky-test" \ + --body "$(cat <<'EOF' +## Flaky Test Report (automated) + +**Test:** `` +**Platform:** +**Category:** Flaky / Shared Regression / Infrastructure +**Period:** to + +### Occurrence Summary + +| PR | Build | Bot | Direct Link | +|----|-------|-----|-------------| +| # | | | []() | + +**Total:** Failed in builds across PRs + +**Deep links:** Always link to the specific job and step/task, not just the build. Use the AzDO URL format: +`https://devdiv.visualstudio.com/DevDiv/_build/results?buildId=BUILD_ID&view=logs&j=JOB_RECORD_ID&t=TASK_RECORD_ID` + +The `j=` (job) and `t=` (task) parameters are the `id` fields from the timeline records. This takes the reader directly to the failing log rather than requiring them to click through multiple jobs. + +### Error Details + +Include the **specific error messages** from the NUnit XML failure messages. If the failure is a build error, include the actual compiler/linker error codes and messages. If different PRs/builds show different error messages for the same test, list them separately — they may be different root causes. + +For **build failures** specifically, always include: +1. The actual build error messages (error codes like CS####, MT####, IL####, MSB####) +2. Links to or attachments of binlog files (zipped) when available +3. The full `dotnet build` command that failed (from the test failure message) + +``` + + + +``` + +If different builds have different errors for the same test, show each variant: + +**Variant A** (builds ): +``` + +``` + +**Variant B** (builds ): +``` + +``` + +**Important:** If different PRs show different error messages for the "same" test failure, they are likely **different root causes** and should be investigated separately. Consider splitting into separate issues or noting that the grouping may be incorrect. + +### Classification + +This failure was identified as **flaky** because: +- It appeared across unrelated PRs +- It disappeared on rerun in cases + +--- +*This issue was automatically generated by CI post-mortem analysis.* +EOF +)" +``` + +All issues **must** have the `ci-postmortem` and `copilot` labels. Additionally use `flaky-test` for flaky tests and `infrastructure` for infra issues. + +#### Comment on existing issue + +```bash +gh issue comment --repo dotnet/macios --body "$(cat <<'EOF' +## CI Post-Mortem Update () + +This failure was seen again in the past week: + +| PR | Build | Date | Outcome | +|----|-------|------|---------| +| # | | | Failed | +... + +Total: occurrences across PRs this week. +EOF +)" +``` + +#### Reopen closed issue + +```bash +gh issue reopen --repo dotnet/macios +gh issue comment --repo dotnet/macios --body "Reopening — this failure recurred in builds this week. See details below. +..." +``` + +## Important Notes + +### Efficiency + +- Process builds in batches. Don't download artifacts for every build — first check the timeline for failed jobs. +- Use the SQL database to accumulate results incrementally. You can query it between phases. +- Skip builds older than 7 days early in the pipeline. + +### Accuracy + +- **Rerun detection requires matching commit SHA.** A newer commit on the same PR that passes does NOT prove flakiness — the new commit may have fixed the issue. +- **Verify the same job/config ran** before concluding a failure "went away." The test matrix can vary between runs. +- **Don't conflate platforms.** A test failing on iOS and macOS should be tracked separately unless the error signature is identical. + +### Rate Limiting + +- AzDO API calls are subject to rate limits. Add small delays between artifact downloads if processing many builds. +- `gh` CLI may also rate-limit. Batch issue searches where possible. + +### Confirmation + +- **Never file or modify issues without user confirmation.** Always present the classification summary and proposed actions first. +- Let the user edit the proposals (e.g., skip certain failures, change labels, adjust titles). diff --git a/.agents/skills/macios-ci-postmortem/references/azure-devops-cli.md b/.agents/skills/macios-ci-postmortem/references/azure-devops-cli.md new file mode 100644 index 000000000000..8468d08b5598 --- /dev/null +++ b/.agents/skills/macios-ci-postmortem/references/azure-devops-cli.md @@ -0,0 +1,95 @@ +# Azure DevOps CLI Reference for macios CI + +## Authentication + +The `az devops` CLI must be authenticated. Typically this is done via: +```bash +az devops configure --defaults organization=https://devdiv.visualstudio.com project=DevDiv +``` + +Or by passing `--org` and `--project` on each command. + +## Key Commands + +### Build metadata +```bash +az pipelines build show --id -o json +``` +Returns: result, status, sourceBranch, definition, requestedFor, startTime, finishTime. + +### Build timeline (jobs and tasks) +```bash +az devops invoke --area build --resource timeline \ + --route-parameters project=DevDiv buildId= \ + --org https://devdiv.visualstudio.com -o json +``` +Returns: records array with type (Stage/Job/Task), name, result, state, log.id, parentId. + +**Important:** `az pipelines build log list` is NOT a valid command. Use the `az devops invoke` approach above. + +### Task logs +```bash +az devops invoke --area build --resource logs \ + --route-parameters project=DevDiv buildId= logId= \ + --org https://devdiv.visualstudio.com -o json +``` +Returns: value array of log line strings. + +### Artifact listing +```bash +az pipelines runs artifact list --run-id -o json +``` + +### Artifact download +```bash +az pipelines runs artifact download \ + --artifact-name "" \ + --path /tmp/ci-artifacts/ \ + --run-id +``` + +## Common Pipeline Names + +- `xamarin-macios-sim-pr-tests` — PR validation with simulator tests +- Other pipeline names may vary; check `definition.name` from build show. + +## Common Job Names in Timeline + +- `T: monotouch_ios` — iOS monotouch tests +- `T: monotouch_tvos` — tvOS monotouch tests +- `macOS tests` — macOS and Mac Catalyst tests +- `Reserve macOS bot for tests` — bot provisioning +- Various build/packaging jobs + +## JSON Parsing Caveat + +`az devops invoke` output may include trailing non-JSON text. Always parse with: +```python +import json +with open('file.json', 'r') as f: + content = f.read() +data = json.JSONDecoder().raw_decode(content)[0] +``` + +Do NOT use `json.loads(content)` directly — it will fail on the trailing text. + +## Test Artifact Names + +TestSummary and HtmlReport artifacts follow a naming convention: +- `TestSummary-simulator_tests-1` — Markdown summary with pass/fail counts and failure details +- `HtmlReport-simulator_tests-1` — ZIP containing HTML report and NUnit XML files + +Common job names: +- `monotouch_ios`, `monotouch_tvos`, `monotouch_macos`, `monotouch_maccatalyst` +- `dotnettests_ios`, `dotnettests_tvos`, `dotnettests_macos`, `dotnettests_maccatalyst` +- `cecil`, `framework`, `xtro`, `msbuild`, `generator`, `sharpie`, `fsharp`, `linker` +- `introspection`, `xcframework`, `interdependent_binding_projects` + +**Important:** Each artifact download overwrites `TestSummary.md` in the target directory. Always download to separate subdirectories named after the artifact. + +## Key Investigation Strategy + +1. **Start with TestSummary artifacts** — they are the fastest way to identify what failed and why. Raw task logs are 40K+ lines and don't contain standard NUnit patterns inline. +2. **For test failures (not build failures)**, download HtmlReport artifacts and parse the NUnit XML files inside for exact test names, assertions, and stack traces. +3. **Only use raw task logs** when you need build error details (MSB/CS/NU errors) or infrastructure error context. +4. **Map timeline logIds to jobs** using the `parentId` field to trace task → job relationships. diff --git a/.github/agents/agentic-workflows.agent.md b/.github/agents/agentic-workflows.agent.md new file mode 100644 index 000000000000..f7e5eb4f1cd1 --- /dev/null +++ b/.github/agents/agentic-workflows.agent.md @@ -0,0 +1,236 @@ +--- +description: GitHub Agentic Workflows (gh-aw) - Create, debug, and upgrade AI-powered workflows with intelligent prompt routing +disable-model-invocation: true +--- + +# GitHub Agentic Workflows Agent + +This agent helps you work with **GitHub Agentic Workflows (gh-aw)**, a CLI extension for creating AI-powered workflows in natural language using markdown files. + +## What This Agent Does + +This is a **dispatcher agent** that routes your request to the appropriate specialized prompt based on your task: + +- **Creating new workflows**: Routes to `create` prompt +- **Updating existing workflows**: Routes to `update` prompt +- **Debugging workflows**: Routes to `debug` prompt +- **Upgrading workflows**: Routes to `upgrade-agentic-workflows` prompt +- **Creating report-generating workflows**: Routes to `report` prompt — consult this whenever the workflow posts status updates, audits, analyses, or any structured output as issues, discussions, or comments +- **Creating shared components**: Routes to `create-shared-agentic-workflow` prompt +- **Fixing Dependabot PRs**: Routes to `dependabot` prompt — use this when Dependabot opens PRs that modify generated manifest files (`.github/workflows/package.json`, `.github/workflows/requirements.txt`, `.github/workflows/go.mod`). Never merge those PRs directly; instead update the source `.md` files and rerun `gh aw compile --dependabot` to bundle all fixes +- **Analyzing test coverage**: Routes to `test-coverage` prompt — consult this whenever the workflow reads, analyzes, or reports on test coverage data from PRs or CI runs +- **Rendering ASCII charts in markdown**: Routes to `asciicharts` guide — consult this whenever the workflow needs compact charts that render reliably in GitHub issues, comments, or discussions +- **CLI commands and triggering workflows**: Routes to `cli-commands` guide — consult this whenever the user asks how to run, compile, debug, or manage workflows from the command line, or when they need the MCP tool equivalent of a `gh aw` command +- **Reducing token consumption / cost optimization**: Routes to `token-optimization` guide — consult this whenever the user asks how to reduce token usage, lower costs, speed up workflows, or measure the impact of prompt changes with experiments +- **Choosing workflow architectures and design patterns**: Routes to `patterns` guide — consult this whenever the user asks for strategy, architecture, operating models, or pattern selection for agentic workflows + +> [!IMPORTANT] +> For architecture/pattern-selection requests, load `https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/patterns.md` first. + +Workflows may optionally include: + +- **Project tracking / monitoring** (GitHub Projects updates, status reporting) +- **Orchestration / coordination** (one workflow assigning agents or dispatching and coordinating other workflows) + +## Files This Applies To + +- Workflow files: `.github/workflows/*.md` and `.github/workflows/**/*.md` +- Workflow lock files: `.github/workflows/*.lock.yml` +- Shared components: `.github/workflows/shared/*.md` +- Configuration: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/github-agentic-workflows.md + +## Problems This Solves + +- **Workflow Creation**: Design secure, validated agentic workflows with proper triggers, tools, and permissions +- **Workflow Debugging**: Analyze logs, identify missing tools, investigate failures, and fix configuration issues +- **Version Upgrades**: Migrate workflows to new gh-aw versions, apply codemods, fix breaking changes +- **Component Design**: Create reusable shared workflow components that wrap MCP servers + +## How to Use + +When you interact with this agent, it will: + +1. **Understand your intent** - Determine what kind of task you're trying to accomplish +2. **Route to the right prompt** - Load the specialized prompt file for your task +3. **Execute the task** - Follow the detailed instructions in the loaded prompt + +## Available Prompts + +### Create New Workflow +**Load when**: User wants to create a new workflow from scratch, add automation, or design a workflow that doesn't exist yet + +**Prompt file**: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/create-agentic-workflow.md + +**Use cases**: +- "Create a workflow that triages issues" +- "I need a workflow to label pull requests" +- "Design a weekly research automation" + +### Update Existing Workflow +**Load when**: User wants to modify, improve, or refactor an existing workflow + +**Prompt file**: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/update-agentic-workflow.md + +**Use cases**: +- "Add web-fetch tool to the issue-classifier workflow" +- "Update the PR reviewer to use discussions instead of issues" +- "Improve the prompt for the weekly-research workflow" + +### Debug Workflow +**Load when**: User needs to investigate, audit, debug, or understand a workflow, troubleshoot issues, analyze logs, or fix errors + +**Prompt file**: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/debug-agentic-workflow.md + +**Use cases**: +- "Why is this workflow failing?" +- "Analyze the logs for workflow X" +- "Investigate missing tool calls in run #12345" + +### Upgrade Agentic Workflows +**Load when**: User wants to upgrade workflows to a new gh-aw version or fix deprecations + +**Prompt file**: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/upgrade-agentic-workflows.md + +**Use cases**: +- "Upgrade all workflows to the latest version" +- "Fix deprecated fields in workflows" +- "Apply breaking changes from the new release" + +### Create a Report-Generating Workflow +**Load when**: The workflow being created or updated produces reports — recurring status updates, audit summaries, analyses, or any structured output posted as a GitHub issue, discussion, or comment + +**Prompt file**: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/report.md + +**Use cases**: +- "Create a weekly CI health report" +- "Post a daily security audit to Discussions" +- "Add a status update comment to open PRs" + +### Create Shared Agentic Workflow +**Load when**: User wants to create a reusable workflow component or wrap an MCP server + +**Prompt file**: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/create-shared-agentic-workflow.md + +**Use cases**: +- "Create a shared component for Notion integration" +- "Wrap the Slack MCP server as a reusable component" +- "Design a shared workflow for database queries" + +### Fix Dependabot PRs +**Load when**: User needs to close or fix open Dependabot PRs that update dependencies in generated manifest files (`.github/workflows/package.json`, `.github/workflows/requirements.txt`, `.github/workflows/go.mod`) + +**Prompt file**: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/dependabot.md + +**Use cases**: +- "Fix the open Dependabot PRs for npm dependencies" +- "Bundle and close the Dependabot PRs for workflow dependencies" +- "Update @playwright/test to fix the Dependabot PR" + +### Analyze Test Coverage +**Load when**: The workflow reads, analyzes, or reports test coverage — whether triggered by a PR, a schedule, or a slash command. Always consult this prompt before designing the coverage data strategy. + +**Prompt file**: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/test-coverage.md + +**Use cases**: +- "Create a workflow that comments coverage on PRs" +- "Analyze coverage trends over time" +- "Add a coverage gate that blocks PRs below a threshold" + +### Render ASCII Charts in Markdown +**Load when**: The workflow needs in-markdown charts (sparklines, bars, table+trend views) that must align cleanly and render reliably across GitHub surfaces, including mobile. + +**Reference file**: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/asciicharts.md + +**Use cases**: +- "Show a compact trend chart in an issue comment" +- "Render a dashboard table with sparkline trends" +- "Generate aligned ASCII bars for service metrics" + +### CLI Commands Reference +**Load when**: The user asks how to run, compile, debug, or manage workflows from the command line; needs the MCP tool equivalent of a `gh aw` command; or is in a restricted environment (e.g., Copilot Cloud) without direct CLI access. + +**Reference file**: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/cli-commands.md + +**Use cases**: +- "How do I trigger workflow X on the main branch?" +- "What's the MCP equivalent of `gh aw logs`?" +- "I'm in Copilot Cloud — how do I compile a workflow?" +- "Show me all available gh aw commands" + +### Token Consumption Optimization +**Load when**: The user asks how to reduce token usage, lower workflow costs, make a workflow faster or cheaper, or measure the impact of prompt or configuration changes. + +**Reference file**: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/token-optimization.md + +**Use cases**: +- "How do I reduce the token cost of this workflow?" +- "My workflow is too expensive — how do I optimize it?" +- "How do I compare token usage between two runs?" +- "Should I use gh-proxy or the MCP server?" +- "How do I use sub-agents to reduce costs?" +- "How do I measure the impact of a prompt change?" + +### Workflow Pattern Selection +**Load when**: The user asks for architecture, strategy, operating model selection, or pattern recommendations for building agentic workflows. + +**Reference file**: https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/patterns.md + +**Use cases**: +- "Which pattern should I use for multi-repo rollout?" +- "How should I structure this workflow architecture?" +- "What pattern fits slash-command triage?" +- "Should this be DispatchOps or DailyOps?" + +## Instructions + +When a user interacts with you: + +1. **Identify the task type** from the user's request +2. **Load the appropriate prompt** from the GitHub repository URLs listed above +3. **Follow the loaded prompt's instructions** exactly +4. **If uncertain**, ask clarifying questions to determine the right prompt + +## Quick Reference + +```bash +# Initialize repository for agentic workflows +gh aw init + +# Generate the lock file for a workflow +gh aw compile [workflow-name] + +# Trigger a workflow on demand (preferred over gh workflow run) +gh aw run # interactive input collection +gh aw run --ref main # run on a specific branch + +# Debug workflow runs +gh aw logs [workflow-name] +gh aw audit + +# Upgrade workflows +gh aw fix --write +gh aw compile --validate +``` + +## Key Features of gh-aw + +- **Natural Language Workflows**: Write workflows in markdown with YAML frontmatter +- **AI Engine Support**: Copilot, Claude, Codex, or custom engines +- **MCP Server Integration**: Connect to Model Context Protocol servers for tools +- **Safe Outputs**: Structured communication between AI and GitHub API +- **Strict Mode**: Security-first validation and sandboxing +- **Shared Components**: Reusable workflow building blocks +- **Repo Memory**: Persistent git-backed storage for agents +- **Sandboxed Execution**: All workflows run in the Agent Workflow Firewall (AWF) sandbox, enabling full `bash` and `edit` tools by default + +## Important Notes + +- Always reference the instructions file at https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/github-agentic-workflows.md for complete documentation +- Use the MCP tool `agentic-workflows` when running in GitHub Copilot Cloud +- Workflows must be compiled to `.lock.yml` files before running in GitHub Actions +- **Bash tools are enabled by default** - Don't restrict bash commands unnecessarily since workflows are sandboxed by the AWF +- Follow security best practices: minimal permissions, explicit network access, no template injection +- **Network configuration**: Use ecosystem identifiers (`node`, `python`, `go`, etc.) or explicit FQDNs in `network.allowed`. Bare shorthands like `npm` or `pypi` are **not** valid. See https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/network.md for the full list of valid ecosystem identifiers and domain patterns. +- **Single-file output**: When creating a workflow, produce exactly **one** workflow `.md` file. Do not create separate documentation files (architecture docs, runbooks, usage guides, etc.). If documentation is needed, add a brief `## Usage` section inside the workflow file itself. +- **Triggering runs**: Always use `gh aw run ` to trigger a workflow on demand — not `gh workflow run .lock.yml`. `gh aw run` handles workflow resolution by short name, input parsing and validation, and correct run-tracking for agentic workflows. Use `--ref ` to run on a specific branch. +- **CLI commands reference**: For a complete guide on all `gh aw` commands and their MCP tool equivalents (for restricted environments), see https://github.com/github/gh-aw/blob/v0.74.8/.github/aw/cli-commands.md diff --git a/.github/aw/actions-lock.json b/.github/aw/actions-lock.json index e44fd6da3ec8..0edb6d2e41ac 100644 --- a/.github/aw/actions-lock.json +++ b/.github/aw/actions-lock.json @@ -1,17 +1,52 @@ { "entries": { + "actions/checkout@v6.0.2": { + "repo": "actions/checkout", + "version": "v6.0.2", + "sha": "de0fac2e4500dabe0009e67214ff5f5447ce83dd" + }, + "actions/download-artifact@v8.0.1": { + "repo": "actions/download-artifact", + "version": "v8.0.1", + "sha": "3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c" + }, "actions/github-script@v9.0.0": { "repo": "actions/github-script", "version": "v9.0.0", "sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3" }, - "github/gh-aw-actions/setup@v0.71.1": { + "actions/setup-node@v6.4.0": { + "repo": "actions/setup-node", + "version": "v6.4.0", + "sha": "48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e" + }, + "actions/upload-artifact@v7.0.1": { + "repo": "actions/upload-artifact", + "version": "v7.0.1", + "sha": "043fb46d1a93c77aae656e7c1c64a875d1fc6a0a" + }, + "github/gh-aw-actions/setup@v0.77.5": { "repo": "github/gh-aw-actions/setup", - "version": "v0.71.1", - "sha": "239aec45b78c8799417efdd5bc6d8cc036629ec1" + "version": "v0.77.5", + "sha": "3ea13c02d765410340d533515cb31a7eef2baaf0" } }, "containers": { + "ghcr.io/github/gh-aw-firewall/agent:0.25.41": { + "image": "ghcr.io/github/gh-aw-firewall/agent:0.25.41", + "digest": "sha256:cb2b565d070116d4b67e355775340528b5a2c3cb18b2c9049638bcc2df681770", + "pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.25.41@sha256:cb2b565d070116d4b67e355775340528b5a2c3cb18b2c9049638bcc2df681770" + }, + "ghcr.io/github/gh-aw-firewall/api-proxy:0.25.41": { + "image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.25.41", + "digest": "sha256:fadd0de387209f69a9a7a1b8722bb5e7fdfb80ba9749a5c60f0e4cd7582a74d0", + "pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.25.41@sha256:fadd0de387209f69a9a7a1b8722bb5e7fdfb80ba9749a5c60f0e4cd7582a74d0" + }, + "ghcr.io/github/gh-aw-firewall/squid:0.25.41": { + "image": "ghcr.io/github/gh-aw-firewall/squid:0.25.41", + "digest": "sha256:1260445d25968dbf3ae70143964177a0e5914cf2ce07a6117f7d3caec6c3e3c4", + "pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.25.41@sha256:1260445d25968dbf3ae70143964177a0e5914cf2ce07a6117f7d3caec6c3e3c4" + }, "ghcr.io/github/gh-aw-mcpg:v0.3.0": { "image": "ghcr.io/github/gh-aw-mcpg:v0.3.0", "digest": "sha256:9c2228324fb1f26f39dc9471612e530ae3efc3156dac05efb2e8d212878d454d", diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 4cb9965eaa88..618589332491 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -136,6 +136,10 @@ interface SomeClass { Located in `msbuild/` directory: - `Xamarin.MacDev.Tasks` - Shared Apple development tasks +### FileWrites + +If a target or task creates a file, that file must be added to the `FileWrites` item group. This ensures MSBuild's incremental clean can delete generated files. Additionally, if a target produces multiple output files, all of them should be listed in the target's `Outputs` attribute for correct incremental build behavior. + ### Project Templates Common project structure for Apple platform apps: @@ -336,4 +340,9 @@ try { } catch (Exception e) { // Code here } -``` \ No newline at end of file +``` + +## Git Branch Safety + +* When creating a branch from `origin/main` (for example `git checkout -b origin/main`), the new branch may be configured to track `origin/main` depending on how it is created and your Git configuration. In that case, a later `git push` or `git push origin` may try to push to `main`. +* To avoid accidentally pushing to main, use `git push -u origin ` for the first push so Git creates `origin/` and sets the branch's upstream safely. If you want to be completely explicit, use `git push origin :`. diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 5ace4600a1f2..13434fb1a2d8 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,6 +1,10 @@ -version: 2 updates: - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "weekly" +- cooldown: + default-days: 7 + directory: / + ignore: + - dependency-name: "github/gh-aw-actions/**" # Managed by gh aw compile. Version-locked to the gh-aw compiler; do not bump. + package-ecosystem: github-actions + schedule: + interval: weekly +version: 2 diff --git a/.github/skills/macios-reviewer/SKILL.md b/.github/skills/macios-reviewer/SKILL.md index 4e58caf65a61..196852d33fcd 100644 --- a/.github/skills/macios-reviewer/SKILL.md +++ b/.github/skills/macios-reviewer/SKILL.md @@ -97,6 +97,13 @@ Post your findings directly: If no issues found **and CI is green**, submit with at most one or two 💡 suggestions and a positive summary. Truly trivial PRs (dependency bumps, 1-line typo fixes) may have no inline comments. +**Review event to submit:** +- If there are ❌ **error** issues → submit as `REQUEST_CHANGES`. +- If there are no ❌ **error** issues (only warnings/suggestions or clean) → submit as `COMMENT`. +- **Never submit `APPROVE`.** + +This is especially important on re-reviews: if a previous review requested changes and those changes have been addressed, submitting a `COMMENT` review replaces the previous `REQUEST_CHANGES` state, clearing the "changes requested" flag on the PR. + **Copilot-authored PRs:** If the PR author is `Copilot` (the GitHub Copilot coding agent) and the verdict is ⚠️ Needs Changes or ❌ Reject, prefix the review summary with `@copilot ` so the comment automatically triggers Copilot to address the feedback. Do NOT add the prefix for ✅ LGTM verdicts. ## Comment format diff --git a/.github/skills/update-expected-app-size/SKILL.md b/.github/skills/update-expected-app-size/SKILL.md new file mode 100644 index 000000000000..1537c6cc59b2 --- /dev/null +++ b/.github/skills/update-expected-app-size/SKILL.md @@ -0,0 +1,126 @@ +--- +name: update-expected-app-size +description: >- + Download updated expected app size files from Azure DevOps CI artifacts for + the current branch. Use when app size tests fail in CI and the user wants to + update the expected files locally. Trigger on "update app size", "download + expected files", "fix app size test", or "update expected app size files". +--- + +# Update Expected App Size Files + +Download updated expected app size files from Azure DevOps artifacts for the current branch's PR build, and apply them to the repository. + +## When to Use + +- App size tests failed in CI and the user wants to update the expected files +- User asks to "update app size", "download expected files", or "fix app size test failures" +- User wants to pull the updated expected files from a recent CI build + +## Background + +The app size tests (`tests/dotnet/UnitTests/AppSizeTest.cs`) compare the built app's size and preserved APIs against expected files stored in `tests/dotnet/UnitTests/expected/`. When the test detects a difference and `WRITE_KNOWN_FAILURES` is not set, it writes the updated expected file to `$(Build.ArtifactStagingDirectory)/updated-expected-sizes/`, and a pipeline step publishes this directory as a build artifact. + +The artifact name follows the pattern `{uploadPrefix}updated-expected-sizes-{testPrefix}-{attempt}` (e.g., `updated-expected-sizes-dotnettests_ios-1`). Inside the artifact, files are named after the test variant: +- `{Platform}-{Variant}-size.txt` — e.g., `iOS-MonoVM-size.txt`, `iOS-MonoVM-interpreter-size.txt`, `iOS-NativeAOT-TrimmableStatic-size.txt`, `MacOSX-CoreCLR-Interpreter-size.txt` +- `{Platform}-{Variant}-preservedapis.txt` — e.g., `iOS-MonoVM-preservedapis.txt`, `MacCatalyst-MonoVM-interpreter-preservedapis.txt` + +The expected files on disk are at: +- `tests/dotnet/UnitTests/expected/{Platform}-{Variant}-size.txt` +- `tests/dotnet/UnitTests/expected/{Platform}-{Variant}-preservedapis.txt` + +## Workflow + +### 1. Determine the current branch and PR + +```bash +BRANCH=$(git branch --show-current) +# Find the PR number for this branch +gh pr list --head "$BRANCH" --repo dotnet/macios --json number,url --jq '.[0]' +``` + +If no PR is found, inform the user that this skill requires a PR to exist for the current branch (so that CI has run). + +### 2. Find the Azure DevOps build + +The CI builds for PRs in dotnet/macios run in the `devdiv` Azure DevOps organization, project `DevDiv`. + +Use the GitHub PR checks to find the Azure DevOps build URL: + +```bash +gh pr checks --repo dotnet/macios +``` + +Look for a check that links to Azure DevOps. The build URL will look like: +``` +https://devdiv.visualstudio.com/DevDiv/_build/results?buildId=XXXXXXX +``` + +Extract the `buildId` from the URL. + +### 3. Download the artifacts + +Use the Azure DevOps REST API to list and download artifacts: + +```bash +# List artifacts for the build +TOKEN=$(az account get-access-token --resource 499b84ac-1321-427f-aa17-267ca6975798 --query accessToken -o tsv) +curl -s "https://devdiv.visualstudio.com/DevDiv/_apis/build/builds/{buildId}/artifacts?api-version=7.0" \ + -H "Authorization: Bearer $TOKEN" +``` + +Look for artifacts whose names contain `updated-expected-sizes` (e.g., `updated-expected-sizes-dotnettests_ios-1`). Get the artifact's `downloadUrl` and download it: + +```bash +# Get the download URL for a specific artifact +ARTIFACT_INFO=$(curl -s "https://devdiv.visualstudio.com/DevDiv/_apis/build/builds/{buildId}/artifacts?artifactName={artifactName}&api-version=7.0" \ + -H "Authorization: Bearer $TOKEN") +DOWNLOAD_URL=$(echo "$ARTIFACT_INFO" | python3 -c "import sys,json; print(json.load(sys.stdin)['resource']['downloadUrl'])") + +# Download the artifact zip +curl -sL "$DOWNLOAD_URL" -H "Authorization: Bearer $TOKEN" -o artifact.zip +``` + +If `az` is not available or not authenticated, direct the user to download manually from the Azure DevOps build artifacts page. + +### 4. Place the files + +Extract the downloaded artifact zip and place the files in the expected directory: + +```bash +EXPECTED_DIR="tests/dotnet/UnitTests/expected" +unzip -o artifact.zip -d /tmp/updated-sizes/ +cp /tmp/updated-sizes/*/*.txt "$EXPECTED_DIR/" +``` + +The files inside the zip already have the correct names (e.g., `iOS-MonoVM-size.txt`) and can be copied directly. + +### 5. Verify and commit + +After placing the files: +1. Run `git diff` to show what changed +2. Ask the user if the changes look correct +3. If confirmed, commit the changes: + ```bash + git add tests/dotnet/UnitTests/expected/ + git commit -m "[tests] Update expected app size files" + ``` + +## Fallback: Manual Download + +If automated download fails (auth issues, etc.), provide the user with: +1. The Azure DevOps build URL +2. Instructions to navigate to the build → Summary → Artifacts section +3. Look for individual artifacts whose names contain `updated-expected-sizes` +4. Download the artifact zip, extract it, and copy the `.txt` files (e.g., `iOS-MonoVM-interpreter-size.txt`) into `tests/dotnet/UnitTests/expected/` + +## Fallback: Run Locally + +If the user can build locally, they can update the expected files directly: + +```bash +WRITE_KNOWN_FAILURES=1 tests-dotnet AppSizeTest +``` + +This runs the tests, updates the expected files in place, and marks the tests as passed. + diff --git a/.github/workflows/autoformat-v2.yml b/.github/workflows/autoformat-v2.yml new file mode 100644 index 000000000000..4fb4d4a234df --- /dev/null +++ b/.github/workflows/autoformat-v2.yml @@ -0,0 +1,97 @@ +name: Autoformat code v2 +on: pull_request + +permissions: {} + +jobs: + # Job for same-repo PRs: format and push directly + autoformat-push: + name: Autoformat and push + runs-on: ubuntu-latest + if: github.event.pull_request.head.repo.full_name == github.repository + permissions: + contents: write + + steps: + - name: 'Checkout' + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + ref: ${{ github.head_ref }} + fetch-depth: 1 + persist-credentials: false + + - name: 'Install .NET' + uses: actions/setup-dotnet@c2fa09f4bde5ebb9d1777cf28262a3eb3db3ced7 # v5 + with: + global-json-file: ./global.json + + - name: 'Autoformat' + run: ./tools/autoformat.sh + + - name: 'Check for changes' + id: check + run: | + if git diff --quiet; then + echo "changes=false" >> "$GITHUB_OUTPUT" + else + echo "changes=true" >> "$GITHUB_OUTPUT" + fi + + - name: 'Commit and push' + if: steps.check.outputs.changes == 'true' + env: + GH_TOKEN: ${{ github.token }} + run: | + git config user.email 'github-actions-autoformatter@xamarin.com' + git config user.name 'GitHub Actions Autoformatter' + git remote set-url origin "https://x-access-token:${GH_TOKEN}@github.com/${{ github.repository }}" + git add -A + git commit -m 'Auto-format source code' + git push + + # Job for fork PRs: format and upload patch as artifact + autoformat-artifact: + name: Autoformat and upload patch + runs-on: ubuntu-latest + if: github.event.pull_request.head.repo.full_name != github.repository + permissions: + contents: read + + steps: + - name: 'Checkout' + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + repository: ${{ github.event.pull_request.head.repo.full_name }} + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + fetch-depth: 1 + + - name: 'Install .NET' + uses: actions/setup-dotnet@c2fa09f4bde5ebb9d1777cf28262a3eb3db3ced7 # v5 + with: + global-json-file: ./global.json + + - name: 'Autoformat' + run: ./tools/autoformat.sh + + - name: 'Create patch' + id: patch + run: | + if git diff --quiet; then + echo "changes=false" >> "$GITHUB_OUTPUT" + else + echo "changes=true" >> "$GITHUB_OUTPUT" + git config user.email 'github-actions-autoformatter@xamarin.com' + git config user.name 'GitHub Actions Autoformatter' + git add -A + git commit -m 'Auto-format source code' + mkdir -p autoformat-output + git format-patch HEAD~1 --stdout > autoformat-output/autoformat.patch + fi + + - name: 'Upload patch' + if: steps.patch.outputs.changes == 'true' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: autoformat + path: autoformat-output/ diff --git a/.github/workflows/autoformat.yml b/.github/workflows/autoformat.yml deleted file mode 100644 index f20d04015aad..000000000000 --- a/.github/workflows/autoformat.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Autoformat code -on: pull_request - -# This action only need a single permission in order to autoformat the code. -permissions: - contents: read - -jobs: - autoformat-code: - name: Autoformat code - runs-on: ubuntu-latest - - steps: - - name: 'Checkout' - uses: actions/checkout@v6 - with: - fetch-depth: 0 - repository: ${{ github.event.pull_request.head.repo.full_name }} - ref: ${{ github.event.pull_request.head.sha }} - - name: 'Install .NET' - uses: actions/setup-dotnet@v5 - with: - global-json-file: ./global.json - - name: 'Autoformat' - uses: rolfbjarne/autoformat@v0.6 - with: - script: ./tools/autoformat.sh - git_user_email: 'github-actions-autoformatter@xamarin.com' - git_user_name: 'GitHub Actions Autoformatter' - checkoutSource: false diff --git a/.github/workflows/autoformat2.yml b/.github/workflows/autoformat2.yml deleted file mode 100644 index bc382aaf8c2e..000000000000 --- a/.github/workflows/autoformat2.yml +++ /dev/null @@ -1,27 +0,0 @@ -name: Autoformat code - push results -on: - workflow_run: - workflows: ["Autoformat code"] - types: - - completed - -# This action needs the following permissions in order to push the results back to the original branch. -permissions: - pull-requests: write - contents: write - -jobs: - push-and-notify: - name: Push autoformatted code and notify user - runs-on: ubuntu-latest - if: > - github.event.workflow_run.event == 'pull_request' && - github.event.workflow_run.conclusion == 'success' - steps: - - name: 'Push autoformatted patch' - uses: rolfbjarne/autoformat-push@v0.3 - with: - githubToken: ${{ secrets.GITHUB_TOKEN }} - git_user_email: 'github-actions-autoformatter@xamarin.com' - git_user_name: 'GitHub Actions Autoformatter' - commentOnPullRequest: false diff --git a/.github/workflows/backport-trigger.yml b/.github/workflows/backport-trigger.yml deleted file mode 100644 index 0cc0f263e5f6..000000000000 --- a/.github/workflows/backport-trigger.yml +++ /dev/null @@ -1,56 +0,0 @@ -name: Backport Trigger - -on: - issue_comment: - types: [created] - -jobs: - setupBackport: - runs-on: ubuntu-latest - # GITHUB_TOKEN change from read-write to read-only on 2024-02-01 requires permissions block - # https://docs.opensource.microsoft.com/github/apps/permission-changes/ - # https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs - permissions: - actions: write - contents: read - security-events: write - if: github.event.issue.pull_request != '' && startswith(github.event.comment.body, '/sudo backport') - outputs: - target_branch: ${{ steps.parse_comment.outputs.target_branch }} - steps: - - name: Parse Comment - id: parse_comment - shell: pwsh - run: | - Write-Host "Parsing $env:COMMENT" - ($botName, $backport, $backportTargetBranch) = [System.Text.RegularExpressions.Regex]::Split("$env:COMMENT", "\s+") - Write-Host "GITHUB_OUTPUT: ${env:GITHUB_OUTPUT}" - [IO.File]::AppendAllText($env:GITHUB_OUTPUT, "target_branch=${backportTargetBranch}$([Environment]::NewLine)") # Equivalent to the deprecated ::set-output command: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idoutputs - env: - COMMENT: "${{ github.event.comment.body }}" - - launchBackportBuild: - needs: setupBackport - uses: xamarin/backport-bot-action/.github/workflows/backport-action.yml@v2.0 - # GITHUB_TOKEN change from read-write to read-only on 2024-02-01 requiring permissions block - # https://docs.opensource.microsoft.com/github/apps/permission-changes/ - # https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs - permissions: - actions: none - contents: read - security-events: none - id-token: write # The backport-action template being invoked requires this permission - with: - pull_request_url: ${{ github.event.issue.pull_request.url }} - target_branch: ${{ needs.setupBackport.outputs.target_branch }} - comment_author: ${{ github.actor }} - github_repository: ${{ github.repository }} - use_fork: false - secrets: - azure_tenant_id: ${{ secrets.BACKPORT_AZURE_TENANT_ID }} - azure_subscription_id: ${{ secrets.BACKPORT_AZURE_SUBSCRIPTION_ID }} - azure_client_id: ${{ secrets.BACKPORT_AZURE_CLIENT_ID }} - ado_organization: ${{ secrets.ADO_PROJECTCOLLECTION }} - ado_project: ${{ secrets.ADO_PROJECT }} - backport_pipeline_id: ${{ secrets.BACKPORT_PIPELINEID }} - github_account_pat: ${{ secrets.SERVICEACCOUNT_PAT }} diff --git a/.github/workflows/bump-global-json.yml b/.github/workflows/bump-global-json.yml index f66a3a0b7eb7..0644a2c53429 100644 --- a/.github/workflows/bump-global-json.yml +++ b/.github/workflows/bump-global-json.yml @@ -1,5 +1,10 @@ name: Bump global.json for dotnet/sdk bumps -on: pull_request_target + +on: + pull_request: + types: [opened, synchronize] + +permissions: {} jobs: bump-global-json: @@ -10,14 +15,18 @@ jobs: # https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs permissions: contents: write - if: contains(github.event.pull_request.title, 'Update dependencies from dotnet/') && github.actor == 'dotnet-maestro[bot]' + # We'll never need to run this workflow for PRs from forks, so explicitly avoid that to limit potential exposure + if: github.event.pull_request.head.repo.full_name == github.repository && + github.event.pull_request.user.login == 'dotnet-maestro[bot]' && + contains(github.event.pull_request.title, 'Update dependencies from dotnet/') steps: - name: 'Checkout repo' - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: fetch-depth: 0 repository: ${{ github.event.pull_request.head.repo.full_name }} - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ github.head_ref }} + persist-credentials: true # we need the credentials to push code - name: 'Update global.json' env: @@ -34,6 +43,5 @@ jobs: git add -- global.json git config --global user.email "github-actions@xamarin.com" git config --global user.name "GitHub Actions" - git checkout "$GITHUB_HEAD_REF" git commit -m "Re-generate global.json for PR #$PR_NUMBER: $PR_TITLE" git push diff --git a/.github/workflows/ci-postmortem.lock.yml b/.github/workflows/ci-postmortem.lock.yml new file mode 100644 index 000000000000..58d2f385a005 --- /dev/null +++ b/.github/workflows/ci-postmortem.lock.yml @@ -0,0 +1,1485 @@ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"15354af11629eb0049ecb70f03b13ed2df90af330f1d6a40d7ce9a202538bb0b","body_hash":"ad13b1075fd08c989fe77b74abdce355d88ab2ebeea692809a67d8b68cd7559b","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot","agent_model":"claude-sonnet-4.5"} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ +# | _ |/ _` |/ _ \ '_ \| __| |/ __| +# | | | | (_| | __/ | | | |_| | (__ +# \_| |_/\__, |\___|_| |_|\__|_|\___| +# __/ | +# _ _ |___/ +# | | | | / _| | +# | | | | ___ _ __ _ __| |_| | _____ ____ +# | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| +# \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ +# \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ +# +# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. +# +# To update this file, edit the corresponding .md file and run: +# gh aw compile +# Not all edits will cause changes to this file. +# +# For more information: https://github.github.com/gh-aw/introduction/overview/ +# +# +# Secrets used: +# - COPILOT_GITHUB_TOKEN +# - GH_AW_GITHUB_MCP_SERVER_TOKEN +# - GH_AW_GITHUB_TOKEN +# - GITHUB_TOKEN +# +# Custom actions used: +# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 +# - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 +# - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 +# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# +# Container images used: +# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 +# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 +# - ghcr.io/github/gh-aw-mcpg:v0.3.22 +# - ghcr.io/github/github-mcp-server:v1.1.0 +# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + +name: "CI Post-Mortem Analysis" +on: + schedule: + - cron: "11 2 * * 0" + # Friendly format: weekly on sunday (scattered) + workflow_dispatch: + inputs: + aw_context: + default: "" + description: "Agent caller context (used internally by Agentic Workflows)." + required: false + type: string + +permissions: {} + +concurrency: + group: "gh-aw-${{ github.workflow }}" + +run-name: "CI Post-Mortem Analysis" + +jobs: + activation: + runs-on: ubuntu-slim + permissions: + actions: read + contents: read + outputs: + comment_id: "" + comment_repo: "" + engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} + lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} + model: ${{ steps.generate_aw_info.outputs.model }} + secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} + setup-span-id: ${{ steps.setup.outputs.span-id }} + setup-trace-id: ${{ steps.setup.outputs.trace-id }} + stale_lock_file_failed: ${{ steps.check-lock-file.outputs.stale_lock_file_failed == 'true' }} + steps: + - name: Setup Scripts + id: setup + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + with: + destination: ${{ runner.temp }}/gh-aw/actions + job-name: ${{ github.job }} + env: + GH_AW_SETUP_WORKFLOW_NAME: "CI Post-Mortem Analysis" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/ci-postmortem.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" + - name: Generate agentic run info + id: generate_aw_info + env: + GH_AW_INFO_ENGINE_ID: "copilot" + GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" + GH_AW_INFO_MODEL: "claude-sonnet-4.5" + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AGENT_VERSION: "1.0.55" + GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_WORKFLOW_NAME: "CI Post-Mortem Analysis" + GH_AW_INFO_EXPERIMENTAL: "false" + GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" + GH_AW_INFO_STAGED: "false" + GH_AW_INFO_ALLOWED_DOMAINS: '["defaults","dotnet","github","aka.ms","dev.azure.com","devdiv.visualstudio.com","microsoft.com","vsassets.io"]' + GH_AW_INFO_FIREWALL_ENABLED: "true" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWMG_VERSION: "" + GH_AW_INFO_FIREWALL_TYPE: "squid" + GH_AW_COMPILED_STRICT: "true" + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); + await main(core, context); + - name: Validate COPILOT_GITHUB_TOKEN secret + id: validate-secret + run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + env: + COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + - name: Checkout .github and .agents folders + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + sparse-checkout: | + .github + .agents + .antigravity + .claude + .codex + .crush + .gemini + .opencode + .pi + sparse-checkout-cone-mode: true + fetch-depth: 1 + - name: Save agent config folders for base branch restoration + env: + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + # poutine:ignore untrusted_checkout_exec + run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" + - name: Check workflow lock file + id: check-lock-file + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_FILE: "ci-postmortem.lock.yml" + GH_AW_CONTEXT_WORKFLOW_REF: "${{ github.workflow_ref }}" + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_workflow_timestamp_api.cjs'); + await main(); + - name: Check compile-agentic version + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_COMPILED_VERSION: "v0.77.5" + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_version_updates.cjs'); + await main(); + - name: Create prompt with built-in context + env: + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + GH_AW_SAFE_OUTPUTS: ${{ runner.temp }}/gh-aw/safeoutputs/outputs.jsonl + GH_AW_EXPR_1A3A194A: ${{ github.event.discussion.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'discussion' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_463A214A: ${{ github.event.pull_request.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'pull_request' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_802A9F6A: ${{ github.event.issue.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'issue' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_FF1D34CE: ${{ github.event.comment.id || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').comment_id }} + GH_AW_GITHUB_ACTOR: ${{ github.actor }} + GH_AW_GITHUB_REPOSITORY: ${{ github.repository }} + GH_AW_GITHUB_RUN_ID: ${{ github.run_id }} + GH_AW_GITHUB_WORKSPACE: ${{ github.workspace }} + # poutine:ignore untrusted_checkout_exec + run: | + bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" + { + cat << 'GH_AW_PROMPT_956c986f1e45d6a0_EOF' + + GH_AW_PROMPT_956c986f1e45d6a0_EOF + cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" + cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" + cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" + cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" + cat << 'GH_AW_PROMPT_956c986f1e45d6a0_EOF' + + Tools: add_comment(max:20), create_issue(max:20), update_issue(max:20), missing_tool, missing_data, noop + + GH_AW_PROMPT_956c986f1e45d6a0_EOF + cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" + cat << 'GH_AW_PROMPT_956c986f1e45d6a0_EOF' + + The following GitHub context information is available for this workflow: + {{#if github.actor}} + - **actor**: __GH_AW_GITHUB_ACTOR__ + {{/if}} + {{#if github.repository}} + - **repository**: __GH_AW_GITHUB_REPOSITORY__ + {{/if}} + {{#if github.workspace}} + - **workspace**: __GH_AW_GITHUB_WORKSPACE__ + {{/if}} + {{#if github.event.issue.number || (github.aw.context.item_type == 'issue' && github.aw.context.item_number)}} + - **issue-number**: #__GH_AW_EXPR_802A9F6A__ + {{/if}} + {{#if github.event.discussion.number || (github.aw.context.item_type == 'discussion' && github.aw.context.item_number)}} + - **discussion-number**: #__GH_AW_EXPR_1A3A194A__ + {{/if}} + {{#if github.event.pull_request.number || (github.aw.context.item_type == 'pull_request' && github.aw.context.item_number)}} + - **pull-request-number**: #__GH_AW_EXPR_463A214A__ + {{/if}} + {{#if github.event.comment.id || github.aw.context.comment_id}} + - **comment-id**: __GH_AW_EXPR_FF1D34CE__ + {{/if}} + {{#if github.run_id}} + - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ + {{/if}} + + + GH_AW_PROMPT_956c986f1e45d6a0_EOF + cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" + cat << 'GH_AW_PROMPT_956c986f1e45d6a0_EOF' + + {{#runtime-import .github/workflows/ci-postmortem.md}} + GH_AW_PROMPT_956c986f1e45d6a0_EOF + } > "$GH_AW_PROMPT" + - name: Interpolate variables and render templates + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + GH_AW_ENGINE_ID: "copilot" + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/interpolate_prompt.cjs'); + await main(); + - name: Substitute placeholders + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + GH_AW_EXPR_1A3A194A: ${{ github.event.discussion.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'discussion' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_463A214A: ${{ github.event.pull_request.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'pull_request' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_802A9F6A: ${{ github.event.issue.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'issue' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_FF1D34CE: ${{ github.event.comment.id || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').comment_id }} + GH_AW_GITHUB_ACTOR: ${{ github.actor }} + GH_AW_GITHUB_REPOSITORY: ${{ github.repository }} + GH_AW_GITHUB_RUN_ID: ${{ github.run_id }} + GH_AW_GITHUB_WORKSPACE: ${{ github.workspace }} + GH_AW_MCP_CLI_SERVERS_LIST: '- `safeoutputs` — run `safeoutputs --help` to see available tools' + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); + + // Call the substitution function + return await substitutePlaceholders({ + file: process.env.GH_AW_PROMPT, + substitutions: { + GH_AW_EXPR_1A3A194A: process.env.GH_AW_EXPR_1A3A194A, + GH_AW_EXPR_463A214A: process.env.GH_AW_EXPR_463A214A, + GH_AW_EXPR_802A9F6A: process.env.GH_AW_EXPR_802A9F6A, + GH_AW_EXPR_FF1D34CE: process.env.GH_AW_EXPR_FF1D34CE, + GH_AW_GITHUB_ACTOR: process.env.GH_AW_GITHUB_ACTOR, + GH_AW_GITHUB_REPOSITORY: process.env.GH_AW_GITHUB_REPOSITORY, + GH_AW_GITHUB_RUN_ID: process.env.GH_AW_GITHUB_RUN_ID, + GH_AW_GITHUB_WORKSPACE: process.env.GH_AW_GITHUB_WORKSPACE, + GH_AW_MCP_CLI_SERVERS_LIST: process.env.GH_AW_MCP_CLI_SERVERS_LIST + } + }); + - name: Validate prompt placeholders + env: + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + # poutine:ignore untrusted_checkout_exec + run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_prompt_placeholders.sh" + - name: Print prompt + env: + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + # poutine:ignore untrusted_checkout_exec + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_prompt_summary.sh" + - name: Upload activation artifact + if: success() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: activation + include-hidden-files: true + path: | + /tmp/gh-aw/aw_info.json + /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/aw-prompts/prompt.txt + /tmp/gh-aw/aw-prompts/prompt-template.txt + /tmp/gh-aw/aw-prompts/prompt-import-tree.json + /tmp/gh-aw/github_rate_limits.jsonl + /tmp/gh-aw/base + /tmp/gh-aw/.github/agents + /tmp/gh-aw/.github/skills + if-no-files-found: ignore + retention-days: 1 + + agent: + needs: activation + runs-on: ubuntu-latest + permissions: + contents: read + issues: read + concurrency: + group: "gh-aw-copilot-${{ github.workflow }}" + queue: max + env: + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + GH_AW_ASSETS_ALLOWED_EXTS: "" + GH_AW_ASSETS_BRANCH: "" + GH_AW_ASSETS_MAX_SIZE_KB: 0 + GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_WORKFLOW_ID_SANITIZED: cipostmortem + outputs: + agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} + effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} + effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} + has_patch: ${{ steps.collect_output.outputs.has_patch }} + inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} + mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} + model: ${{ needs.activation.outputs.model }} + model_not_supported_error: ${{ steps.detect-agent-errors.outputs.model_not_supported_error || 'false' }} + output: ${{ steps.collect_output.outputs.output }} + output_types: ${{ steps.collect_output.outputs.output_types }} + setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} + setup-span-id: ${{ steps.setup.outputs.span-id }} + setup-trace-id: ${{ steps.setup.outputs.trace-id }} + steps: + - name: Setup Scripts + id: setup + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + with: + destination: ${{ runner.temp }}/gh-aw/actions + job-name: ${{ github.job }} + trace-id: ${{ needs.activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: "CI Post-Mortem Analysis" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/ci-postmortem.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" + - name: Set runtime paths + id: set-runtime-paths + run: | + { + echo "GH_AW_SAFE_OUTPUTS=${RUNNER_TEMP}/gh-aw/safeoutputs/outputs.jsonl" + echo "GH_AW_SAFE_OUTPUTS_CONFIG_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" + echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" + } >> "$GITHUB_OUTPUT" + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - name: Create gh-aw temp directory + run: bash "${RUNNER_TEMP}/gh-aw/actions/create_gh_aw_tmp_dir.sh" + - name: Configure gh CLI for GitHub Enterprise + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" + env: + GH_TOKEN: ${{ github.token }} + - name: Configure Git credentials + env: + REPO_NAME: ${{ github.repository }} + SERVER_URL: ${{ github.server_url }} + GITHUB_TOKEN: ${{ github.token }} + run: | + git config --global user.email "github-actions[bot]@users.noreply.github.com" + git config --global user.name "github-actions[bot]" + git config --global am.keepcr true + # Re-authenticate git with GitHub token + SERVER_URL_STRIPPED="${SERVER_URL#https://}" + git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" + echo "Git configured with standard GitHub Actions identity" + - name: Checkout PR branch + id: checkout-pr + if: | + github.event.pull_request || github.event.issue.pull_request + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + with: + github-token: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); + await main(); + - name: Install GitHub Copilot CLI + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + env: + GH_HOST: github.com + - name: Install AWF binary + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + - name: Parse integrity filter lists + id: parse-guard-vars + env: + GH_AW_BLOCKED_USERS_VAR: ${{ vars.GH_AW_GITHUB_BLOCKED_USERS || '' }} + GH_AW_TRUSTED_USERS_VAR: ${{ vars.GH_AW_GITHUB_TRUSTED_USERS || '' }} + GH_AW_APPROVAL_LABELS_VAR: ${{ vars.GH_AW_GITHUB_APPROVAL_LABELS || '' }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/parse_guard_list.sh" + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: activation + path: /tmp/gh-aw + - name: Restore agent config folders from base branch + if: steps.checkout-pr.outcome == 'success' + env: + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" + - name: Restore inline sub-agents from activation artifact + env: + GH_AW_SUB_AGENT_DIR: ".github/agents" + GH_AW_SUB_AGENT_EXT: ".agent.md" + run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_sub_agents.sh" + - name: Restore inline skills from activation artifact + env: + GH_AW_SKILL_DIR: ".github/skills" + run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" + - name: Download container images + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + - name: Generate Safe Outputs Config + run: | + mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" + mkdir -p /tmp/gh-aw/safeoutputs + mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_c2d474e65378a915_EOF' + {"add_comment":{"max":20},"create_issue":{"max":20},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{},"update_issue":{"allow_body":true,"max":20}} + GH_AW_SAFE_OUTPUTS_CONFIG_c2d474e65378a915_EOF + - name: Generate Safe Outputs Tools + env: + GH_AW_TOOLS_META_JSON: | + { + "description_suffixes": { + "add_comment": " CONSTRAINTS: Maximum 20 comment(s) can be added. Supports reply_to_id for discussion threading.", + "create_issue": " CONSTRAINTS: Maximum 20 issue(s) can be created.", + "update_issue": " CONSTRAINTS: Maximum 20 issue(s) can be updated." + }, + "repo_params": {}, + "dynamic_tools": [] + } + GH_AW_VALIDATION_JSON: | + { + "add_comment": { + "defaultMax": 1, + "fields": { + "body": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 65000 + }, + "item_number": { + "issueOrPRNumber": true + }, + "reply_to_id": { + "type": "string", + "maxLength": 256 + }, + "repo": { + "type": "string", + "maxLength": 256 + } + } + }, + "create_issue": { + "defaultMax": 1, + "fields": { + "body": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 65000 + }, + "fields": { + "type": "array" + }, + "labels": { + "type": "array", + "itemType": "string", + "itemSanitize": true, + "itemMaxLength": 128 + }, + "parent": { + "issueOrPRNumber": true + }, + "repo": { + "type": "string", + "maxLength": 256 + }, + "temporary_id": { + "type": "string" + }, + "title": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 128 + } + } + }, + "missing_data": { + "defaultMax": 20, + "fields": { + "alternatives": { + "type": "string", + "sanitize": true, + "maxLength": 256 + }, + "context": { + "type": "string", + "sanitize": true, + "maxLength": 256 + }, + "data_type": { + "type": "string", + "sanitize": true, + "maxLength": 128 + }, + "reason": { + "type": "string", + "sanitize": true, + "maxLength": 256 + } + } + }, + "missing_tool": { + "defaultMax": 20, + "fields": { + "alternatives": { + "type": "string", + "sanitize": true, + "maxLength": 512 + }, + "reason": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 256 + }, + "tool": { + "type": "string", + "sanitize": true, + "maxLength": 128 + } + } + }, + "noop": { + "defaultMax": 1, + "fields": { + "message": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 65000 + } + } + }, + "report_incomplete": { + "defaultMax": 5, + "fields": { + "details": { + "type": "string", + "sanitize": true, + "maxLength": 65000 + }, + "reason": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 1024 + } + } + }, + "update_issue": { + "defaultMax": 1, + "fields": { + "assignees": { + "type": "array", + "itemType": "string", + "itemSanitize": true, + "itemMaxLength": 39 + }, + "body": { + "type": "string", + "sanitize": true, + "maxLength": 65000 + }, + "issue_number": { + "issueOrPRNumber": true + }, + "labels": { + "type": "array", + "itemType": "string", + "itemSanitize": true, + "itemMaxLength": 128 + }, + "milestone": { + "optionalPositiveInteger": true + }, + "operation": { + "type": "string", + "enum": [ + "replace", + "append", + "prepend", + "replace-island" + ] + }, + "repo": { + "type": "string", + "maxLength": 256 + }, + "status": { + "type": "string", + "enum": [ + "open", + "closed" + ] + }, + "title": { + "type": "string", + "sanitize": true, + "maxLength": 128 + } + }, + "customValidation": "requiresOneOf:status,title,body" + } + } + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); + await main(); + - name: Generate Safe Outputs MCP Server Config + id: safe-outputs-config + run: | + # Generate a secure random API key (360 bits of entropy, 40+ chars) + # Mask immediately to prevent timing vulnerabilities + API_KEY=$(openssl rand -base64 45 | tr -d '/+=') + echo "::add-mask::${API_KEY}" + + PORT=3001 + + # Set outputs for next steps + { + echo "safe_outputs_api_key=${API_KEY}" + echo "safe_outputs_port=${PORT}" + } >> "$GITHUB_OUTPUT" + + echo "Safe Outputs MCP server will run on port ${PORT}" + + - name: Start Safe Outputs MCP HTTP Server + id: safe-outputs-start + env: + DEBUG: '*' + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} + GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} + GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json + GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + run: | + # Environment variables are set above to prevent template injection + export DEBUG + export GH_AW_SAFE_OUTPUTS + export GH_AW_SAFE_OUTPUTS_PORT + export GH_AW_SAFE_OUTPUTS_API_KEY + export GH_AW_SAFE_OUTPUTS_TOOLS_PATH + export GH_AW_SAFE_OUTPUTS_CONFIG_PATH + export GH_AW_MCP_LOG_DIR + + bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" + + - name: Start MCP Gateway + id: start-mcp-gateway + env: + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} + GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} + GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + run: | + set -eo pipefail + mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" + + # Export gateway environment variables for MCP config and gateway script + export MCP_GATEWAY_PORT="8080" + export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_HOST_DOMAIN="localhost" + MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') + echo "::add-mask::${MCP_GATEWAY_API_KEY}" + export MCP_GATEWAY_API_KEY + export MCP_GATEWAY_PAYLOAD_DIR="/tmp/gh-aw/mcp-payloads" + mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" + export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" + export DEBUG="*" + + export GH_AW_ENGINE="copilot" + MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') + MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') + case "${DOCKER_HOST:-}" in + unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; + /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; + * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; + esac + DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' + + mkdir -p /home/runner/.copilot + GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) + cat << GH_AW_MCP_CONFIG_7bd5cd6513b45b21_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + { + "mcpServers": { + "github": { + "type": "stdio", + "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "env": { + "GITHUB_HOST": "\${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_READ_ONLY": "1", + "GITHUB_TOOLSETS": "issues,repos" + }, + "guard-policies": { + "allow-only": { + "approval-labels": ${{ steps.parse-guard-vars.outputs.approval_labels }}, + "blocked-users": ${{ steps.parse-guard-vars.outputs.blocked_users }}, + "min-integrity": "none", + "repos": "all", + "trusted-users": ${{ steps.parse-guard-vars.outputs.trusted_users }} + } + } + }, + "safeoutputs": { + "type": "http", + "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", + "headers": { + "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + }, + "guard-policies": { + "write-sink": { + "accept": [ + "*" + ] + } + } + } + }, + "gateway": { + "port": $MCP_GATEWAY_PORT, + "domain": "${MCP_GATEWAY_DOMAIN}", + "apiKey": "${MCP_GATEWAY_API_KEY}", + "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" + } + } + GH_AW_MCP_CONFIG_7bd5cd6513b45b21_EOF + - name: Mount MCP servers as CLIs + id: mount-mcp-clis + continue-on-error: true + env: + MCP_GATEWAY_API_KEY: ${{ steps.start-mcp-gateway.outputs.gateway-api-key }} + MCP_GATEWAY_DOMAIN: ${{ steps.start-mcp-gateway.outputs.gateway-domain }} + MCP_GATEWAY_PORT: ${{ steps.start-mcp-gateway.outputs.gateway-port }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io); + const { main } = require('${{ runner.temp }}/gh-aw/actions/mount_mcp_as_cli.cjs'); + await main(); + - name: Clean credentials + continue-on-error: true + run: bash "${RUNNER_TEMP}/gh-aw/actions/clean_git_credentials.sh" + - name: Audit pre-agent workspace + id: pre_agent_audit + continue-on-error: true + run: bash "${RUNNER_TEMP}/gh-aw/actions/audit_pre_agent_workspace.sh" + - name: Execute GitHub Copilot CLI + id: agentic_execution + # Copilot CLI tool arguments (sorted): + timeout-minutes: 20 + run: | + set -o pipefail + printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + touch /tmp/gh-aw/agent-step-summary.md + GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) + export GH_AW_NODE_BIN + export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" + (umask 177 && touch /tmp/gh-aw/agent-stdio.log) + printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["*.githubusercontent.com","*.vsblob.vsassets.io","aka.ms","api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.nuget.org","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","azuresearch-usnc.nuget.org","azuresearch-ussc.nuget.org","builds.dotnet.microsoft.com","ci.dot.net","codeload.github.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","dc.services.visualstudio.com","dev.azure.com","devdiv.visualstudio.com","dist.nuget.org","docs.github.com","dot.net","dotnet.microsoft.com","dotnetcli.blob.core.windows.net","github-cloud.githubusercontent.com","github-cloud.s3.amazonaws.com","github.blog","github.com","github.githubassets.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","lfs.github.com","microsoft.com","nuget.org","nuget.pkg.github.com","nugetregistryv2prod.blob.core.windows.net","objects.githubusercontent.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","oneocsp.microsoft.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","patch-diff.githubusercontent.com","pkgs.dev.azure.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","vsassets.io","www.googleapis.com","www.microsoft.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" + GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json + GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + fi + GH_AW_TOOL_CACHE_MOUNT="" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + if [ -d "$GH_AW_TOOL_CACHE" ]; then + if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then + GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" + fi + elif [ -d "/home/runner/work/_tool" ]; then + GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" + fi + # shellcheck disable=SC1003 + sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + env: + AWF_REFLECT_ENABLED: 1 + COPILOT_AGENT_RUNNER_TYPE: STANDALONE + COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode + COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_MODEL: claude-sonnet-4.5 + GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_PHASE: agent + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} + GH_AW_VERSION: v0.77.5 + GITHUB_API_URL: ${{ github.api_url }} + GITHUB_AW: true + GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows + GITHUB_HEAD_REF: ${{ github.head_ref }} + GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_REF_NAME: ${{ github.ref_name }} + GITHUB_SERVER_URL: ${{ github.server_url }} + GITHUB_STEP_SUMMARY: /tmp/gh-aw/agent-step-summary.md + GITHUB_WORKSPACE: ${{ github.workspace }} + GIT_AUTHOR_EMAIL: github-actions[bot]@users.noreply.github.com + GIT_AUTHOR_NAME: github-actions[bot] + GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com + GIT_COMMITTER_NAME: github-actions[bot] + RUNNER_TEMP: ${{ runner.temp }} + XDG_CONFIG_HOME: /home/runner + - name: Detect agent errors + if: always() + id: detect-agent-errors + continue-on-error: true + run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" + - name: Configure Git credentials + env: + REPO_NAME: ${{ github.repository }} + SERVER_URL: ${{ github.server_url }} + GITHUB_TOKEN: ${{ github.token }} + run: | + git config --global user.email "github-actions[bot]@users.noreply.github.com" + git config --global user.name "github-actions[bot]" + git config --global am.keepcr true + # Re-authenticate git with GitHub token + SERVER_URL_STRIPPED="${SERVER_URL#https://}" + git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" + echo "Git configured with standard GitHub Actions identity" + - name: Copy Copilot session state files to logs + if: always() + continue-on-error: true + run: bash "${RUNNER_TEMP}/gh-aw/actions/copy_copilot_session_state.sh" + - name: Stop MCP Gateway + if: always() + continue-on-error: true + env: + MCP_GATEWAY_PORT: ${{ steps.start-mcp-gateway.outputs.gateway-port }} + MCP_GATEWAY_API_KEY: ${{ steps.start-mcp-gateway.outputs.gateway-api-key }} + GATEWAY_PID: ${{ steps.start-mcp-gateway.outputs.gateway-pid }} + run: | + bash "${RUNNER_TEMP}/gh-aw/actions/stop_mcp_gateway.sh" "$GATEWAY_PID" + - name: Redact secrets in logs + if: always() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); + await main(); + env: + GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' + SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} + SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Append agent step summary + if: always() + run: bash "${RUNNER_TEMP}/gh-aw/actions/append_agent_step_summary.sh" + - name: Copy Safe Outputs + if: always() + env: + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} + run: | + mkdir -p /tmp/gh-aw + cp "$GH_AW_SAFE_OUTPUTS" /tmp/gh-aw/safeoutputs.jsonl 2>/dev/null || true + - name: Ingest agent output + id: collect_output + if: always() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} + GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,*.vsblob.vsassets.io,aka.ms,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.nuget.org,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,azuresearch-usnc.nuget.org,azuresearch-ussc.nuget.org,builds.dotnet.microsoft.com,ci.dot.net,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,dc.services.visualstudio.com,dev.azure.com,devdiv.visualstudio.com,dist.nuget.org,docs.github.com,dot.net,dotnet.microsoft.com,dotnetcli.blob.core.windows.net,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,microsoft.com,nuget.org,nuget.pkg.github.com,nugetregistryv2prod.blob.core.windows.net,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,oneocsp.microsoft.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,pkgs.dev.azure.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,vsassets.io,www.googleapis.com,www.microsoft.com" + GITHUB_SERVER_URL: ${{ github.server_url }} + GITHUB_API_URL: ${{ github.api_url }} + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/collect_ndjson_output.cjs'); + await main(); + - name: Parse agent logs for step summary + if: always() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_copilot_log.cjs'); + await main(); + - name: Parse MCP Gateway logs for step summary + if: always() + id: parse-mcp-gateway + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_mcp_gateway_log.cjs'); + await main(); + - name: Print firewall logs + if: always() + continue-on-error: true + env: + AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs + run: | + # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts + # AWF runs with sudo, creating files owned by root + sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true + # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) + if command -v awf &> /dev/null; then + awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" + else + echo 'AWF binary not installed, skipping firewall log summary' + fi + - name: Parse token usage for step summary + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); + - name: Print AWF reflect summary + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/awf_reflect_summary.cjs'); + await main(); + - name: Write agent output placeholder if missing + if: always() + run: | + if [ ! -f /tmp/gh-aw/agent_output.json ]; then + echo '{"items":[]}' > /tmp/gh-aw/agent_output.json + fi + - name: Upload agent artifacts + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: agent + path: | + /tmp/gh-aw/aw-prompts/prompt.txt + /tmp/gh-aw/sandbox/agent/logs/ + /tmp/gh-aw/redacted-urls.log + /tmp/gh-aw/mcp-logs/ + /tmp/gh-aw/proxy-logs/ + !/tmp/gh-aw/proxy-logs/proxy-tls/ + /tmp/gh-aw/agent_usage.json + /tmp/gh-aw/agent-stdio.log + /tmp/gh-aw/pre-agent-audit.txt + /tmp/gh-aw/agent/ + /tmp/gh-aw/github_rate_limits.jsonl + /tmp/gh-aw/safeoutputs.jsonl + /tmp/gh-aw/agent_output.json + /tmp/gh-aw/aw-*.patch + /tmp/gh-aw/aw-*.bundle + /tmp/gh-aw/awf-config.json + /tmp/gh-aw/sandbox/firewall/logs/ + /tmp/gh-aw/sandbox/firewall/audit/ + /tmp/gh-aw/sandbox/firewall/awf-reflect.json + if-no-files-found: ignore + + conclusion: + needs: + - activation + - agent + - detection + - safe_outputs + if: > + always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || + needs.activation.outputs.stale_lock_file_failed == 'true') + runs-on: ubuntu-slim + permissions: + contents: read + discussions: write + issues: write + pull-requests: write + concurrency: + group: "gh-aw-conclusion-ci-postmortem" + cancel-in-progress: false + queue: max + outputs: + incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} + noop_message: ${{ steps.noop.outputs.noop_message }} + tools_reported: ${{ steps.missing_tool.outputs.tools_reported }} + total_count: ${{ steps.missing_tool.outputs.total_count }} + steps: + - name: Setup Scripts + id: setup + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + with: + destination: ${{ runner.temp }}/gh-aw/actions + job-name: ${{ github.job }} + trace-id: ${{ needs.activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: "CI Post-Mortem Analysis" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/ci-postmortem.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" + - name: Download agent output artifact + id: download-agent-output + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: agent + path: /tmp/gh-aw/ + - name: Setup agent output environment variable + id: setup-agent-output-env + if: steps.download-agent-output.outcome == 'success' + run: | + mkdir -p /tmp/gh-aw/ + find "/tmp/gh-aw/" -type f -print + echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Process no-op messages + id: noop + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} + GH_AW_NOOP_MAX: "1" + GH_AW_WORKFLOW_NAME: "CI Post-Mortem Analysis" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/ci-postmortem.md" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} + GH_AW_NOOP_REPORT_AS_ISSUE: "true" + with: + github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/handle_noop_message.cjs'); + await main(); + - name: Log detection run + id: detection_runs + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} + GH_AW_WORKFLOW_NAME: "CI Post-Mortem Analysis" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/ci-postmortem.md" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} + GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} + with: + github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/handle_detection_runs.cjs'); + await main(); + - name: Record missing tool + id: missing_tool + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} + GH_AW_MISSING_TOOL_CREATE_ISSUE: "true" + GH_AW_WORKFLOW_NAME: "CI Post-Mortem Analysis" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/ci-postmortem.md" + with: + github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/missing_tool.cjs'); + await main(); + - name: Record incomplete + id: report_incomplete + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} + GH_AW_REPORT_INCOMPLETE_CREATE_ISSUE: "true" + GH_AW_WORKFLOW_NAME: "CI Post-Mortem Analysis" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/ci-postmortem.md" + with: + github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/report_incomplete_handler.cjs'); + await main(); + - name: Handle agent failure + id: handle_agent_failure + if: always() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} + GH_AW_WORKFLOW_NAME: "CI Post-Mortem Analysis" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/ci-postmortem.md" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} + GH_AW_WORKFLOW_ID: "ci-postmortem" + GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" + GH_AW_ENGINE_ID: "copilot" + GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} + GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} + GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} + GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} + GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} + GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} + GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" + GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_GROUP_REPORTS: "false" + GH_AW_FAILURE_REPORT_AS_ISSUE: "true" + GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" + GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" + GH_AW_TIMEOUT_MINUTES: "20" + GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" + with: + github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/handle_agent_failure.cjs'); + await main(); + + detection: + needs: + - activation + - agent + if: > + always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} + detection_reason: ${{ steps.detection_conclusion.outputs.reason }} + detection_success: ${{ steps.detection_conclusion.outputs.success }} + steps: + - name: Setup Scripts + id: setup + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + with: + destination: ${{ runner.temp }}/gh-aw/actions + job-name: ${{ github.job }} + trace-id: ${{ needs.activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: "CI Post-Mortem Analysis" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/ci-postmortem.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" + - name: Download agent output artifact + id: download-agent-output + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: agent + path: /tmp/gh-aw/ + - name: Setup agent output environment variable + id: setup-agent-output-env + if: steps.download-agent-output.outcome == 'success' + run: | + mkdir -p /tmp/gh-aw/ + find "/tmp/gh-aw/" -type f -print + echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Checkout repository for patch context + if: needs.agent.outputs.has_patch == 'true' + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + # --- Threat Detection --- + - name: Clean stale firewall files from agent artifact + run: | + rm -rf /tmp/gh-aw/sandbox/firewall/logs + rm -rf /tmp/gh-aw/sandbox/firewall/audit + - name: Download container images + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + - name: Check if detection needed + id: detection_guard + if: always() + env: + OUTPUT_TYPES: ${{ needs.agent.outputs.output_types }} + HAS_PATCH: ${{ needs.agent.outputs.has_patch }} + run: | + if [[ -n "$OUTPUT_TYPES" || "$HAS_PATCH" == "true" ]]; then + echo "run_detection=true" >> "$GITHUB_OUTPUT" + echo "Detection will run: output_types=$OUTPUT_TYPES, has_patch=$HAS_PATCH" + else + echo "run_detection=false" >> "$GITHUB_OUTPUT" + echo "Detection skipped: no agent outputs or patches to analyze" + fi + - name: Clear MCP Config for detection + if: always() && steps.detection_guard.outputs.run_detection == 'true' + run: | + rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" + rm -f /home/runner/.copilot/mcp-config.json + rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" + - name: Prepare threat detection files + if: always() && steps.detection_guard.outputs.run_detection == 'true' + run: | + mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true + if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then + echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." + fi + cp /tmp/gh-aw/agent_output.json /tmp/gh-aw/threat-detection/agent_output.json 2>/dev/null || true + for f in /tmp/gh-aw/aw-*.patch; do + [ -f "$f" ] && cp "$f" /tmp/gh-aw/threat-detection/ 2>/dev/null || true + done + for f in /tmp/gh-aw/aw-*.bundle; do + [ -f "$f" ] && cp "$f" /tmp/gh-aw/threat-detection/ 2>/dev/null || true + done + echo "Prepared threat detection files:" + ls -la /tmp/gh-aw/threat-detection/ 2>/dev/null || true + - name: Setup threat detection + if: always() && steps.detection_guard.outputs.run_detection == 'true' + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + WORKFLOW_NAME: "CI Post-Mortem Analysis" + WORKFLOW_DESCRIPTION: "No description provided" + HAS_PATCH: ${{ needs.agent.outputs.has_patch }} + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/setup_threat_detection.cjs'); + await main(); + - name: Ensure threat-detection directory and log + if: always() && steps.detection_guard.outputs.run_detection == 'true' + run: | + mkdir -p /tmp/gh-aw/threat-detection + touch /tmp/gh-aw/threat-detection/detection.log + - name: Setup Node.js + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: '24' + package-manager-cache: false + - name: Install GitHub Copilot CLI + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + env: + GH_HOST: github.com + - name: Install AWF binary + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + - name: Execute GitHub Copilot CLI + if: always() && steps.detection_guard.outputs.run_detection == 'true' + continue-on-error: true + id: detection_agentic_execution + # Copilot CLI tool arguments (sorted): + timeout-minutes: 20 + run: | + set -o pipefail + printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + touch /tmp/gh-aw/agent-step-summary.md + GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) + export GH_AW_NODE_BIN + export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" + (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) + printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" + GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json + GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + fi + GH_AW_TOOL_CACHE_MOUNT="" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + if [ -d "$GH_AW_TOOL_CACHE" ]; then + if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then + GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" + fi + elif [ -d "/home/runner/work/_tool" ]; then + GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" + fi + # shellcheck disable=SC1003 + sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ + -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + env: + AWF_REFLECT_ENABLED: 1 + COPILOT_AGENT_RUNNER_TYPE: STANDALONE + COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode + COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_MODEL: claude-sonnet-4.5 + GH_AW_PHASE: detection + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + GH_AW_VERSION: v0.77.5 + GITHUB_API_URL: ${{ github.api_url }} + GITHUB_AW: true + GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows + GITHUB_HEAD_REF: ${{ github.head_ref }} + GITHUB_REF_NAME: ${{ github.ref_name }} + GITHUB_SERVER_URL: ${{ github.server_url }} + GITHUB_STEP_SUMMARY: /tmp/gh-aw/agent-step-summary.md + GITHUB_WORKSPACE: ${{ github.workspace }} + GIT_AUTHOR_EMAIL: github-actions[bot]@users.noreply.github.com + GIT_AUTHOR_NAME: github-actions[bot] + GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com + GIT_COMMITTER_NAME: github-actions[bot] + RUNNER_TEMP: ${{ runner.temp }} + XDG_CONFIG_HOME: /home/runner + - name: Upload threat detection log + if: always() && steps.detection_guard.outputs.run_detection == 'true' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: detection + path: /tmp/gh-aw/threat-detection/detection.log + if-no-files-found: ignore + - name: Parse and conclude threat detection + id: detection_conclusion + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }} + DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }} + GH_AW_DETECTION_CONTINUE_ON_ERROR: "true" + with: + script: | + try { + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_threat_detection_results.cjs'); + await main(); + } catch (loadErr) { + const continueOnError = process.env.GH_AW_DETECTION_CONTINUE_ON_ERROR !== 'false'; + const detectionExecutionFailed = process.env.DETECTION_AGENTIC_EXECUTION_OUTCOME === 'failure'; + const msg = 'ERR_SYSTEM: \u274C Unexpected error loading threat detection module: ' + (loadErr && loadErr.message ? loadErr.message : String(loadErr)); + core.error(msg); + core.setOutput('reason', 'parse_error'); + if (continueOnError && !detectionExecutionFailed) { + core.warning('\u26A0\uFE0F ' + msg); + core.setOutput('conclusion', 'warning'); + core.setOutput('success', 'false'); + } else { + core.setOutput('conclusion', 'failure'); + core.setOutput('success', 'false'); + core.setFailed(msg); + } + } + + safe_outputs: + needs: + - activation + - agent + - detection + if: (!cancelled()) && needs.agent.result != 'skipped' && needs.detection.result == 'success' + runs-on: ubuntu-slim + permissions: + contents: read + discussions: write + issues: write + pull-requests: write + timeout-minutes: 15 + env: + GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/ci-postmortem" + GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} + GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} + GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} + GH_AW_ENGINE_ID: "copilot" + GH_AW_ENGINE_MODEL: "claude-sonnet-4.5" + GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_WORKFLOW_ID: "ci-postmortem" + GH_AW_WORKFLOW_NAME: "CI Post-Mortem Analysis" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/ci-postmortem.md" + outputs: + code_push_failure_count: ${{ steps.process_safe_outputs.outputs.code_push_failure_count }} + code_push_failure_errors: ${{ steps.process_safe_outputs.outputs.code_push_failure_errors }} + comment_id: ${{ steps.process_safe_outputs.outputs.comment_id }} + comment_url: ${{ steps.process_safe_outputs.outputs.comment_url }} + create_discussion_error_count: ${{ steps.process_safe_outputs.outputs.create_discussion_error_count }} + create_discussion_errors: ${{ steps.process_safe_outputs.outputs.create_discussion_errors }} + created_issue_number: ${{ steps.process_safe_outputs.outputs.created_issue_number }} + created_issue_url: ${{ steps.process_safe_outputs.outputs.created_issue_url }} + process_safe_outputs_processed_count: ${{ steps.process_safe_outputs.outputs.processed_count }} + process_safe_outputs_temporary_id_map: ${{ steps.process_safe_outputs.outputs.temporary_id_map }} + steps: + - name: Setup Scripts + id: setup + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + with: + destination: ${{ runner.temp }}/gh-aw/actions + job-name: ${{ github.job }} + trace-id: ${{ needs.activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: "CI Post-Mortem Analysis" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/ci-postmortem.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" + - name: Download agent output artifact + id: download-agent-output + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: agent + path: /tmp/gh-aw/ + - name: Setup agent output environment variable + id: setup-agent-output-env + if: steps.download-agent-output.outcome == 'success' + run: | + mkdir -p /tmp/gh-aw/ + find "/tmp/gh-aw/" -type f -print + echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Configure GH_HOST for enterprise compatibility + id: ghes-host-config + shell: bash + run: | + # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct + # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. + GH_HOST="${GITHUB_SERVER_URL#https://}" + GH_HOST="${GH_HOST#http://}" + echo "GH_HOST=${GH_HOST}" >> "$GITHUB_ENV" + - name: Process Safe Outputs + id: process_safe_outputs + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} + GH_AW_COMMENT_ID: ${{ needs.activation.outputs.comment_id }} + GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,*.vsblob.vsassets.io,aka.ms,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.nuget.org,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,azuresearch-usnc.nuget.org,azuresearch-ussc.nuget.org,builds.dotnet.microsoft.com,ci.dot.net,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,dc.services.visualstudio.com,dev.azure.com,devdiv.visualstudio.com,dist.nuget.org,docs.github.com,dot.net,dotnet.microsoft.com,dotnetcli.blob.core.windows.net,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,microsoft.com,nuget.org,nuget.pkg.github.com,nugetregistryv2prod.blob.core.windows.net,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,oneocsp.microsoft.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,pkgs.dev.azure.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,vsassets.io,www.googleapis.com,www.microsoft.com" + GITHUB_SERVER_URL: ${{ github.server_url }} + GITHUB_API_URL: ${{ github.api_url }} + GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"add_comment\":{\"max\":20},\"create_issue\":{\"max\":20},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"true\"},\"report_incomplete\":{},\"update_issue\":{\"allow_body\":true,\"max\":20}}" + with: + github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/safe_output_handler_manager.cjs'); + await main(); + - name: Upload Safe Outputs Items + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: safe-outputs-items + path: | + /tmp/gh-aw/safe-output-items.jsonl + /tmp/gh-aw/temporary-id-map.json + if-no-files-found: ignore + diff --git a/.github/workflows/ci-postmortem.md b/.github/workflows/ci-postmortem.md new file mode 100644 index 000000000000..64065525ca6e --- /dev/null +++ b/.github/workflows/ci-postmortem.md @@ -0,0 +1,57 @@ +--- +on: + schedule: + - cron: "weekly on sunday" + workflow_dispatch: +permissions: + contents: read + issues: read +engine: + id: copilot + model: claude-sonnet-4.5 +network: + allowed: + - defaults + - dotnet + - github + - "aka.ms" + - "dev.azure.com" + - "devdiv.visualstudio.com" + - "microsoft.com" + - "vsassets.io" +tools: + github: + toolsets: [issues, repos] + min-integrity: none +safe-outputs: + create-issue: + max: 20 + add-comment: + max: 20 + update-issue: + max: 20 +--- + +# CI Post-Mortem Analysis + +Perform a weekly post-mortem analysis of CI failures across recent PRs in dotnet/macios to identify flaky tests, infrastructure issues, and shared regressions that are not caused by any specific PR. + +## Instructions + +1. Read the skill definition from `.agents/skills/macios-ci-postmortem/SKILL.md` — this contains the full 4-phase workflow. +2. Read the Azure DevOps CLI reference from `.agents/skills/macios-ci-postmortem/references/azure-devops-cli.md`. +3. Execute all four phases of the workflow: + - **Phase 1: Discovery** — collect all PR-validation builds from the last 7 days + - **Phase 2: Extraction** — download TestSummary artifacts for triage, then HtmlReport artifacts only for jobs with test failures, and parse NUnit XML for individual test-level failures + - **Phase 3: Classification** — categorize failures as flaky (cross-PR or rerun-recovered), infrastructure (bot-specific or cross-bot), or PR-specific (exclude these). Also exclude `AppSizeTest` failures. + - **Phase 4: Issue Actions** — search for existing `ci-postmortem` issues, then file new issues or comment on existing ones +4. All issues must have the `ci-postmortem` and `copilot` labels. +5. File one issue per distinct test failure — do not group unrelated test failures together. +6. For infrastructure issues, check if failures are concentrated on specific bots by extracting `workerName` from build timelines. + +## Constraints + +- Only file issues for failures that appear across 2+ unrelated PRs, or that are confirmed flaky by rerun recovery (same commit, different outcome). +- Never file issues for PR-specific failures — those are the PR author's responsibility. +- Always search for existing `ci-postmortem` issues before creating new ones. Comment on existing issues if the failure is already tracked. +- Always exclude `AppSizeTest` failures — they are expected to fail across PRs. diff --git a/.github/workflows/code-radiator.lock.yml b/.github/workflows/code-radiator.lock.yml new file mode 100644 index 000000000000..76736b1d9f98 --- /dev/null +++ b/.github/workflows/code-radiator.lock.yml @@ -0,0 +1,1615 @@ +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"1ba69a47e6cfbd91cfe78d637aac47fa364d969c56a89ac3523d5c936169f250","body_hash":"b966744ea05e67fd471e10231f2cce01d0525af33bc90ff317655344e889cc92","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot","agent_model":"claude-sonnet-4.5"} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_CI_TRIGGER_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} +# ___ _ _ +# / _ \ | | (_) +# | |_| | __ _ ___ _ __ | |_ _ ___ +# | _ |/ _` |/ _ \ '_ \| __| |/ __| +# | | | | (_| | __/ | | | |_| | (__ +# \_| |_/\__, |\___|_| |_|\__|_|\___| +# __/ | +# _ _ |___/ +# | | | | / _| | +# | | | | ___ _ __ _ __| |_| | _____ ____ +# | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| +# \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ +# \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ +# +# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. +# +# To update this file, edit the corresponding .md file and run: +# gh aw compile +# Not all edits will cause changes to this file. +# +# For more information: https://github.github.com/gh-aw/introduction/overview/ +# +# +# Secrets used: +# - COPILOT_GITHUB_TOKEN +# - GH_AW_CI_TRIGGER_TOKEN +# - GH_AW_GITHUB_MCP_SERVER_TOKEN +# - GH_AW_GITHUB_TOKEN +# - GITHUB_TOKEN +# +# Custom actions used: +# - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 +# - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 +# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 +# - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 +# - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 +# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 +# +# Container images used: +# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 +# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 +# - ghcr.io/github/gh-aw-mcpg:v0.3.22 +# - ghcr.io/github/github-mcp-server:v1.1.0 +# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + +name: "Code Radiator" +on: + # roles: # Roles processed as role check in pre-activation job + # - admin # Roles processed as role check in pre-activation job + # - maintain # Roles processed as role check in pre-activation job + # - write # Roles processed as role check in pre-activation job + schedule: + - cron: "41 19 * * *" + # Friendly format: daily (scattered) + workflow_dispatch: + inputs: + aw_context: + default: "" + description: "Agent caller context (used internally by Agentic Workflows)." + required: false + type: string + +permissions: {} + +concurrency: + cancel-in-progress: true + group: code-radiator-${{ github.ref || github.run_id }} + +run-name: "Code Radiator" + +jobs: + activation: + runs-on: ubuntu-slim + permissions: + actions: read + contents: read + outputs: + comment_id: "" + comment_repo: "" + engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} + lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} + model: ${{ steps.generate_aw_info.outputs.model }} + secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} + setup-span-id: ${{ steps.setup.outputs.span-id }} + setup-trace-id: ${{ steps.setup.outputs.trace-id }} + stale_lock_file_failed: ${{ steps.check-lock-file.outputs.stale_lock_file_failed == 'true' }} + steps: + - name: Setup Scripts + id: setup + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + with: + destination: ${{ runner.temp }}/gh-aw/actions + job-name: ${{ github.job }} + env: + GH_AW_SETUP_WORKFLOW_NAME: "Code Radiator" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/code-radiator.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" + - name: Generate agentic run info + id: generate_aw_info + env: + GH_AW_INFO_ENGINE_ID: "copilot" + GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" + GH_AW_INFO_MODEL: "claude-sonnet-4.5" + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AGENT_VERSION: "1.0.55" + GH_AW_INFO_CLI_VERSION: "v0.77.5" + GH_AW_INFO_WORKFLOW_NAME: "Code Radiator" + GH_AW_INFO_EXPERIMENTAL: "false" + GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" + GH_AW_INFO_STAGED: "false" + GH_AW_INFO_ALLOWED_DOMAINS: '["defaults","github"]' + GH_AW_INFO_FIREWALL_ENABLED: "true" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_AWMG_VERSION: "" + GH_AW_INFO_FIREWALL_TYPE: "squid" + GH_AW_COMPILED_STRICT: "true" + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_aw_info.cjs'); + await main(core, context); + - name: Validate COPILOT_GITHUB_TOKEN secret + id: validate-secret + run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_multi_secret.sh" COPILOT_GITHUB_TOKEN 'GitHub Copilot CLI' https://github.github.com/gh-aw/reference/engines/#github-copilot-default + env: + COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + - name: Checkout .github and .agents folders + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + sparse-checkout: | + .github + .agents + .antigravity + .claude + .codex + .crush + .gemini + .opencode + .pi + sparse-checkout-cone-mode: true + fetch-depth: 1 + - name: Save agent config folders for base branch restoration + env: + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + # poutine:ignore untrusted_checkout_exec + run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" + - name: Check workflow lock file + id: check-lock-file + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_WORKFLOW_FILE: "code-radiator.lock.yml" + GH_AW_CONTEXT_WORKFLOW_REF: "${{ github.workflow_ref }}" + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_workflow_timestamp_api.cjs'); + await main(); + - name: Check compile-agentic version + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_COMPILED_VERSION: "v0.77.5" + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/check_version_updates.cjs'); + await main(); + - name: Create prompt with built-in context + env: + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + GH_AW_SAFE_OUTPUTS: ${{ runner.temp }}/gh-aw/safeoutputs/outputs.jsonl + GH_AW_EXPR_1A3A194A: ${{ github.event.discussion.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'discussion' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_463A214A: ${{ github.event.pull_request.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'pull_request' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_802A9F6A: ${{ github.event.issue.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'issue' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_FF1D34CE: ${{ github.event.comment.id || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').comment_id }} + GH_AW_GITHUB_ACTOR: ${{ github.actor }} + GH_AW_GITHUB_REPOSITORY: ${{ github.repository }} + GH_AW_GITHUB_RUN_ID: ${{ github.run_id }} + GH_AW_GITHUB_WORKSPACE: ${{ github.workspace }} + # poutine:ignore untrusted_checkout_exec + run: | + bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" + { + cat << 'GH_AW_PROMPT_686c839083e52610_EOF' + + GH_AW_PROMPT_686c839083e52610_EOF + cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" + cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" + cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" + cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" + cat << 'GH_AW_PROMPT_686c839083e52610_EOF' + + Tools: add_comment(max:10), create_pull_request(max:10), update_pull_request(max:10), add_labels(max:10), push_to_pull_request_branch(max:10), missing_tool, missing_data, noop + GH_AW_PROMPT_686c839083e52610_EOF + cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_create_pull_request.md" + cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_push_to_pr_branch.md" + cat << 'GH_AW_PROMPT_686c839083e52610_EOF' + + GH_AW_PROMPT_686c839083e52610_EOF + cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" + cat << 'GH_AW_PROMPT_686c839083e52610_EOF' + + The following GitHub context information is available for this workflow: + {{#if github.actor}} + - **actor**: __GH_AW_GITHUB_ACTOR__ + {{/if}} + {{#if github.repository}} + - **repository**: __GH_AW_GITHUB_REPOSITORY__ + {{/if}} + {{#if github.workspace}} + - **workspace**: __GH_AW_GITHUB_WORKSPACE__ + {{/if}} + {{#if github.event.issue.number || (github.aw.context.item_type == 'issue' && github.aw.context.item_number)}} + - **issue-number**: #__GH_AW_EXPR_802A9F6A__ + {{/if}} + {{#if github.event.discussion.number || (github.aw.context.item_type == 'discussion' && github.aw.context.item_number)}} + - **discussion-number**: #__GH_AW_EXPR_1A3A194A__ + {{/if}} + {{#if github.event.pull_request.number || (github.aw.context.item_type == 'pull_request' && github.aw.context.item_number)}} + - **pull-request-number**: #__GH_AW_EXPR_463A214A__ + {{/if}} + {{#if github.event.comment.id || github.aw.context.comment_id}} + - **comment-id**: __GH_AW_EXPR_FF1D34CE__ + {{/if}} + {{#if github.run_id}} + - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ + {{/if}} + - **checkouts**: The following repositories have been checked out and are available in the workspace: + - repo `__GH_AW_GITHUB_REPOSITORY__` → `$GITHUB_WORKSPACE` (cwd) [full history, all branches available as remote-tracking refs] [additional refs fetched: *] + - **Note**: If a branch you need is not in the list above and is not listed as an additional fetched ref, it has NOT been checked out. For private repositories you cannot fetch it without proper authentication. If the branch is required and not available, exit with an error and ask the user to add it to the `fetch:` option of the `checkout:` configuration (e.g., `fetch: ["refs/pulls/open/*"]` for all open PR refs, or `fetch: ["main", "feature/my-branch"]` for specific branches). + + + GH_AW_PROMPT_686c839083e52610_EOF + cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" + cat << 'GH_AW_PROMPT_686c839083e52610_EOF' + + {{#runtime-import .github/workflows/code-radiator.md}} + GH_AW_PROMPT_686c839083e52610_EOF + } > "$GH_AW_PROMPT" + - name: Interpolate variables and render templates + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + GH_AW_ENGINE_ID: "copilot" + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/interpolate_prompt.cjs'); + await main(); + - name: Substitute placeholders + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + GH_AW_EXPR_1A3A194A: ${{ github.event.discussion.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'discussion' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_463A214A: ${{ github.event.pull_request.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'pull_request' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_802A9F6A: ${{ github.event.issue.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'issue' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_FF1D34CE: ${{ github.event.comment.id || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').comment_id }} + GH_AW_GITHUB_ACTOR: ${{ github.actor }} + GH_AW_GITHUB_REPOSITORY: ${{ github.repository }} + GH_AW_GITHUB_RUN_ID: ${{ github.run_id }} + GH_AW_GITHUB_WORKSPACE: ${{ github.workspace }} + GH_AW_MCP_CLI_SERVERS_LIST: '- `safeoutputs` — run `safeoutputs --help` to see available tools' + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + + const substitutePlaceholders = require('${{ runner.temp }}/gh-aw/actions/substitute_placeholders.cjs'); + + // Call the substitution function + return await substitutePlaceholders({ + file: process.env.GH_AW_PROMPT, + substitutions: { + GH_AW_EXPR_1A3A194A: process.env.GH_AW_EXPR_1A3A194A, + GH_AW_EXPR_463A214A: process.env.GH_AW_EXPR_463A214A, + GH_AW_EXPR_802A9F6A: process.env.GH_AW_EXPR_802A9F6A, + GH_AW_EXPR_FF1D34CE: process.env.GH_AW_EXPR_FF1D34CE, + GH_AW_GITHUB_ACTOR: process.env.GH_AW_GITHUB_ACTOR, + GH_AW_GITHUB_REPOSITORY: process.env.GH_AW_GITHUB_REPOSITORY, + GH_AW_GITHUB_RUN_ID: process.env.GH_AW_GITHUB_RUN_ID, + GH_AW_GITHUB_WORKSPACE: process.env.GH_AW_GITHUB_WORKSPACE, + GH_AW_MCP_CLI_SERVERS_LIST: process.env.GH_AW_MCP_CLI_SERVERS_LIST + } + }); + - name: Validate prompt placeholders + env: + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + # poutine:ignore untrusted_checkout_exec + run: bash "${RUNNER_TEMP}/gh-aw/actions/validate_prompt_placeholders.sh" + - name: Print prompt + env: + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + # poutine:ignore untrusted_checkout_exec + run: bash "${RUNNER_TEMP}/gh-aw/actions/print_prompt_summary.sh" + - name: Upload activation artifact + if: success() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: activation + include-hidden-files: true + path: | + /tmp/gh-aw/aw_info.json + /tmp/gh-aw/model_multipliers.json + /tmp/gh-aw/aw-prompts/prompt.txt + /tmp/gh-aw/aw-prompts/prompt-template.txt + /tmp/gh-aw/aw-prompts/prompt-import-tree.json + /tmp/gh-aw/github_rate_limits.jsonl + /tmp/gh-aw/base + /tmp/gh-aw/.github/agents + /tmp/gh-aw/.github/skills + if-no-files-found: ignore + retention-days: 1 + + agent: + needs: activation + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + concurrency: + group: "gh-aw-copilot-${{ github.workflow }}" + queue: max + env: + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + GH_AW_ASSETS_ALLOWED_EXTS: "" + GH_AW_ASSETS_BRANCH: "" + GH_AW_ASSETS_MAX_SIZE_KB: 0 + GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + GH_AW_WORKFLOW_ID_SANITIZED: coderadiator + outputs: + agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} + checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} + effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} + effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} + has_patch: ${{ steps.collect_output.outputs.has_patch }} + inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} + mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} + model: ${{ needs.activation.outputs.model }} + model_not_supported_error: ${{ steps.detect-agent-errors.outputs.model_not_supported_error || 'false' }} + output: ${{ steps.collect_output.outputs.output }} + output_types: ${{ steps.collect_output.outputs.output_types }} + setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} + setup-span-id: ${{ steps.setup.outputs.span-id }} + setup-trace-id: ${{ steps.setup.outputs.trace-id }} + steps: + - name: Setup Scripts + id: setup + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + with: + destination: ${{ runner.temp }}/gh-aw/actions + job-name: ${{ github.job }} + trace-id: ${{ needs.activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: "Code Radiator" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/code-radiator.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" + - name: Set runtime paths + id: set-runtime-paths + run: | + { + echo "GH_AW_SAFE_OUTPUTS=${RUNNER_TEMP}/gh-aw/safeoutputs/outputs.jsonl" + echo "GH_AW_SAFE_OUTPUTS_CONFIG_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" + echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" + } >> "$GITHUB_OUTPUT" + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + fetch-depth: 0 + - name: Fetch additional refs + env: + GH_AW_FETCH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + run: | + header=$(printf "x-access-token:%s" "${GH_AW_FETCH_TOKEN}" | base64 -w 0) + git -c "http.extraheader=Authorization: Basic ${header}" fetch origin '+refs/heads/*:refs/remotes/origin/*' + - name: Create gh-aw temp directory + run: bash "${RUNNER_TEMP}/gh-aw/actions/create_gh_aw_tmp_dir.sh" + - name: Configure gh CLI for GitHub Enterprise + run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" + env: + GH_TOKEN: ${{ github.token }} + - name: Configure Git credentials + env: + REPO_NAME: ${{ github.repository }} + SERVER_URL: ${{ github.server_url }} + GITHUB_TOKEN: ${{ github.token }} + run: | + git config --global user.email "github-actions[bot]@users.noreply.github.com" + git config --global user.name "github-actions[bot]" + git config --global am.keepcr true + # Re-authenticate git with GitHub token + SERVER_URL_STRIPPED="${SERVER_URL#https://}" + git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" + echo "Git configured with standard GitHub Actions identity" + - name: Checkout PR branch + id: checkout-pr + if: | + github.event.pull_request || github.event.issue.pull_request + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + with: + github-token: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); + await main(); + - name: Install GitHub Copilot CLI + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + env: + GH_HOST: github.com + - name: Install AWF binary + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + - name: Parse integrity filter lists + id: parse-guard-vars + env: + GH_AW_BLOCKED_USERS_VAR: ${{ vars.GH_AW_GITHUB_BLOCKED_USERS || '' }} + GH_AW_TRUSTED_USERS_VAR: ${{ vars.GH_AW_GITHUB_TRUSTED_USERS || '' }} + GH_AW_APPROVAL_LABELS_VAR: ${{ vars.GH_AW_GITHUB_APPROVAL_LABELS || '' }} + run: bash "${RUNNER_TEMP}/gh-aw/actions/parse_guard_list.sh" + - name: Download activation artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: activation + path: /tmp/gh-aw + - name: Restore agent config folders from base branch + if: steps.checkout-pr.outcome == 'success' + env: + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" + run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" + - name: Restore inline sub-agents from activation artifact + env: + GH_AW_SUB_AGENT_DIR: ".github/agents" + GH_AW_SUB_AGENT_EXT: ".agent.md" + run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_sub_agents.sh" + - name: Restore inline skills from activation artifact + env: + GH_AW_SKILL_DIR: ".github/skills" + run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" + - name: Download container images + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + - name: Generate Safe Outputs Config + run: | + mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" + mkdir -p /tmp/gh-aw/safeoutputs + mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_9a64ac31bc43ee2c_EOF' + {"add_comment":{"max":10,"target":"*"},"add_labels":{"max":10,"target":"*"},"create_pull_request":{"allowed_base_branches":["net*.0","xcode*","xcode*.*"],"max":10,"max_patch_files":1000,"max_patch_size":1024,"protect_top_level_dot_folders":true,"protected_files":["package.json","bun.lockb","bunfig.toml","deno.json","deno.jsonc","deno.lock","global.json","NuGet.Config","Directory.Packages.props","mix.exs","mix.lock","go.mod","go.sum","stack.yaml","stack.yaml.lock","pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts","gradle.properties","package-lock.json","yarn.lock","pnpm-lock.yaml","npm-shrinkwrap.json","requirements.txt","Pipfile","Pipfile.lock","pyproject.toml","setup.py","setup.cfg","Gemfile","Gemfile.lock","uv.lock","CODEOWNERS","DESIGN.md","README.md","CONTRIBUTING.md","CHANGELOG.md","SECURITY.md","CODE_OF_CONDUCT.md","AGENTS.md","CLAUDE.md","GEMINI.md"],"protected_files_policy":"request_review","signed_commits":false},"create_report_incomplete_issue":{},"merge_pull_request":{"max":10},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"push_to_pull_request_branch":{"if_no_changes":"warn","max":10,"max_patch_size":1024,"protect_top_level_dot_folders":true,"protected_files":["package.json","bun.lockb","bunfig.toml","deno.json","deno.jsonc","deno.lock","global.json","NuGet.Config","Directory.Packages.props","mix.exs","mix.lock","go.mod","go.sum","stack.yaml","stack.yaml.lock","pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts","gradle.properties","package-lock.json","yarn.lock","pnpm-lock.yaml","npm-shrinkwrap.json","requirements.txt","Pipfile","Pipfile.lock","pyproject.toml","setup.py","setup.cfg","Gemfile","Gemfile.lock","uv.lock","CODEOWNERS","DESIGN.md","README.md","CONTRIBUTING.md","CHANGELOG.md","SECURITY.md","CODE_OF_CONDUCT.md","AGENTS.md","CLAUDE.md","GEMINI.md"],"signed_commits":false,"target":"*","title_prefix":"🤖 Merge 'main' =\u003e '"},"report_incomplete":{},"update_pull_request":{"allow_body":true,"allow_title":true,"max":10,"update_branch":false}} + GH_AW_SAFE_OUTPUTS_CONFIG_9a64ac31bc43ee2c_EOF + - name: Generate Safe Outputs Tools + env: + GH_AW_TOOLS_META_JSON: | + { + "description_suffixes": { + "add_comment": " CONSTRAINTS: Maximum 10 comment(s) can be added. Target: *. Supports reply_to_id for discussion threading.", + "add_labels": " CONSTRAINTS: Maximum 10 label(s) can be added. Target: *.", + "create_pull_request": " CONSTRAINTS: Maximum 10 pull request(s) can be created.", + "push_to_pull_request_branch": " CONSTRAINTS: Maximum 10 push(es) can be made. The target pull request title must start with \"🤖 Merge 'main' =\u003e '\".", + "update_pull_request": " CONSTRAINTS: Maximum 10 pull request(s) can be updated." + }, + "repo_params": {}, + "dynamic_tools": [] + } + GH_AW_VALIDATION_JSON: | + { + "add_comment": { + "defaultMax": 1, + "fields": { + "body": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 65000 + }, + "item_number": { + "issueOrPRNumber": true + }, + "reply_to_id": { + "type": "string", + "maxLength": 256 + }, + "repo": { + "type": "string", + "maxLength": 256 + } + } + }, + "add_labels": { + "defaultMax": 5, + "fields": { + "item_number": { + "issueNumberOrTemporaryId": true + }, + "labels": { + "required": true, + "type": "array", + "itemType": "string", + "itemSanitize": true, + "itemMaxLength": 128 + }, + "repo": { + "type": "string", + "maxLength": 256 + } + } + }, + "create_pull_request": { + "defaultMax": 1, + "fields": { + "base": { + "type": "string", + "sanitize": true, + "maxLength": 128 + }, + "body": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 65000 + }, + "branch": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 256 + }, + "draft": { + "type": "boolean" + }, + "labels": { + "type": "array", + "itemType": "string", + "itemSanitize": true, + "itemMaxLength": 128 + }, + "repo": { + "type": "string", + "maxLength": 256 + }, + "title": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 128 + } + } + }, + "merge_pull_request": { + "defaultMax": 1, + "fields": { + "commit_message": { + "type": "string", + "sanitize": true, + "maxLength": 65000 + }, + "commit_title": { + "type": "string", + "sanitize": true, + "maxLength": 256 + }, + "merge_method": { + "type": "string", + "enum": [ + "merge", + "squash", + "rebase" + ] + }, + "pull_request_number": { + "issueOrPRNumber": true + }, + "repo": { + "type": "string", + "maxLength": 256 + } + } + }, + "missing_data": { + "defaultMax": 20, + "fields": { + "alternatives": { + "type": "string", + "sanitize": true, + "maxLength": 256 + }, + "context": { + "type": "string", + "sanitize": true, + "maxLength": 256 + }, + "data_type": { + "type": "string", + "sanitize": true, + "maxLength": 128 + }, + "reason": { + "type": "string", + "sanitize": true, + "maxLength": 256 + } + } + }, + "missing_tool": { + "defaultMax": 20, + "fields": { + "alternatives": { + "type": "string", + "sanitize": true, + "maxLength": 512 + }, + "reason": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 256 + }, + "tool": { + "type": "string", + "sanitize": true, + "maxLength": 128 + } + } + }, + "noop": { + "defaultMax": 1, + "fields": { + "message": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 65000 + } + } + }, + "push_to_pull_request_branch": { + "defaultMax": 1, + "fields": { + "branch": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 256 + }, + "message": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 65000 + }, + "pull_request_number": { + "issueOrPRNumber": true + } + } + }, + "report_incomplete": { + "defaultMax": 5, + "fields": { + "details": { + "type": "string", + "sanitize": true, + "maxLength": 65000 + }, + "reason": { + "required": true, + "type": "string", + "sanitize": true, + "maxLength": 1024 + } + } + }, + "update_pull_request": { + "defaultMax": 1, + "fields": { + "body": { + "type": "string", + "sanitize": true, + "maxLength": 65000 + }, + "draft": { + "type": "boolean" + }, + "operation": { + "type": "string", + "enum": [ + "replace", + "append", + "prepend" + ] + }, + "pull_request_number": { + "issueOrPRNumber": true + }, + "repo": { + "type": "string", + "maxLength": 256 + }, + "title": { + "type": "string", + "sanitize": true, + "maxLength": 256 + }, + "update_branch": { + "type": "boolean" + } + }, + "customValidation": "requiresOneOf:title,body,update_branch" + } + } + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/generate_safe_outputs_tools.cjs'); + await main(); + - name: Generate Safe Outputs MCP Server Config + id: safe-outputs-config + run: | + # Generate a secure random API key (360 bits of entropy, 40+ chars) + # Mask immediately to prevent timing vulnerabilities + API_KEY=$(openssl rand -base64 45 | tr -d '/+=') + echo "::add-mask::${API_KEY}" + + PORT=3001 + + # Set outputs for next steps + { + echo "safe_outputs_api_key=${API_KEY}" + echo "safe_outputs_port=${PORT}" + } >> "$GITHUB_OUTPUT" + + echo "Safe Outputs MCP server will run on port ${PORT}" + + - name: Start Safe Outputs MCP HTTP Server + id: safe-outputs-start + env: + DEBUG: '*' + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} + GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-config.outputs.safe_outputs_port }} + GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-config.outputs.safe_outputs_api_key }} + GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/tools.json + GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ runner.temp }}/gh-aw/safeoutputs/config.json + GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs + run: | + # Environment variables are set above to prevent template injection + export DEBUG + export GH_AW_SAFE_OUTPUTS + export GH_AW_SAFE_OUTPUTS_PORT + export GH_AW_SAFE_OUTPUTS_API_KEY + export GH_AW_SAFE_OUTPUTS_TOOLS_PATH + export GH_AW_SAFE_OUTPUTS_CONFIG_PATH + export GH_AW_MCP_LOG_DIR + + bash "${RUNNER_TEMP}/gh-aw/actions/start_safe_outputs_server.sh" + + - name: Start MCP Gateway + id: start-mcp-gateway + env: + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} + GH_AW_SAFE_OUTPUTS_API_KEY: ${{ steps.safe-outputs-start.outputs.api_key }} + GH_AW_SAFE_OUTPUTS_PORT: ${{ steps.safe-outputs-start.outputs.port }} + GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + run: | + set -eo pipefail + mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" + + # Export gateway environment variables for MCP config and gateway script + export MCP_GATEWAY_PORT="8080" + export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_HOST_DOMAIN="localhost" + MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') + echo "::add-mask::${MCP_GATEWAY_API_KEY}" + export MCP_GATEWAY_API_KEY + export MCP_GATEWAY_PAYLOAD_DIR="/tmp/gh-aw/mcp-payloads" + mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" + export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" + export DEBUG="*" + + export GH_AW_ENGINE="copilot" + MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') + MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') + case "${DOCKER_HOST:-}" in + unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; + /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; + * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; + esac + DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' + + mkdir -p /home/runner/.copilot + GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) + cat << GH_AW_MCP_CONFIG_ecdd849dd0c87e2d_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + { + "mcpServers": { + "github": { + "type": "stdio", + "container": "ghcr.io/github/github-mcp-server:v1.1.0", + "env": { + "GITHUB_HOST": "\${GITHUB_SERVER_URL}", + "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", + "GITHUB_READ_ONLY": "1", + "GITHUB_TOOLSETS": "pull_requests,repos" + }, + "guard-policies": { + "allow-only": { + "approval-labels": ${{ steps.parse-guard-vars.outputs.approval_labels }}, + "blocked-users": ${{ steps.parse-guard-vars.outputs.blocked_users }}, + "min-integrity": "approved", + "repos": "all", + "trusted-users": ${{ steps.parse-guard-vars.outputs.trusted_users }} + } + } + }, + "safeoutputs": { + "type": "http", + "url": "http://host.docker.internal:$GH_AW_SAFE_OUTPUTS_PORT", + "headers": { + "Authorization": "\${GH_AW_SAFE_OUTPUTS_API_KEY}" + }, + "guard-policies": { + "write-sink": { + "accept": [ + "*" + ] + } + } + } + }, + "gateway": { + "port": $MCP_GATEWAY_PORT, + "domain": "${MCP_GATEWAY_DOMAIN}", + "apiKey": "${MCP_GATEWAY_API_KEY}", + "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" + } + } + GH_AW_MCP_CONFIG_ecdd849dd0c87e2d_EOF + - name: Mount MCP servers as CLIs + id: mount-mcp-clis + continue-on-error: true + env: + MCP_GATEWAY_API_KEY: ${{ steps.start-mcp-gateway.outputs.gateway-api-key }} + MCP_GATEWAY_DOMAIN: ${{ steps.start-mcp-gateway.outputs.gateway-domain }} + MCP_GATEWAY_PORT: ${{ steps.start-mcp-gateway.outputs.gateway-port }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io); + const { main } = require('${{ runner.temp }}/gh-aw/actions/mount_mcp_as_cli.cjs'); + await main(); + - name: Clean credentials + continue-on-error: true + run: bash "${RUNNER_TEMP}/gh-aw/actions/clean_git_credentials.sh" + - name: Audit pre-agent workspace + id: pre_agent_audit + continue-on-error: true + run: bash "${RUNNER_TEMP}/gh-aw/actions/audit_pre_agent_workspace.sh" + - name: Execute GitHub Copilot CLI + id: agentic_execution + # Copilot CLI tool arguments (sorted): + timeout-minutes: 20 + run: | + set -o pipefail + printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + touch /tmp/gh-aw/agent-step-summary.md + GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) + export GH_AW_NODE_BIN + export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" + (umask 177 && touch /tmp/gh-aw/agent-stdio.log) + printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["*.githubusercontent.com","api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","codeload.github.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","docs.github.com","github-cloud.githubusercontent.com","github-cloud.s3.amazonaws.com","github.blog","github.com","github.githubassets.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","lfs.github.com","objects.githubusercontent.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","patch-diff.githubusercontent.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","www.googleapis.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" + GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json + GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + fi + GH_AW_TOOL_CACHE_MOUNT="" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + if [ -d "$GH_AW_TOOL_CACHE" ]; then + if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then + GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" + fi + elif [ -d "/home/runner/work/_tool" ]; then + GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" + fi + # shellcheck disable=SC1003 + sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + env: + AWF_REFLECT_ENABLED: 1 + COPILOT_AGENT_RUNNER_TYPE: STANDALONE + COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode + COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_MODEL: claude-sonnet-4.5 + GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json + GH_AW_PHASE: agent + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} + GH_AW_VERSION: v0.77.5 + GITHUB_API_URL: ${{ github.api_url }} + GITHUB_AW: true + GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows + GITHUB_HEAD_REF: ${{ github.head_ref }} + GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + GITHUB_REF_NAME: ${{ github.ref_name }} + GITHUB_SERVER_URL: ${{ github.server_url }} + GITHUB_STEP_SUMMARY: /tmp/gh-aw/agent-step-summary.md + GITHUB_WORKSPACE: ${{ github.workspace }} + GIT_AUTHOR_EMAIL: github-actions[bot]@users.noreply.github.com + GIT_AUTHOR_NAME: github-actions[bot] + GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com + GIT_COMMITTER_NAME: github-actions[bot] + RUNNER_TEMP: ${{ runner.temp }} + XDG_CONFIG_HOME: /home/runner + - name: Detect agent errors + if: always() + id: detect-agent-errors + continue-on-error: true + run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" + - name: Configure Git credentials + env: + REPO_NAME: ${{ github.repository }} + SERVER_URL: ${{ github.server_url }} + GITHUB_TOKEN: ${{ github.token }} + run: | + git config --global user.email "github-actions[bot]@users.noreply.github.com" + git config --global user.name "github-actions[bot]" + git config --global am.keepcr true + # Re-authenticate git with GitHub token + SERVER_URL_STRIPPED="${SERVER_URL#https://}" + git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" + echo "Git configured with standard GitHub Actions identity" + - name: Copy Copilot session state files to logs + if: always() + continue-on-error: true + run: bash "${RUNNER_TEMP}/gh-aw/actions/copy_copilot_session_state.sh" + - name: Stop MCP Gateway + if: always() + continue-on-error: true + env: + MCP_GATEWAY_PORT: ${{ steps.start-mcp-gateway.outputs.gateway-port }} + MCP_GATEWAY_API_KEY: ${{ steps.start-mcp-gateway.outputs.gateway-api-key }} + GATEWAY_PID: ${{ steps.start-mcp-gateway.outputs.gateway-pid }} + run: | + bash "${RUNNER_TEMP}/gh-aw/actions/stop_mcp_gateway.sh" "$GATEWAY_PID" + - name: Redact secrets in logs + if: always() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/redact_secrets.cjs'); + await main(); + env: + GH_AW_SECRET_NAMES: 'COPILOT_GITHUB_TOKEN,GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' + SECRET_COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} + SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} + SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Append agent step summary + if: always() + run: bash "${RUNNER_TEMP}/gh-aw/actions/append_agent_step_summary.sh" + - name: Copy Safe Outputs + if: always() + env: + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} + run: | + mkdir -p /tmp/gh-aw + cp "$GH_AW_SAFE_OUTPUTS" /tmp/gh-aw/safeoutputs.jsonl 2>/dev/null || true + - name: Ingest agent output + id: collect_output + if: always() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} + GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,docs.github.com,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" + GITHUB_SERVER_URL: ${{ github.server_url }} + GITHUB_API_URL: ${{ github.api_url }} + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/collect_ndjson_output.cjs'); + await main(); + - name: Parse agent logs for step summary + if: always() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_copilot_log.cjs'); + await main(); + - name: Parse MCP Gateway logs for step summary + if: always() + id: parse-mcp-gateway + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_mcp_gateway_log.cjs'); + await main(); + - name: Print firewall logs + if: always() + continue-on-error: true + env: + AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs + run: | + # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts + # AWF runs with sudo, creating files owned by root + sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true + # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) + if command -v awf &> /dev/null; then + awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" + else + echo 'AWF binary not installed, skipping firewall log summary' + fi + - name: Parse token usage for step summary + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); + await main(); + - name: Print AWF reflect summary + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/awf_reflect_summary.cjs'); + await main(); + - name: Write agent output placeholder if missing + if: always() + run: | + if [ ! -f /tmp/gh-aw/agent_output.json ]; then + echo '{"items":[]}' > /tmp/gh-aw/agent_output.json + fi + - name: Upload agent artifacts + if: always() + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: agent + path: | + /tmp/gh-aw/aw-prompts/prompt.txt + /tmp/gh-aw/sandbox/agent/logs/ + /tmp/gh-aw/redacted-urls.log + /tmp/gh-aw/mcp-logs/ + /tmp/gh-aw/proxy-logs/ + !/tmp/gh-aw/proxy-logs/proxy-tls/ + /tmp/gh-aw/agent_usage.json + /tmp/gh-aw/agent-stdio.log + /tmp/gh-aw/pre-agent-audit.txt + /tmp/gh-aw/agent/ + /tmp/gh-aw/github_rate_limits.jsonl + /tmp/gh-aw/safeoutputs.jsonl + /tmp/gh-aw/agent_output.json + /tmp/gh-aw/aw-*.patch + /tmp/gh-aw/aw-*.bundle + /tmp/gh-aw/awf-config.json + /tmp/gh-aw/sandbox/firewall/logs/ + /tmp/gh-aw/sandbox/firewall/audit/ + /tmp/gh-aw/sandbox/firewall/awf-reflect.json + if-no-files-found: ignore + + conclusion: + needs: + - activation + - agent + - detection + - safe_outputs + if: > + always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || + needs.activation.outputs.stale_lock_file_failed == 'true') + runs-on: ubuntu-slim + permissions: + contents: write + discussions: write + issues: write + pull-requests: write + concurrency: + group: "gh-aw-conclusion-code-radiator" + cancel-in-progress: false + queue: max + outputs: + incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} + noop_message: ${{ steps.noop.outputs.noop_message }} + tools_reported: ${{ steps.missing_tool.outputs.tools_reported }} + total_count: ${{ steps.missing_tool.outputs.total_count }} + steps: + - name: Setup Scripts + id: setup + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + with: + destination: ${{ runner.temp }}/gh-aw/actions + job-name: ${{ github.job }} + trace-id: ${{ needs.activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: "Code Radiator" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/code-radiator.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" + - name: Download agent output artifact + id: download-agent-output + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: agent + path: /tmp/gh-aw/ + - name: Setup agent output environment variable + id: setup-agent-output-env + if: steps.download-agent-output.outcome == 'success' + run: | + mkdir -p /tmp/gh-aw/ + find "/tmp/gh-aw/" -type f -print + echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Process no-op messages + id: noop + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} + GH_AW_NOOP_MAX: "1" + GH_AW_WORKFLOW_NAME: "Code Radiator" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/code-radiator.md" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} + GH_AW_NOOP_REPORT_AS_ISSUE: "true" + with: + github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/handle_noop_message.cjs'); + await main(); + - name: Log detection run + id: detection_runs + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} + GH_AW_WORKFLOW_NAME: "Code Radiator" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/code-radiator.md" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} + GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} + with: + github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/handle_detection_runs.cjs'); + await main(); + - name: Record missing tool + id: missing_tool + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} + GH_AW_MISSING_TOOL_CREATE_ISSUE: "true" + GH_AW_WORKFLOW_NAME: "Code Radiator" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/code-radiator.md" + with: + github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/missing_tool.cjs'); + await main(); + - name: Record incomplete + id: report_incomplete + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} + GH_AW_REPORT_INCOMPLETE_CREATE_ISSUE: "true" + GH_AW_WORKFLOW_NAME: "Code Radiator" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/code-radiator.md" + with: + github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/report_incomplete_handler.cjs'); + await main(); + - name: Handle agent failure + id: handle_agent_failure + if: always() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} + GH_AW_WORKFLOW_NAME: "Code Radiator" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/code-radiator.md" + GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} + GH_AW_WORKFLOW_ID: "code-radiator" + GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "168" + GH_AW_ENGINE_ID: "copilot" + GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} + GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} + GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} + GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} + GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} + GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} + GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} + GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" + GH_AW_CODE_PUSH_FAILURE_ERRORS: ${{ needs.safe_outputs.outputs.code_push_failure_errors }} + GH_AW_CODE_PUSH_FAILURE_COUNT: ${{ needs.safe_outputs.outputs.code_push_failure_count }} + GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} + GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} + GH_AW_GROUP_REPORTS: "false" + GH_AW_FAILURE_REPORT_AS_ISSUE: "true" + GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" + GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" + GH_AW_TIMEOUT_MINUTES: "20" + GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" + with: + github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/handle_agent_failure.cjs'); + await main(); + + detection: + needs: + - activation + - agent + if: > + always() && needs.agent.result != 'skipped' && (needs.agent.outputs.output_types != '' || needs.agent.outputs.has_patch == 'true') + runs-on: ubuntu-latest + permissions: + contents: read + outputs: + detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} + detection_reason: ${{ steps.detection_conclusion.outputs.reason }} + detection_success: ${{ steps.detection_conclusion.outputs.success }} + steps: + - name: Setup Scripts + id: setup + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + with: + destination: ${{ runner.temp }}/gh-aw/actions + job-name: ${{ github.job }} + trace-id: ${{ needs.activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: "Code Radiator" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/code-radiator.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" + - name: Download agent output artifact + id: download-agent-output + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: agent + path: /tmp/gh-aw/ + - name: Setup agent output environment variable + id: setup-agent-output-env + if: steps.download-agent-output.outcome == 'success' + run: | + mkdir -p /tmp/gh-aw/ + find "/tmp/gh-aw/" -type f -print + echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Checkout repository for patch context + if: needs.agent.outputs.has_patch == 'true' + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + # --- Threat Detection --- + - name: Clean stale firewall files from agent artifact + run: | + rm -rf /tmp/gh-aw/sandbox/firewall/logs + rm -rf /tmp/gh-aw/sandbox/firewall/audit + - name: Download container images + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 + - name: Check if detection needed + id: detection_guard + if: always() + env: + OUTPUT_TYPES: ${{ needs.agent.outputs.output_types }} + HAS_PATCH: ${{ needs.agent.outputs.has_patch }} + run: | + if [[ -n "$OUTPUT_TYPES" || "$HAS_PATCH" == "true" ]]; then + echo "run_detection=true" >> "$GITHUB_OUTPUT" + echo "Detection will run: output_types=$OUTPUT_TYPES, has_patch=$HAS_PATCH" + else + echo "run_detection=false" >> "$GITHUB_OUTPUT" + echo "Detection skipped: no agent outputs or patches to analyze" + fi + - name: Clear MCP Config for detection + if: always() && steps.detection_guard.outputs.run_detection == 'true' + run: | + rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" + rm -f /home/runner/.copilot/mcp-config.json + rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" + - name: Prepare threat detection files + if: always() && steps.detection_guard.outputs.run_detection == 'true' + run: | + mkdir -p /tmp/gh-aw/threat-detection/aw-prompts + cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true + if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then + echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." + fi + cp /tmp/gh-aw/agent_output.json /tmp/gh-aw/threat-detection/agent_output.json 2>/dev/null || true + for f in /tmp/gh-aw/aw-*.patch; do + [ -f "$f" ] && cp "$f" /tmp/gh-aw/threat-detection/ 2>/dev/null || true + done + for f in /tmp/gh-aw/aw-*.bundle; do + [ -f "$f" ] && cp "$f" /tmp/gh-aw/threat-detection/ 2>/dev/null || true + done + echo "Prepared threat detection files:" + ls -la /tmp/gh-aw/threat-detection/ 2>/dev/null || true + - name: Setup threat detection + if: always() && steps.detection_guard.outputs.run_detection == 'true' + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + WORKFLOW_NAME: "Code Radiator" + WORKFLOW_DESCRIPTION: "No description provided" + HAS_PATCH: ${{ needs.agent.outputs.has_patch }} + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/setup_threat_detection.cjs'); + await main(); + - name: Ensure threat-detection directory and log + if: always() && steps.detection_guard.outputs.run_detection == 'true' + run: | + mkdir -p /tmp/gh-aw/threat-detection + touch /tmp/gh-aw/threat-detection/detection.log + - name: Setup Node.js + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: '24' + package-manager-cache: false + - name: Install GitHub Copilot CLI + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 + env: + GH_HOST: github.com + - name: Install AWF binary + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 + - name: Execute GitHub Copilot CLI + if: always() && steps.detection_guard.outputs.run_detection == 'true' + continue-on-error: true + id: detection_agentic_execution + # Copilot CLI tool arguments (sorted): + timeout-minutes: 20 + run: | + set -o pipefail + printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt + touch /tmp/gh-aw/agent-step-summary.md + GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) + export GH_AW_NODE_BIN + export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" + (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) + printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" + GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json + GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + fi + GH_AW_TOOL_CACHE_MOUNT="" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + if [ -d "$GH_AW_TOOL_CACHE" ]; then + if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then + GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" + fi + elif [ -d "/home/runner/work/_tool" ]; then + GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" + fi + # shellcheck disable=SC1003 + sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ + -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + env: + AWF_REFLECT_ENABLED: 1 + COPILOT_AGENT_RUNNER_TYPE: STANDALONE + COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode + COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} + COPILOT_MODEL: claude-sonnet-4.5 + GH_AW_PHASE: detection + GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + GH_AW_VERSION: v0.77.5 + GITHUB_API_URL: ${{ github.api_url }} + GITHUB_AW: true + GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows + GITHUB_HEAD_REF: ${{ github.head_ref }} + GITHUB_REF_NAME: ${{ github.ref_name }} + GITHUB_SERVER_URL: ${{ github.server_url }} + GITHUB_STEP_SUMMARY: /tmp/gh-aw/agent-step-summary.md + GITHUB_WORKSPACE: ${{ github.workspace }} + GIT_AUTHOR_EMAIL: github-actions[bot]@users.noreply.github.com + GIT_AUTHOR_NAME: github-actions[bot] + GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com + GIT_COMMITTER_NAME: github-actions[bot] + RUNNER_TEMP: ${{ runner.temp }} + XDG_CONFIG_HOME: /home/runner + - name: Upload threat detection log + if: always() && steps.detection_guard.outputs.run_detection == 'true' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: detection + path: /tmp/gh-aw/threat-detection/detection.log + if-no-files-found: ignore + - name: Parse and conclude threat detection + id: detection_conclusion + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }} + DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }} + GH_AW_DETECTION_CONTINUE_ON_ERROR: "true" + with: + script: | + try { + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_threat_detection_results.cjs'); + await main(); + } catch (loadErr) { + const continueOnError = process.env.GH_AW_DETECTION_CONTINUE_ON_ERROR !== 'false'; + const detectionExecutionFailed = process.env.DETECTION_AGENTIC_EXECUTION_OUTCOME === 'failure'; + const msg = 'ERR_SYSTEM: \u274C Unexpected error loading threat detection module: ' + (loadErr && loadErr.message ? loadErr.message : String(loadErr)); + core.error(msg); + core.setOutput('reason', 'parse_error'); + if (continueOnError && !detectionExecutionFailed) { + core.warning('\u26A0\uFE0F ' + msg); + core.setOutput('conclusion', 'warning'); + core.setOutput('success', 'false'); + } else { + core.setOutput('conclusion', 'failure'); + core.setOutput('success', 'false'); + core.setFailed(msg); + } + } + + safe_outputs: + needs: + - activation + - agent + - detection + if: (!cancelled()) && needs.agent.result != 'skipped' && needs.detection.result == 'success' + runs-on: ubuntu-slim + permissions: + contents: write + discussions: write + issues: write + pull-requests: write + timeout-minutes: 15 + env: + GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/code-radiator" + GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} + GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} + GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} + GH_AW_ENGINE_ID: "copilot" + GH_AW_ENGINE_MODEL: "claude-sonnet-4.5" + GH_AW_ENGINE_VERSION: "1.0.55" + GH_AW_WORKFLOW_ID: "code-radiator" + GH_AW_WORKFLOW_NAME: "Code Radiator" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/code-radiator.md" + outputs: + code_push_failure_count: ${{ steps.process_safe_outputs.outputs.code_push_failure_count }} + code_push_failure_errors: ${{ steps.process_safe_outputs.outputs.code_push_failure_errors }} + comment_id: ${{ steps.process_safe_outputs.outputs.comment_id }} + comment_url: ${{ steps.process_safe_outputs.outputs.comment_url }} + create_discussion_error_count: ${{ steps.process_safe_outputs.outputs.create_discussion_error_count }} + create_discussion_errors: ${{ steps.process_safe_outputs.outputs.create_discussion_errors }} + created_pr_number: ${{ steps.process_safe_outputs.outputs.created_pr_number }} + created_pr_url: ${{ steps.process_safe_outputs.outputs.created_pr_url }} + process_safe_outputs_processed_count: ${{ steps.process_safe_outputs.outputs.processed_count }} + process_safe_outputs_temporary_id_map: ${{ steps.process_safe_outputs.outputs.temporary_id_map }} + push_commit_sha: ${{ steps.process_safe_outputs.outputs.push_commit_sha }} + push_commit_url: ${{ steps.process_safe_outputs.outputs.push_commit_url }} + steps: + - name: Setup Scripts + id: setup + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 + with: + destination: ${{ runner.temp }}/gh-aw/actions + job-name: ${{ github.job }} + trace-id: ${{ needs.activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: "Code Radiator" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/code-radiator.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" + - name: Download agent output artifact + id: download-agent-output + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: agent + path: /tmp/gh-aw/ + - name: Setup agent output environment variable + id: setup-agent-output-env + if: steps.download-agent-output.outcome == 'success' + run: | + mkdir -p /tmp/gh-aw/ + find "/tmp/gh-aw/" -type f -print + echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" + - name: Download patch artifact + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: agent + path: /tmp/gh-aw/ + - name: Extract base branch from agent output + id: extract-base-branch + if: steps.download-agent-output.outcome == 'success' + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/extract_base_branch_from_agent_output.cjs'); + await main(); + - name: Checkout repository (trusted default branch for comment events) + if: ((!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') || (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'push_to_pull_request_branch')) && (github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment') + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: ${{ github.event.repository.default_branch }} + token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + persist-credentials: false + fetch-depth: 0 + - name: Checkout repository + if: ((!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') || (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'push_to_pull_request_branch')) && github.event_name != 'issue_comment' && github.event_name != 'pull_request_review_comment' + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: ${{ steps.extract-base-branch.outputs.base-branch || github.base_ref || github.event.pull_request.base.ref || github.ref_name || github.event.repository.default_branch }} + token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + persist-credentials: false + fetch-depth: 0 + - name: Configure Git credentials + if: (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'create_pull_request') || (!cancelled()) && needs.agent.result != 'skipped' && contains(needs.agent.outputs.output_types, 'push_to_pull_request_branch') + env: + REPO_NAME: ${{ github.repository }} + SERVER_URL: ${{ github.server_url }} + GIT_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + run: | + git config --global user.email "github-actions[bot]@users.noreply.github.com" + git config --global user.name "github-actions[bot]" + git config --global am.keepcr true + # Re-authenticate git with GitHub token + SERVER_URL_STRIPPED="${SERVER_URL#https://}" + git remote set-url origin "https://x-access-token:${GIT_TOKEN}@${SERVER_URL_STRIPPED}/${REPO_NAME}.git" + echo "Git configured with standard GitHub Actions identity" + - name: Configure GH_HOST for enterprise compatibility + id: ghes-host-config + shell: bash + run: | + # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct + # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. + GH_HOST="${GITHUB_SERVER_URL#https://}" + GH_HOST="${GH_HOST#http://}" + echo "GH_HOST=${GH_HOST}" >> "$GITHUB_ENV" + - name: Process Safe Outputs + id: process_safe_outputs + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} + GH_AW_COMMENT_ID: ${{ needs.activation.outputs.comment_id }} + GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,docs.github.com,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" + GITHUB_SERVER_URL: ${{ github.server_url }} + GITHUB_API_URL: ${{ github.api_url }} + GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"add_comment\":{\"max\":10,\"target\":\"*\"},\"add_labels\":{\"max\":10,\"target\":\"*\"},\"create_pull_request\":{\"allowed_base_branches\":[\"net*.0\",\"xcode*\",\"xcode*.*\"],\"max\":10,\"max_patch_files\":1000,\"max_patch_size\":1024,\"protect_top_level_dot_folders\":true,\"protected_files\":[\"package.json\",\"bun.lockb\",\"bunfig.toml\",\"deno.json\",\"deno.jsonc\",\"deno.lock\",\"global.json\",\"NuGet.Config\",\"Directory.Packages.props\",\"mix.exs\",\"mix.lock\",\"go.mod\",\"go.sum\",\"stack.yaml\",\"stack.yaml.lock\",\"pom.xml\",\"build.gradle\",\"build.gradle.kts\",\"settings.gradle\",\"settings.gradle.kts\",\"gradle.properties\",\"package-lock.json\",\"yarn.lock\",\"pnpm-lock.yaml\",\"npm-shrinkwrap.json\",\"requirements.txt\",\"Pipfile\",\"Pipfile.lock\",\"pyproject.toml\",\"setup.py\",\"setup.cfg\",\"Gemfile\",\"Gemfile.lock\",\"uv.lock\",\"CODEOWNERS\",\"DESIGN.md\",\"README.md\",\"CONTRIBUTING.md\",\"CHANGELOG.md\",\"SECURITY.md\",\"CODE_OF_CONDUCT.md\",\"AGENTS.md\",\"CLAUDE.md\",\"GEMINI.md\"],\"protected_files_policy\":\"request_review\",\"signed_commits\":false},\"create_report_incomplete_issue\":{},\"merge_pull_request\":{\"max\":10},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"true\"},\"push_to_pull_request_branch\":{\"if_no_changes\":\"warn\",\"max\":10,\"max_patch_size\":1024,\"protect_top_level_dot_folders\":true,\"protected_files\":[\"package.json\",\"bun.lockb\",\"bunfig.toml\",\"deno.json\",\"deno.jsonc\",\"deno.lock\",\"global.json\",\"NuGet.Config\",\"Directory.Packages.props\",\"mix.exs\",\"mix.lock\",\"go.mod\",\"go.sum\",\"stack.yaml\",\"stack.yaml.lock\",\"pom.xml\",\"build.gradle\",\"build.gradle.kts\",\"settings.gradle\",\"settings.gradle.kts\",\"gradle.properties\",\"package-lock.json\",\"yarn.lock\",\"pnpm-lock.yaml\",\"npm-shrinkwrap.json\",\"requirements.txt\",\"Pipfile\",\"Pipfile.lock\",\"pyproject.toml\",\"setup.py\",\"setup.cfg\",\"Gemfile\",\"Gemfile.lock\",\"uv.lock\",\"CODEOWNERS\",\"DESIGN.md\",\"README.md\",\"CONTRIBUTING.md\",\"CHANGELOG.md\",\"SECURITY.md\",\"CODE_OF_CONDUCT.md\",\"AGENTS.md\",\"CLAUDE.md\",\"GEMINI.md\"],\"signed_commits\":false,\"target\":\"*\",\"title_prefix\":\"🤖 Merge 'main' =\\u003e '\"},\"report_incomplete\":{},\"update_pull_request\":{\"allow_body\":true,\"allow_title\":true,\"max\":10,\"update_branch\":false}}" + GH_AW_CI_TRIGGER_TOKEN: ${{ secrets.GH_AW_CI_TRIGGER_TOKEN }} + with: + github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/safe_output_handler_manager.cjs'); + await main(); + - name: Upload Safe Outputs Items + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: safe-outputs-items + path: | + /tmp/gh-aw/safe-output-items.jsonl + /tmp/gh-aw/temporary-id-map.json + if-no-files-found: ignore + diff --git a/.github/workflows/code-radiator.md b/.github/workflows/code-radiator.md new file mode 100644 index 000000000000..e1fe86d0d97d --- /dev/null +++ b/.github/workflows/code-radiator.md @@ -0,0 +1,190 @@ +--- +on: + schedule: daily + workflow_dispatch: + roles: [admin, maintain, write] +concurrency: + group: "code-radiator-${{ github.ref || github.run_id }}" + cancel-in-progress: true +permissions: + contents: read + pull-requests: read +engine: + id: copilot + model: claude-sonnet-4.5 +network: + allowed: + - defaults + - github +tools: + github: + toolsets: [pull_requests, repos] + min-integrity: approved + bash: true +checkout: + fetch: ["*"] + fetch-depth: 0 +safe-outputs: + max-patch-files: 1000 + create-pull-request: + max: 10 + signed-commits: false + allowed-base-branches: + - "net*.0" + - "xcode*" + - "xcode*.*" + add-comment: + max: 10 + target: "*" + add-labels: + max: 10 + target: "*" + merge-pull-request: + max: 10 + push-to-pull-request-branch: + max: 10 + signed-commits: false + target: "*" + required-title-prefix: "🤖 Merge 'main' => '" + update-pull-request: + max: 10 +--- + +# Code Radiator + +Merge code from `main` into active target branches, creating pull requests for each. + +## Target Branch Patterns + +Only consider remote branches matching these patterns: +- `net*.0` (e.g., `net11.0`, `net10.0`) +- `xcode*` (e.g., `xcode26`) +- `xcode*.*` (e.g., `xcode26.4`) + +Only process branches that have had commits in the last 30 days. + +## Workflow + +### 1. Identify Target Branches + +```bash +# List remote branches matching target patterns with recent activity +git fetch origin +git for-each-ref --sort=-committerdate --format='%(refname:short) %(committerdate:iso8601)' refs/remotes/origin/ +``` + +Filter to branches matching the patterns above AND having a commit within the last month. + +### 2. For Each Target Branch + +#### a. Determine the local branch name + +The local branch name is: `merge/main-to--` (e.g., `merge/main-to-net11.0-20260506`). + +#### b. Check for existing pull requests + +Search for an open PR with: +- Base: the target branch +- Title matching: `🤖 Merge 'main' => ''` + +If a matching PR exists: +- If it is a **draft**: add a comment saying "⏭️ Skipping merge update: this PR is a draft. Convert to ready when you want automated updates to resume." and **skip** this target. +- If it is **not a draft**: use its head branch name as the local branch name (to update the existing PR). + +#### c. Update from target branch + +If updating an existing PR, first merge the target branch into the PR branch to incorporate any new commits from the target: + +```bash +git checkout -B "" "origin/" +git merge "origin/" --no-edit -m "Merge branch '' into ''" +``` + +If creating a new branch, start from the target: + +```bash +git checkout -B "" "origin/" +``` + +#### d. Merge main + +```bash +git merge origin/main --no-edit -m "Merge branch 'main' into ''" +``` + +#### e. Resolve merge conflicts + +If there are merge conflicts: + +**For files under `tests/dotnet/UnitTests/expected/`:** +- Do not include these files in the merge commit at all. Remove them from the index: + ```bash + git rm --cached + ``` + +**For `eng/Version.Details.props` or `eng/Version.Details.xml`:** +- Parse both the `origin/main` and `origin/` versions of the file as XML. +- For each `` element present in both files, keep the one with the **higher** `` value. +- Use semantic version comparison (split on `.`, `-`, `+` and compare numerically). +- Write the merged result and `git add` the file. + +**For `NuGet.config`:** +- Include all package source feeds from both the source (main) and target branches. +- If a feed exists in both with the same key but different URL, keep both (rename the key from main to avoid collision). +- Write the merged result and `git add` the file. + +**For any other conflicting files:** +- Do your best to resolve them using context and judgment. +- If you resolved any "other" conflicts (not covered by the rules above), mark the PR for human review: + - Do **not** enable automerge (and disable it if already enabled). + - Add the `do-not-merge` label. + - Add a comment requesting human review of the conflict resolution, listing which files were manually resolved. + +#### e. Create or update the PR + +Do **NOT** run `git push` manually. The safeoutputs tool handles pushing. + +Use the `create_pull_request` safeoutput tool to push the branch and create/update the PR: +- `branch`: `` (e.g., `merge/main-to-net11.0-20260527`) +- `base`: `` (e.g., `net11.0`) — **always provide this field** +- `title`: `🤖 Merge 'main' => ''` +- `body`: `Automated merge of \`main\` into \`\`.\n\nCreated by the code-radiator workflow.` + +> **Important**: Do NOT unset the upstream tracking branch. After `git checkout -B "" "origin/"`, the upstream is set to `origin/`. Keep it set — the safeoutputs tool relies on this to detect the commits to push. + +After creating the PR, enable automerge (merge strategy) using the GitHub MCP `enable_auto_merge` tool or `gh pr merge --auto --merge`. + +### 3. Summary + +After processing all branches, report: +- Which PRs were created (with links) +- Which PRs were updated +- Which branches were skipped (draft PRs, no conflicts resolution possible) +- Which branches had no diff (main already merged) + +## Conflict Resolution Details + +### Version file merge algorithm + +For `eng/Version.Details.props` and `eng/Version.Details.xml`: + +1. Parse both XML files. +2. Build a map of `Dependency[@Name]` → `Version` text from each file. +3. For each dependency present in either file, select the higher version. +4. Use the target branch's file as the base structure, updating versions where main has higher values. +5. Dependencies that exist only in main should be added to the result. + +### Version comparison + +Split version strings on `.`, `-`, and `+`. Compare each segment numerically. Example: +- `9.0.0-preview.1.24080.9` vs `9.0.0-preview.2.24101.3` → second is higher. + +## Important Notes + +- Never force push. +- Do NOT run `git push` manually — the safeoutputs `create_pull_request` tool handles pushing. +- Do NOT unset the upstream tracking branch after creating the local branch. The safeoutputs tool uses `@{upstream}` to detect commits that need to be pushed. Unsetting the upstream causes the tool to report "No changes to commit - no commits found" even when commits exist. +- Always provide the `base` branch when calling `safeoutputs create_pull_request` (e.g., `base: "net11.0"`). +- The workflow operates on the current repository checkout. +- Run `git fetch origin` before starting to ensure up-to-date remote refs. +- Use the GitHub MCP tools or `gh` CLI for non-push PR operations (comment, list, merge --auto, enable automerge). diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml new file mode 100644 index 000000000000..451d17b79bd5 --- /dev/null +++ b/.github/workflows/copilot-setup-steps.yml @@ -0,0 +1,28 @@ +name: "Copilot Setup Steps" + +# This workflow configures the environment for GitHub Copilot Agent with gh-aw MCP server +on: + workflow_dispatch: + push: + paths: + - .github/workflows/copilot-setup-steps.yml + +jobs: + # The job MUST be called 'copilot-setup-steps' to be recognized by GitHub Copilot Agent + copilot-setup-steps: + runs-on: ubuntu-latest + + # Set minimal permissions for setup steps + # Copilot Agent receives its own token with appropriate permissions + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + - name: Install gh-aw extension + uses: github/gh-aw-actions/setup-cli@efa55847f72aadb03490d955263ff911bf758700 # v0.74.8 + with: + version: v0.74.8 diff --git a/.github/workflows/inter-branch-merge-flow.yml b/.github/workflows/inter-branch-merge-flow.yml index 35a5b4584b4f..7c95ddd17a32 100644 --- a/.github/workflows/inter-branch-merge-flow.yml +++ b/.github/workflows/inter-branch-merge-flow.yml @@ -16,13 +16,13 @@ name: Inter-branch merge workflow on: - push: - branches: - - main + # allow triggering this action manually + workflow_dispatch: - # Run every day at 3:00 AM UTC - schedule: - - cron: '0 3 * * *' +# Disable for now, trying out an agentic workflow +# # Run every day at 3:00 AM UTC +# schedule: +# - cron: '0 3 * * *' permissions: contents: write @@ -30,4 +30,4 @@ permissions: jobs: Merge: - uses: dotnet/arcade/.github/workflows/inter-branch-merge-base.yml@main + uses: dotnet/arcade/.github/workflows/inter-branch-merge-base.yml@b36a3594d11b8d56bf7d3dbce919e0688715d5ec # main diff --git a/.github/workflows/label-checker.yml b/.github/workflows/label-checker.yml deleted file mode 100644 index 58a7169aa78d..000000000000 --- a/.github/workflows/label-checker.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Labels verification -on: - pull_request: - types: [opened, reopened, labeled, unlabeled, synchronize] - -permissions: - contents: read - -jobs: - labels-check: - permissions: - contents: none - runs-on: ubuntu-latest - name: Labels verification - - steps: - - run: exit 0 - name: 'Monojenkins PR' - # always happy if monojenkins - if: github.actor == 'vs-mobiletools-engineering-service2' || github.actor == 'github-actions[bot]' || github.actor == 'dotnet-maestro[bot]' - - - run: exit 1 - name: 'User PR with no labels' - # failure if not monojenkins and not dotnet-maestro and no labels - if: github.actor != 'vs-mobiletools-engineering-service2' && github.actor != 'dotnet-maestro[bot]' && join(github.event.pull_request.labels, ',') == '' - - - run: exit 0 - name: 'User PR with labels' - # success if not monojenkins but labels - if: github.actor != 'vs-mobiletools-engineering-service2' && github.actor != 'dotnet-maestro[bot]' && join(github.event.pull_request.labels, ',') != '' diff --git a/.github/workflows/localization-update.yml b/.github/workflows/localization-update.yml deleted file mode 100644 index 4e7c3b47a0ce..000000000000 --- a/.github/workflows/localization-update.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Get Localization Translations -on: - push: - branches: - - "lego/*" - -permissions: - contents: read - -jobs: - pull-request: - permissions: - contents: read # for actions/checkout to fetch code - pull-requests: write # for repo-sync/pull-request to create pull requests - name: '[Localization PR to main]' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - name: checkout - - - uses: repo-sync/pull-request@v2 - name: pull-request - with: - destination_branch: "main" - pr_title: "[Localization] Pulling New Localization Translations $GITHUB_RUN_ID" - pr_body: "Automated PR. Bring new translated changes in the lcl files for OneLocBuild to create translated resx files." - pr_label: "localization_bot,not-notes-worthy" - pr_milestone: "Future" - pr_allow_empty: false - github_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/localization_branch_sync.yml b/.github/workflows/localization_branch_sync.yml deleted file mode 100644 index 93f6ad852dc0..000000000000 --- a/.github/workflows/localization_branch_sync.yml +++ /dev/null @@ -1,32 +0,0 @@ -# Disabling this action since we do something similar already in the CI - -name: Sync Localization Branch -on: - pull_request: - branches: - - 'main' - types: [closed] - -concurrency: - group: 'Localization-Sync' - cancel-in-progress: false - -jobs: - replaceLocalizationBranch: - name: 'Replace Localization Branch' - runs-on: ubuntu-latest - if: ${{ github.event.pull_request.merged == true && github.event.pull_request.user.login == 'github-actions[bot]' && contains(github.event.pull_request.labels.*.name, 'localization_bot') }} - steps: - - uses: dawidd6/action-delete-branch@v3 - name: 'delete' - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - branches: Localization - soft_fail: true - - - uses: peterjgrainger/action-create-branch@v4.0.0 - name: 'Create Localization Branch' - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - branch: 'Localization' diff --git a/.github/workflows/macios-reviewer.lock.yml b/.github/workflows/macios-reviewer.lock.yml index 96544eebf0de..582956c5136e 100644 --- a/.github/workflows/macios-reviewer.lock.yml +++ b/.github/workflows/macios-reviewer.lock.yml @@ -1,5 +1,5 @@ -# gh-aw-metadata: {"schema_version":"v3","frontmatter_hash":"a4ffe1d52364aca7fafba9ba975ec40a3f4fc4908801119268fc1812f9b09cbe","compiler_version":"v0.71.1","strict":true,"agent_id":"copilot","agent_model":"claude-sonnet-4.5"} -# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"239aec45b78c8799417efdd5bc6d8cc036629ec1","version":"v0.71.1"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.28","digest":"sha256:a8834e285807654bf680154faa710d43fe4365a0868142f5c20e48c85e137a7a","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.25.28@sha256:a8834e285807654bf680154faa710d43fe4365a0868142f5c20e48c85e137a7a"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.28","digest":"sha256:93290f2393752252911bd7c39a047f776c0b53063575e7bde4e304962a9a61cb","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.28@sha256:93290f2393752252911bd7c39a047f776c0b53063575e7bde4e304962a9a61cb"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.28","digest":"sha256:844c18280f82cd1b06345eb2f4e91966b34185bfc51c9f237c3e022e848fb474","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.25.28@sha256:844c18280f82cd1b06345eb2f4e91966b34185bfc51c9f237c3e022e848fb474"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.0","digest":"sha256:9c2228324fb1f26f39dc9471612e530ae3efc3156dac05efb2e8d212878d454d","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.3.0@sha256:9c2228324fb1f26f39dc9471612e530ae3efc3156dac05efb2e8d212878d454d"},{"image":"ghcr.io/github/github-mcp-server:v1.0.2","digest":"sha256:26db03408086a99cf1916348dcc4f9614206658f9082a8060dc7c81ad787f4ba","pinned_image":"ghcr.io/github/github-mcp-server:v1.0.2@sha256:26db03408086a99cf1916348dcc4f9614206658f9082a8060dc7c81ad787f4ba"},{"image":"node:lts-alpine","digest":"sha256:d1b3b4da11eefd5941e7f0b9cf17783fc99d9c6fc34884a665f40a06dbdfc94f","pinned_image":"node:lts-alpine@sha256:d1b3b4da11eefd5941e7f0b9cf17783fc99d9c6fc34884a665f40a06dbdfc94f"}]} +# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"a0f64139dbc6fe8697f9fd99f5489155b561c37ec0b13d7eaf30bda56d034e7f","body_hash":"62e09281b84230e857c88588f55f5794cfba9d3e9ff9021d9528645b9b3c2965","compiler_version":"v0.77.5","strict":true,"agent_id":"copilot","agent_model":"claude-sonnet-4.5"} +# gh-aw-manifest: {"version":1,"secrets":["COPILOT_GITHUB_TOKEN","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/checkout","sha":"de0fac2e4500dabe0009e67214ff5f5447ce83dd","version":"v6.0.2"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/setup-node","sha":"48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e","version":"v6.4.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"3ea13c02d765410340d533515cb31a7eef2baaf0","version":"v0.77.5"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.25.58"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.3.22"},{"image":"ghcr.io/github/github-mcp-server:v1.1.0"},{"image":"node:lts-alpine","digest":"sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14","pinned_image":"node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14"}]} # ___ _ _ # / _ \ | | (_) # | |_| | __ _ ___ _ __ | |_ _ ___ @@ -14,7 +14,7 @@ # \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ # \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ # -# This file was automatically generated by gh-aw (v0.71.1). DO NOT EDIT. +# This file was automatically generated by gh-aw (v0.77.5). DO NOT EDIT. # # To update this file, edit the corresponding .md file and run: # gh aw compile @@ -32,34 +32,35 @@ # Custom actions used: # - actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 # - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 -# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 +# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 # - actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 # - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@239aec45b78c8799417efdd5bc6d8cc036629ec1 # v0.71.1 +# - github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 # # Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.25.28@sha256:a8834e285807654bf680154faa710d43fe4365a0868142f5c20e48c85e137a7a -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.28@sha256:93290f2393752252911bd7c39a047f776c0b53063575e7bde4e304962a9a61cb -# - ghcr.io/github/gh-aw-firewall/squid:0.25.28@sha256:844c18280f82cd1b06345eb2f4e91966b34185bfc51c9f237c3e022e848fb474 -# - ghcr.io/github/gh-aw-mcpg:v0.3.0@sha256:9c2228324fb1f26f39dc9471612e530ae3efc3156dac05efb2e8d212878d454d -# - ghcr.io/github/github-mcp-server:v1.0.2@sha256:26db03408086a99cf1916348dcc4f9614206658f9082a8060dc7c81ad787f4ba -# - node:lts-alpine@sha256:d1b3b4da11eefd5941e7f0b9cf17783fc99d9c6fc34884a665f40a06dbdfc94f +# - ghcr.io/github/gh-aw-firewall/agent:0.25.58 +# - ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 +# - ghcr.io/github/gh-aw-firewall/squid:0.25.58 +# - ghcr.io/github/gh-aw-mcpg:v0.3.22 +# - ghcr.io/github/github-mcp-server:v1.1.0 +# - node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 name: ".NET for Apple Platforms PR Reviewer" -"on": +on: issue_comment: types: - created - edited # roles: # Roles processed as role check in pre-activation job # - admin # Roles processed as role check in pre-activation job - # - maintainer # Roles processed as role check in pre-activation job + # - maintain # Roles processed as role check in pre-activation job # - write # Roles processed as role check in pre-activation job permissions: {} concurrency: - group: "gh-aw-${{ github.workflow }}-${{ github.event.issue.number || github.event.pull_request.number || github.run_id }}" + cancel-in-progress: false + group: macios-reviewer-${{ github.event.issue.number || github.event.pull_request.number || github.run_id }} run-name: ".NET for Apple Platforms PR Reviewer" @@ -72,6 +73,7 @@ jobs: actions: read contents: read issues: write + pull-requests: write outputs: body: ${{ steps.sanitized.outputs.body }} comment_id: ${{ steps.add-comment.outputs.comment-id }} @@ -81,6 +83,8 @@ jobs: lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} model: ${{ steps.generate_aw_info.outputs.model }} secret_verification_result: ${{ steps.validate-secret.outputs.verification_result }} + setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} + setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} slash_command: ${{ needs.pre_activation.outputs.matched_command }} stale_lock_file_failed: ${{ steps.check-lock-file.outputs.stale_lock_file_failed == 'true' }} @@ -89,31 +93,38 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@239aec45b78c8799417efdd5bc6d8cc036629ec1 # v0.71.1 + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} trace-id: ${{ needs.pre_activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.pre_activation.outputs.setup-parent-span-id || needs.pre_activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/macios-reviewer.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" - name: Generate agentic run info id: generate_aw_info env: GH_AW_INFO_ENGINE_ID: "copilot" GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" GH_AW_INFO_MODEL: "claude-sonnet-4.5" - GH_AW_INFO_VERSION: "1.0.35" - GH_AW_INFO_AGENT_VERSION: "1.0.35" - GH_AW_INFO_CLI_VERSION: "v0.71.1" + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AGENT_VERSION: "1.0.55" + GH_AW_INFO_CLI_VERSION: "v0.77.5" GH_AW_INFO_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" GH_AW_INFO_EXPERIMENTAL: "false" GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" GH_AW_INFO_STAGED: "false" GH_AW_INFO_ALLOWED_DOMAINS: '["defaults","dotnet","github","aka.ms","dev.azure.com","microsoft.com","vsassets.io"]' GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.25.28" + GH_AW_INFO_AWF_VERSION: "v0.25.58" GH_AW_INFO_AWMG_VERSION: "" GH_AW_INFO_FIREWALL_TYPE: "squid" GH_AW_COMPILED_STRICT: "true" - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -123,7 +134,7 @@ jobs: - name: Add eyes reaction for immediate feedback id: react if: github.event_name == 'issues' || github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment' || github.event_name == 'discussion' || github.event_name == 'discussion_comment' || github.event_name == 'pull_request' && github.event.pull_request.head.repo.id == github.repository_id - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_REACTION: "eyes" with: @@ -145,22 +156,24 @@ jobs: sparse-checkout: | .github .agents + .antigravity .claude .codex .crush .gemini .opencode + .pi sparse-checkout-cone-mode: true fetch-depth: 1 - name: Save agent config folders for base branch restoration env: - GH_AW_AGENT_FOLDERS: ".agents .claude .codex .crush .gemini .github .opencode" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md CLAUDE.md GEMINI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" # poutine:ignore untrusted_checkout_exec run: bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - name: Check workflow lock file id: check-lock-file - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_WORKFLOW_FILE: "macios-reviewer.lock.yml" GH_AW_CONTEXT_WORKFLOW_REF: "${{ github.workflow_ref }}" @@ -171,9 +184,9 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/check_workflow_timestamp_api.cjs'); await main(); - name: Check compile-agentic version - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_COMPILED_VERSION: "v0.71.1" + GH_AW_COMPILED_VERSION: "v0.77.5" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -182,9 +195,9 @@ jobs: await main(); - name: Compute current body text id: sanitized - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,*.vsblob.vsassets.io,aka.ms,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.nuget.org,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,azuresearch-usnc.nuget.org,azuresearch-ussc.nuget.org,builds.dotnet.microsoft.com,ci.dot.net,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,dc.services.visualstudio.com,dev.azure.com,dist.nuget.org,docs.github.com,dot.net,dotnet.microsoft.com,dotnetcli.blob.core.windows.net,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,microsoft.com,nuget.org,nuget.pkg.github.com,nugetregistryv2prod.blob.core.windows.net,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,oneocsp.microsoft.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,pkgs.dev.azure.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,vsassets.io,www.googleapis.com,www.microsoft.com" + GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,*.vsblob.vsassets.io,aka.ms,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.nuget.org,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,azuresearch-usnc.nuget.org,azuresearch-ussc.nuget.org,builds.dotnet.microsoft.com,ci.dot.net,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,dc.services.visualstudio.com,dev.azure.com,dist.nuget.org,docs.github.com,dot.net,dotnet.microsoft.com,dotnetcli.blob.core.windows.net,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,microsoft.com,nuget.org,nuget.pkg.github.com,nugetregistryv2prod.blob.core.windows.net,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,oneocsp.microsoft.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,pkgs.dev.azure.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,vsassets.io,www.googleapis.com,www.microsoft.com" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -194,7 +207,7 @@ jobs: - name: Add comment with workflow run link id: add-comment if: github.event_name == 'issues' || github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment' || github.event_name == 'discussion' || github.event_name == 'discussion_comment' || github.event_name == 'pull_request' && github.event.pull_request.head.repo.id == github.repository_id - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" with: @@ -207,11 +220,11 @@ jobs: env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ runner.temp }}/gh-aw/safeoutputs/outputs.jsonl + GH_AW_EXPR_1A3A194A: ${{ github.event.discussion.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'discussion' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_463A214A: ${{ github.event.pull_request.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'pull_request' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_802A9F6A: ${{ github.event.issue.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'issue' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_FF1D34CE: ${{ github.event.comment.id || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').comment_id }} GH_AW_GITHUB_ACTOR: ${{ github.actor }} - GH_AW_GITHUB_EVENT_COMMENT_ID: ${{ github.event.comment.id }} - GH_AW_GITHUB_EVENT_DISCUSSION_NUMBER: ${{ github.event.discussion.number }} - GH_AW_GITHUB_EVENT_ISSUE_NUMBER: ${{ github.event.issue.number }} - GH_AW_GITHUB_EVENT_PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }} GH_AW_GITHUB_REPOSITORY: ${{ github.repository }} GH_AW_GITHUB_RUN_ID: ${{ github.run_id }} GH_AW_GITHUB_WORKSPACE: ${{ github.workspace }} @@ -220,59 +233,63 @@ jobs: run: | bash "${RUNNER_TEMP}/gh-aw/actions/create_prompt_first.sh" { - cat << 'GH_AW_PROMPT_31522cd090dd3137_EOF' + cat << 'GH_AW_PROMPT_33adc77fba6f068a_EOF' - GH_AW_PROMPT_31522cd090dd3137_EOF + GH_AW_PROMPT_33adc77fba6f068a_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/xpia.md" cat "${RUNNER_TEMP}/gh-aw/prompts/temp_folder_prompt.md" cat "${RUNNER_TEMP}/gh-aw/prompts/markdown.md" cat "${RUNNER_TEMP}/gh-aw/prompts/safe_outputs_prompt.md" - cat << 'GH_AW_PROMPT_31522cd090dd3137_EOF' + cat << 'GH_AW_PROMPT_33adc77fba6f068a_EOF' Tools: create_pull_request_review_comment(max:50), submit_pull_request_review, missing_tool, missing_data, noop + GH_AW_PROMPT_33adc77fba6f068a_EOF + cat "${RUNNER_TEMP}/gh-aw/prompts/mcp_cli_tools_prompt.md" + cat << 'GH_AW_PROMPT_33adc77fba6f068a_EOF' The following GitHub context information is available for this workflow: - {{#if __GH_AW_GITHUB_ACTOR__ }} + {{#if github.actor}} - **actor**: __GH_AW_GITHUB_ACTOR__ {{/if}} - {{#if __GH_AW_GITHUB_REPOSITORY__ }} + {{#if github.repository}} - **repository**: __GH_AW_GITHUB_REPOSITORY__ {{/if}} - {{#if __GH_AW_GITHUB_WORKSPACE__ }} + {{#if github.workspace}} - **workspace**: __GH_AW_GITHUB_WORKSPACE__ {{/if}} - {{#if __GH_AW_GITHUB_EVENT_ISSUE_NUMBER__ }} - - **issue-number**: #__GH_AW_GITHUB_EVENT_ISSUE_NUMBER__ + {{#if github.event.issue.number || (github.aw.context.item_type == 'issue' && github.aw.context.item_number)}} + - **issue-number**: #__GH_AW_EXPR_802A9F6A__ {{/if}} - {{#if __GH_AW_GITHUB_EVENT_DISCUSSION_NUMBER__ }} - - **discussion-number**: #__GH_AW_GITHUB_EVENT_DISCUSSION_NUMBER__ + {{#if github.event.discussion.number || (github.aw.context.item_type == 'discussion' && github.aw.context.item_number)}} + - **discussion-number**: #__GH_AW_EXPR_1A3A194A__ {{/if}} - {{#if __GH_AW_GITHUB_EVENT_PULL_REQUEST_NUMBER__ }} - - **pull-request-number**: #__GH_AW_GITHUB_EVENT_PULL_REQUEST_NUMBER__ + {{#if github.event.pull_request.number || (github.aw.context.item_type == 'pull_request' && github.aw.context.item_number)}} + - **pull-request-number**: #__GH_AW_EXPR_463A214A__ {{/if}} - {{#if __GH_AW_GITHUB_EVENT_COMMENT_ID__ }} - - **comment-id**: __GH_AW_GITHUB_EVENT_COMMENT_ID__ + {{#if github.event.comment.id || github.aw.context.comment_id}} + - **comment-id**: __GH_AW_EXPR_FF1D34CE__ {{/if}} - {{#if __GH_AW_GITHUB_RUN_ID__ }} + {{#if github.run_id}} - **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__ {{/if}} - GH_AW_PROMPT_31522cd090dd3137_EOF + GH_AW_PROMPT_33adc77fba6f068a_EOF cat "${RUNNER_TEMP}/gh-aw/prompts/github_mcp_tools_with_safeoutputs_prompt.md" if [ "$GITHUB_EVENT_NAME" = "issue_comment" ] && [ -n "$GH_AW_IS_PR_COMMENT" ] || [ "$GITHUB_EVENT_NAME" = "pull_request_review_comment" ] || [ "$GITHUB_EVENT_NAME" = "pull_request_review" ]; then cat "${RUNNER_TEMP}/gh-aw/prompts/pr_context_prompt.md" fi - cat << 'GH_AW_PROMPT_31522cd090dd3137_EOF' + cat << 'GH_AW_PROMPT_33adc77fba6f068a_EOF' {{#runtime-import .github/workflows/macios-reviewer.md}} - GH_AW_PROMPT_31522cd090dd3137_EOF + GH_AW_PROMPT_33adc77fba6f068a_EOF } > "$GH_AW_PROMPT" - name: Interpolate variables and render templates - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + GH_AW_ENGINE_ID: "copilot" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -280,18 +297,19 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/interpolate_prompt.cjs'); await main(); - name: Substitute placeholders - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt + GH_AW_EXPR_1A3A194A: ${{ github.event.discussion.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'discussion' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_463A214A: ${{ github.event.pull_request.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'pull_request' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_802A9F6A: ${{ github.event.issue.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'issue' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} + GH_AW_EXPR_FF1D34CE: ${{ github.event.comment.id || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').comment_id }} GH_AW_GITHUB_ACTOR: ${{ github.actor }} - GH_AW_GITHUB_EVENT_COMMENT_ID: ${{ github.event.comment.id }} - GH_AW_GITHUB_EVENT_DISCUSSION_NUMBER: ${{ github.event.discussion.number }} - GH_AW_GITHUB_EVENT_ISSUE_NUMBER: ${{ github.event.issue.number }} - GH_AW_GITHUB_EVENT_PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }} GH_AW_GITHUB_REPOSITORY: ${{ github.repository }} GH_AW_GITHUB_RUN_ID: ${{ github.run_id }} GH_AW_GITHUB_WORKSPACE: ${{ github.workspace }} GH_AW_IS_PR_COMMENT: ${{ github.event.issue.pull_request && 'true' || '' }} + GH_AW_MCP_CLI_SERVERS_LIST: '- `safeoutputs` — run `safeoutputs --help` to see available tools' GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_ACTIVATED: ${{ needs.pre_activation.outputs.activated }} GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_MATCHED_COMMAND: ${{ needs.pre_activation.outputs.matched_command }} with: @@ -305,15 +323,16 @@ jobs: return await substitutePlaceholders({ file: process.env.GH_AW_PROMPT, substitutions: { + GH_AW_EXPR_1A3A194A: process.env.GH_AW_EXPR_1A3A194A, + GH_AW_EXPR_463A214A: process.env.GH_AW_EXPR_463A214A, + GH_AW_EXPR_802A9F6A: process.env.GH_AW_EXPR_802A9F6A, + GH_AW_EXPR_FF1D34CE: process.env.GH_AW_EXPR_FF1D34CE, GH_AW_GITHUB_ACTOR: process.env.GH_AW_GITHUB_ACTOR, - GH_AW_GITHUB_EVENT_COMMENT_ID: process.env.GH_AW_GITHUB_EVENT_COMMENT_ID, - GH_AW_GITHUB_EVENT_DISCUSSION_NUMBER: process.env.GH_AW_GITHUB_EVENT_DISCUSSION_NUMBER, - GH_AW_GITHUB_EVENT_ISSUE_NUMBER: process.env.GH_AW_GITHUB_EVENT_ISSUE_NUMBER, - GH_AW_GITHUB_EVENT_PULL_REQUEST_NUMBER: process.env.GH_AW_GITHUB_EVENT_PULL_REQUEST_NUMBER, GH_AW_GITHUB_REPOSITORY: process.env.GH_AW_GITHUB_REPOSITORY, GH_AW_GITHUB_RUN_ID: process.env.GH_AW_GITHUB_RUN_ID, GH_AW_GITHUB_WORKSPACE: process.env.GH_AW_GITHUB_WORKSPACE, GH_AW_IS_PR_COMMENT: process.env.GH_AW_IS_PR_COMMENT, + GH_AW_MCP_CLI_SERVERS_LIST: process.env.GH_AW_MCP_CLI_SERVERS_LIST, GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_ACTIVATED: process.env.GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_ACTIVATED, GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_MATCHED_COMMAND: process.env.GH_AW_NEEDS_PRE_ACTIVATION_OUTPUTS_MATCHED_COMMAND } @@ -333,11 +352,17 @@ jobs: uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: activation + include-hidden-files: true path: | /tmp/gh-aw/aw_info.json + /tmp/gh-aw/model_multipliers.json /tmp/gh-aw/aw-prompts/prompt.txt + /tmp/gh-aw/aw-prompts/prompt-template.txt + /tmp/gh-aw/aw-prompts/prompt-import-tree.json /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/base + /tmp/gh-aw/.github/agents + /tmp/gh-aw/.github/skills if-no-files-found: ignore retention-days: 1 @@ -355,25 +380,35 @@ jobs: GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs GH_AW_WORKFLOW_ID_SANITIZED: maciosreviewer outputs: - agentic_engine_timeout: ${{ steps.detect-copilot-errors.outputs.agentic_engine_timeout || 'false' }} + agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} + effective_tokens_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.effective_tokens_rate_limit_error || 'false' }} has_patch: ${{ steps.collect_output.outputs.has_patch }} - inference_access_error: ${{ steps.detect-copilot-errors.outputs.inference_access_error || 'false' }} - mcp_policy_error: ${{ steps.detect-copilot-errors.outputs.mcp_policy_error || 'false' }} + inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} + mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} model: ${{ needs.activation.outputs.model }} - model_not_supported_error: ${{ steps.detect-copilot-errors.outputs.model_not_supported_error || 'false' }} + model_not_supported_error: ${{ steps.detect-agent-errors.outputs.model_not_supported_error || 'false' }} output: ${{ steps.collect_output.outputs.output }} output_types: ${{ steps.collect_output.outputs.output_types }} + setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} + setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@239aec45b78c8799417efdd5bc6d8cc036629ec1 # v0.71.1 + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} trace-id: ${{ needs.activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/macios-reviewer.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" - name: Set runtime paths id: set-runtime-paths run: | @@ -409,7 +444,7 @@ jobs: id: checkout-pr if: | github.event.pull_request || github.event.issue.pull_request - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} with: @@ -420,11 +455,11 @@ jobs: const { main } = require('${{ runner.temp }}/gh-aw/actions/checkout_pr_branch.cjs'); await main(); - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.35 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.28 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 - name: Parse integrity filter lists id: parse-guard-vars env: @@ -440,20 +475,29 @@ jobs: - name: Restore agent config folders from base branch if: steps.checkout-pr.outcome == 'success' env: - GH_AW_AGENT_FOLDERS: ".agents .claude .codex .crush .gemini .github .opencode" - GH_AW_AGENT_FILES: ".crush.json AGENTS.md CLAUDE.md GEMINI.md opencode.jsonc" + GH_AW_AGENT_FOLDERS: ".agents .antigravity .claude .codex .crush .gemini .github .opencode .pi" + GH_AW_AGENT_FILES: ".crush.json AGENTS.md ANTIGRAVITY.md CLAUDE.md GEMINI.md PI.md opencode.jsonc" run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" + - name: Restore inline sub-agents from activation artifact + env: + GH_AW_SUB_AGENT_DIR: ".github/agents" + GH_AW_SUB_AGENT_EXT: ".agent.md" + run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_sub_agents.sh" + - name: Restore inline skills from activation artifact + env: + GH_AW_SKILL_DIR: ".github/skills" + run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.28@sha256:a8834e285807654bf680154faa710d43fe4365a0868142f5c20e48c85e137a7a ghcr.io/github/gh-aw-firewall/api-proxy:0.25.28@sha256:93290f2393752252911bd7c39a047f776c0b53063575e7bde4e304962a9a61cb ghcr.io/github/gh-aw-firewall/squid:0.25.28@sha256:844c18280f82cd1b06345eb2f4e91966b34185bfc51c9f237c3e022e848fb474 ghcr.io/github/gh-aw-mcpg:v0.3.0@sha256:9c2228324fb1f26f39dc9471612e530ae3efc3156dac05efb2e8d212878d454d ghcr.io/github/github-mcp-server:v1.0.2@sha256:26db03408086a99cf1916348dcc4f9614206658f9082a8060dc7c81ad787f4ba node:lts-alpine@sha256:d1b3b4da11eefd5941e7f0b9cf17783fc99d9c6fc34884a665f40a06dbdfc94f - - name: Write Safe Outputs Config + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 ghcr.io/github/gh-aw-mcpg:v0.3.22 ghcr.io/github/github-mcp-server:v1.1.0 node:lts-alpine@sha256:2bdb65ed1dab192432bc31c95f94155ca5ad7fc1392fb7eb7526ab682fa5bf14 + - name: Generate Safe Outputs Config run: | mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" mkdir -p /tmp/gh-aw/safeoutputs mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_89a2d4b9522a1c3e_EOF' - {"create_pull_request_review_comment":{"max":50,"side":"RIGHT"},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{},"submit_pull_request_review":{"allowed_events":["COMMENT","REQUEST_CHANGES"],"max":1}} - GH_AW_SAFE_OUTPUTS_CONFIG_89a2d4b9522a1c3e_EOF - - name: Write Safe Outputs Tools + cat > "${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" << 'GH_AW_SAFE_OUTPUTS_CONFIG_df05992f6de27b87_EOF' + {"create_pull_request_review_comment":{"max":50,"side":"RIGHT"},"create_report_incomplete_issue":{},"missing_data":{},"missing_tool":{},"noop":{"max":1,"report-as-issue":"true"},"report_incomplete":{},"submit_pull_request_review":{"allowed_events":["COMMENT","REQUEST_CHANGES"],"max":1,"supersede_older_reviews":true}} + GH_AW_SAFE_OUTPUTS_CONFIG_df05992f6de27b87_EOF + - name: Generate Safe Outputs Tools env: GH_AW_TOOLS_META_JSON: | { @@ -595,7 +639,7 @@ jobs: } } } - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -656,6 +700,7 @@ jobs: # Export gateway environment variables for MCP config and gateway script export MCP_GATEWAY_PORT="8080" export MCP_GATEWAY_DOMAIN="host.docker.internal" + export MCP_GATEWAY_HOST_DOMAIN="localhost" MCP_GATEWAY_API_KEY=$(openssl rand -base64 45 | tr -d '/+=') echo "::add-mask::${MCP_GATEWAY_API_KEY}" export MCP_GATEWAY_API_KEY @@ -667,17 +712,22 @@ jobs: export GH_AW_ENGINE="copilot" MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - DOCKER_SOCK_GID=$(stat -c '%g' /var/run/docker.sock 2>/dev/null || echo '0') - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v /var/run/docker.sock:/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.0' + case "${DOCKER_HOST:-}" in + unix://* ) DOCKER_SOCK_PATH="${DOCKER_HOST#unix://}" ;; + /* ) DOCKER_SOCK_PATH="$DOCKER_HOST" ;; + * ) DOCKER_SOCK_PATH=/var/run/docker.sock ;; + esac + DOCKER_SOCK_GID=$(stat -c '%g' "$DOCKER_SOCK_PATH" 2>/dev/null || echo '0') + export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network host --add-host host.docker.internal:127.0.0.1 --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_API_KEY -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e GH_AW_SAFE_OUTPUTS_PORT -e GH_AW_SAFE_OUTPUTS_API_KEY -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw ghcr.io/github/gh-aw-mcpg:v0.3.22' mkdir -p /home/runner/.copilot GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_8d4f4bdb31699167_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" + cat << GH_AW_MCP_CONFIG_3ee2b0f26b6b2009_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" { "mcpServers": { "github": { "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.0.2", + "container": "ghcr.io/github/github-mcp-server:v1.1.0", "env": { "GITHUB_HOST": "\${GITHUB_SERVER_URL}", "GITHUB_PERSONAL_ACCESS_TOKEN": "\${GITHUB_MCP_SERVER_TOKEN}", @@ -688,7 +738,7 @@ jobs: "allow-only": { "approval-labels": ${{ steps.parse-guard-vars.outputs.approval_labels }}, "blocked-users": ${{ steps.parse-guard-vars.outputs.blocked_users }}, - "min-integrity": "none", + "min-integrity": "approved", "repos": "all", "trusted-users": ${{ steps.parse-guard-vars.outputs.trusted_users }} } @@ -716,33 +766,70 @@ jobs: "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}" } } - GH_AW_MCP_CONFIG_8d4f4bdb31699167_EOF - - name: Clean git credentials + GH_AW_MCP_CONFIG_3ee2b0f26b6b2009_EOF + - name: Mount MCP servers as CLIs + id: mount-mcp-clis + continue-on-error: true + env: + MCP_GATEWAY_API_KEY: ${{ steps.start-mcp-gateway.outputs.gateway-api-key }} + MCP_GATEWAY_DOMAIN: ${{ steps.start-mcp-gateway.outputs.gateway-domain }} + MCP_GATEWAY_PORT: ${{ steps.start-mcp-gateway.outputs.gateway-port }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io); + const { main } = require('${{ runner.temp }}/gh-aw/actions/mount_mcp_as_cli.cjs'); + await main(); + - name: Clean credentials continue-on-error: true run: bash "${RUNNER_TEMP}/gh-aw/actions/clean_git_credentials.sh" + - name: Audit pre-agent workspace + id: pre_agent_audit + continue-on-error: true + run: bash "${RUNNER_TEMP}/gh-aw/actions/audit_pre_agent_workspace.sh" - name: Execute GitHub Copilot CLI id: agentic_execution # Copilot CLI tool arguments (sorted): timeout-minutes: 20 run: | set -o pipefail + printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN + export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/agent-stdio.log) + printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["*.githubusercontent.com","*.vsblob.vsassets.io","aka.ms","api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","api.nuget.org","api.snapcraft.io","archive.ubuntu.com","azure.archive.ubuntu.com","azuresearch-usnc.nuget.org","azuresearch-ussc.nuget.org","builds.dotnet.microsoft.com","ci.dot.net","codeload.github.com","crl.geotrust.com","crl.globalsign.com","crl.identrust.com","crl.sectigo.com","crl.thawte.com","crl.usertrust.com","crl.verisign.com","crl3.digicert.com","crl4.digicert.com","crls.ssl.com","dc.services.visualstudio.com","dev.azure.com","dist.nuget.org","docs.github.com","dot.net","dotnet.microsoft.com","dotnetcli.blob.core.windows.net","github-cloud.githubusercontent.com","github-cloud.s3.amazonaws.com","github.blog","github.com","github.githubassets.com","host.docker.internal","json-schema.org","json.schemastore.org","keyserver.ubuntu.com","lfs.github.com","microsoft.com","nuget.org","nuget.pkg.github.com","nugetregistryv2prod.blob.core.windows.net","objects.githubusercontent.com","ocsp.digicert.com","ocsp.geotrust.com","ocsp.globalsign.com","ocsp.identrust.com","ocsp.sectigo.com","ocsp.ssl.com","ocsp.thawte.com","ocsp.usertrust.com","ocsp.verisign.com","oneocsp.microsoft.com","packagecloud.io","packages.cloud.google.com","packages.microsoft.com","patch-diff.githubusercontent.com","pkgs.dev.azure.com","ppa.launchpad.net","raw.githubusercontent.com","registry.npmjs.org","s.symcb.com","s.symcd.com","security.ubuntu.com","telemetry.enterprise.githubcopilot.com","ts-crl.ws.symantec.com","ts-ocsp.ws.symantec.com","vsassets.io","www.googleapis.com","www.microsoft.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000,"models":{"agent":["sonnet-6x","gpt-5.4","gpt-5.3","gemini-pro","any"],"antigravity":["copilot/antigravity*","google/antigravity*","gemini/antigravity*"],"any":["copilot/*","anthropic/*","openai/*","google/*","gemini/*"],"claude":["agent"],"codex":["agent"],"coding":["copilot/gpt-5*codex*","openai/gpt-5*codex*","gpt-5-codex"],"computer-use":["copilot/*computer-use*","google/*computer-use*","gemini/*computer-use*","openai/*computer-use*"],"copilot":["agent"],"deep-research":["copilot/deep-research*","copilot/o3-deep-research*","copilot/o4-mini-deep-research*","google/deep-research*","gemini/deep-research*","openai/o3-deep-research*","openai/o4-mini-deep-research*"],"gemini":["agent"],"gemini-3-flash":["copilot/gemini-3*flash*","google/gemini-3*flash*","gemini/gemini-3*flash*"],"gemini-3-pro":["copilot/gemini-3*pro*","google/gemini-3*pro*","gemini/gemini-3*pro*"],"gemini-3.1-flash":["copilot/gemini-3.1*flash*","google/gemini-3.1*flash*","gemini/gemini-3.1*flash*"],"gemini-3.1-pro":["copilot/gemini-3.1*pro*","google/gemini-3.1*pro*","gemini/gemini-3.1*pro*"],"gemini-3.5-flash":["copilot/gemini-3.5*flash*","google/gemini-3.5*flash*","gemini/gemini-3.5*flash*"],"gemini-flash":["copilot/gemini-*flash*","google/gemini-*flash*","gemini/gemini-*flash*"],"gemini-flash-lite":["copilot/gemini-*flash*lite*","google/gemini-*flash*lite*","gemini/gemini-*flash*lite*"],"gemini-pro":["copilot/gemini-*pro*","google/gemini-*pro*","gemini/gemini-*pro*"],"gemma":["copilot/gemma*","google/gemma*","gemini/gemma*"],"gpt-5":["copilot/gpt-5*","openai/gpt-5*"],"gpt-5-codex":["copilot/gpt-5*codex*","openai/gpt-5*codex*"],"gpt-5-mini":["copilot/gpt-5*mini*","openai/gpt-5*mini*"],"gpt-5-nano":["copilot/gpt-5*nano*","openai/gpt-5*nano*"],"gpt-5-pro":["copilot/gpt-5*pro*","openai/gpt-5*pro*"],"gpt-5.2":["copilot/gpt-5.2*","openai/gpt-5.2*"],"gpt-5.3":["copilot/gpt-5.3*","openai/gpt-5.3*"],"gpt-5.4":["copilot/gpt-5.4*","openai/gpt-5.4*"],"gpt-5.5":["copilot/gpt-5.5*","openai/gpt-5.5*"],"haiku":["copilot/*haiku*","anthropic/*haiku*"],"large":["sonnet","gpt-5-pro","gpt-5","gemini-pro"],"mini":["haiku","gpt-5-mini","gpt-5-nano","gemini-flash-lite"],"opus":["copilot/*opus*","anthropic/*opus*"],"opusplan":["opus?effort=high"],"reasoning":["copilot/o1*","copilot/o3*","copilot/o4*","openai/o1*","openai/o3*","openai/o4*"],"robotics":["copilot/*robotics*","google/*robotics*","gemini/*robotics*"],"small":["mini"],"sonnet":["copilot/*sonnet*","anthropic/*sonnet*"],"sonnet-6x":["copilot/*sonnet-4-5-*","anthropic/*sonnet-4-5-*","copilot/*sonnet-4-6*","anthropic/*sonnet-4-6*"],"summarization":["haiku","gpt-5-mini","gemini-flash-lite","mini"],"vision":["copilot/gemini-*image*","gemini/gemini-*image*","copilot/gemini-*flash*","gemini/gemini-*flash*"]}},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" + GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json + GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + fi + GH_AW_TOOL_CACHE_MOUNT="" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + if [ -d "$GH_AW_TOOL_CACHE" ]; then + if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then + GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" + fi + elif [ -d "/home/runner/work/_tool" ]; then + GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" + fi # shellcheck disable=SC1003 - sudo -E awf --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --allow-domains '*.githubusercontent.com,*.vsblob.vsassets.io,aka.ms,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.nuget.org,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,azuresearch-usnc.nuget.org,azuresearch-ussc.nuget.org,builds.dotnet.microsoft.com,ci.dot.net,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,dc.services.visualstudio.com,dev.azure.com,dist.nuget.org,docs.github.com,dot.net,dotnet.microsoft.com,dotnetcli.blob.core.windows.net,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,microsoft.com,nuget.org,nuget.pkg.github.com,nugetregistryv2prod.blob.core.windows.net,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,oneocsp.microsoft.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,pkgs.dev.azure.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,vsassets.io,www.googleapis.com,www.microsoft.com' --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --image-tag 0.25.28,squid=sha256:844c18280f82cd1b06345eb2f4e91966b34185bfc51c9f237c3e022e848fb474,agent=sha256:a8834e285807654bf680154faa710d43fe4365a0868142f5c20e48c85e137a7a,api-proxy=sha256:93290f2393752252911bd7c39a047f776c0b53063575e7bde4e304962a9a61cb,cli-proxy=sha256:fdf310e4678ce58d248c466b89399e9680a3003038fd19322c388559016aaac7 --skip-pull --enable-api-proxy \ - -- /bin/bash -c 'GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || echo node)"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_driver.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log + sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_API_KEY --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ + -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/agent-stdio.log env: + AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE - COPILOT_API_KEY: dummy-byok-key-for-offline-mode + COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} COPILOT_MODEL: claude-sonnet-4.5 GH_AW_MCP_CONFIG: /home/runner/.copilot/mcp-config.json GH_AW_PHASE: agent GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_VERSION: v0.71.1 + GH_AW_VERSION: v0.77.5 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -756,12 +843,13 @@ jobs: GIT_AUTHOR_NAME: github-actions[bot] GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] + RUNNER_TEMP: ${{ runner.temp }} XDG_CONFIG_HOME: /home/runner - - name: Detect Copilot errors - id: detect-copilot-errors + - name: Detect agent errors if: always() + id: detect-agent-errors continue-on-error: true - run: node "${RUNNER_TEMP}/gh-aw/actions/detect_copilot_errors.cjs" + run: node "${RUNNER_TEMP}/gh-aw/actions/detect_agent_errors.cjs" - name: Configure Git credentials env: REPO_NAME: ${{ github.repository }} @@ -790,7 +878,7 @@ jobs: bash "${RUNNER_TEMP}/gh-aw/actions/stop_mcp_gateway.sh" "$GATEWAY_PID" - name: Redact secrets in logs if: always() - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -816,13 +904,13 @@ jobs: - name: Ingest agent output id: collect_output if: always() - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,*.vsblob.vsassets.io,aka.ms,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.nuget.org,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,azuresearch-usnc.nuget.org,azuresearch-ussc.nuget.org,builds.dotnet.microsoft.com,ci.dot.net,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,dc.services.visualstudio.com,dev.azure.com,dist.nuget.org,docs.github.com,dot.net,dotnet.microsoft.com,dotnetcli.blob.core.windows.net,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,microsoft.com,nuget.org,nuget.pkg.github.com,nugetregistryv2prod.blob.core.windows.net,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,oneocsp.microsoft.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,pkgs.dev.azure.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,vsassets.io,www.googleapis.com,www.microsoft.com" + GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,*.vsblob.vsassets.io,aka.ms,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.nuget.org,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,azuresearch-usnc.nuget.org,azuresearch-ussc.nuget.org,builds.dotnet.microsoft.com,ci.dot.net,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,dc.services.visualstudio.com,dev.azure.com,dist.nuget.org,docs.github.com,dot.net,dotnet.microsoft.com,dotnetcli.blob.core.windows.net,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,microsoft.com,nuget.org,nuget.pkg.github.com,nugetregistryv2prod.blob.core.windows.net,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,oneocsp.microsoft.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,pkgs.dev.azure.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,vsassets.io,www.googleapis.com,www.microsoft.com" GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_API_URL: ${{ github.api_url }} - GH_AW_COMMAND: review + GH_AW_COMMANDS: "[\"review\"]" with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -831,7 +919,7 @@ jobs: await main(); - name: Parse agent logs for step summary if: always() - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ with: @@ -843,7 +931,7 @@ jobs: - name: Parse MCP Gateway logs for step summary if: always() id: parse-mcp-gateway - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); @@ -858,7 +946,7 @@ jobs: run: | # Fix permissions on firewall logs/audit dirs so they can be uploaded as artifacts # AWF runs with sudo, creating files owned by root - sudo chmod -R a+r /tmp/gh-aw/sandbox/firewall 2>/dev/null || true + sudo chmod -R a+rX /tmp/gh-aw/sandbox/firewall 2>/dev/null || true # Only run awf logs summary if awf command exists (it may not be installed if workflow failed before install step) if command -v awf &> /dev/null; then awf logs summary | tee -a "$GITHUB_STEP_SUMMARY" @@ -868,13 +956,23 @@ jobs: - name: Parse token usage for step summary if: always() continue-on-error: true - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); setupGlobals(core, github, context, exec, io, getOctokit); const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_token_usage.cjs'); await main(); + - name: Print AWF reflect summary + if: always() + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/awf_reflect_summary.cjs'); + await main(); - name: Write agent output placeholder if missing if: always() run: | @@ -896,14 +994,17 @@ jobs: !/tmp/gh-aw/proxy-logs/proxy-tls/ /tmp/gh-aw/agent_usage.json /tmp/gh-aw/agent-stdio.log + /tmp/gh-aw/pre-agent-audit.txt /tmp/gh-aw/agent/ /tmp/gh-aw/github_rate_limits.jsonl /tmp/gh-aw/safeoutputs.jsonl /tmp/gh-aw/agent_output.json /tmp/gh-aw/aw-*.patch /tmp/gh-aw/aw-*.bundle + /tmp/gh-aw/awf-config.json /tmp/gh-aw/sandbox/firewall/logs/ /tmp/gh-aw/sandbox/firewall/audit/ + /tmp/gh-aw/sandbox/firewall/awf-reflect.json if-no-files-found: ignore conclusion: @@ -922,6 +1023,7 @@ jobs: concurrency: group: "gh-aw-conclusion-macios-reviewer" cancel-in-progress: false + queue: max outputs: incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} noop_message: ${{ steps.noop.outputs.noop_message }} @@ -930,11 +1032,18 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@239aec45b78c8799417efdd5bc6d8cc036629ec1 # v0.71.1 + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} trace-id: ${{ needs.activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/macios-reviewer.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output continue-on-error: true @@ -951,11 +1060,12 @@ jobs: echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - name: Process no-op messages id: noop - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} GH_AW_NOOP_MAX: "1" GH_AW_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/macios-reviewer.md" GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_NOOP_REPORT_AS_ISSUE: "true" @@ -968,10 +1078,11 @@ jobs: await main(); - name: Log detection run id: detection_runs - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} GH_AW_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/macios-reviewer.md" GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} @@ -984,11 +1095,12 @@ jobs: await main(); - name: Record missing tool id: missing_tool - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} GH_AW_MISSING_TOOL_CREATE_ISSUE: "true" GH_AW_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/macios-reviewer.md" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -998,11 +1110,12 @@ jobs: await main(); - name: Record incomplete id: report_incomplete - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} GH_AW_REPORT_INCOMPLETE_CREATE_ISSUE: "true" GH_AW_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/macios-reviewer.md" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1013,10 +1126,11 @@ jobs: - name: Handle agent failure id: handle_agent_failure if: always() - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} GH_AW_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/macios-reviewer.md" GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} GH_AW_WORKFLOW_ID: "macios-reviewer" @@ -1024,15 +1138,21 @@ jobs: GH_AW_ENGINE_ID: "copilot" GH_AW_SECRET_VERIFICATION_RESULT: ${{ needs.activation.outputs.secret_verification_result }} GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} + GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} + GH_AW_EFFECTIVE_TOKENS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.effective_tokens_rate_limit_error || 'false' }} GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} + GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} GH_AW_GROUP_REPORTS: "false" GH_AW_FAILURE_REPORT_AS_ISSUE: "true" + GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" + GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" GH_AW_TIMEOUT_MINUTES: "20" + GH_AW_MAX_EFFECTIVE_TOKENS: "25000000" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | @@ -1042,7 +1162,7 @@ jobs: await main(); - name: Update reaction comment with completion status id: conclusion - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} GH_AW_COMMENT_ID: ${{ needs.activation.outputs.comment_id }} @@ -1050,6 +1170,7 @@ jobs: GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} GH_AW_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} + GH_AW_SAFE_OUTPUTS_RESULT: ${{ needs.safe_outputs.result }} GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} with: @@ -1076,11 +1197,18 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@239aec45b78c8799417efdd5bc6d8cc036629ec1 # v0.71.1 + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} trace-id: ${{ needs.activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/macios-reviewer.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output continue-on-error: true @@ -1106,7 +1234,7 @@ jobs: rm -rf /tmp/gh-aw/sandbox/firewall/logs rm -rf /tmp/gh-aw/sandbox/firewall/audit - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.28@sha256:a8834e285807654bf680154faa710d43fe4365a0868142f5c20e48c85e137a7a ghcr.io/github/gh-aw-firewall/api-proxy:0.25.28@sha256:93290f2393752252911bd7c39a047f776c0b53063575e7bde4e304962a9a61cb ghcr.io/github/gh-aw-firewall/squid:0.25.28@sha256:844c18280f82cd1b06345eb2f4e91966b34185bfc51c9f237c3e022e848fb474 + run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.25.58 ghcr.io/github/gh-aw-firewall/api-proxy:0.25.58 ghcr.io/github/gh-aw-firewall/squid:0.25.58 - name: Check if detection needed id: detection_guard if: always() @@ -1121,7 +1249,7 @@ jobs: echo "run_detection=false" >> "$GITHUB_OUTPUT" echo "Detection skipped: no agent outputs or patches to analyze" fi - - name: Clear MCP configuration for detection + - name: Clear MCP Config for detection if: always() && steps.detection_guard.outputs.run_detection == 'true' run: | rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" @@ -1132,6 +1260,9 @@ jobs: run: | mkdir -p /tmp/gh-aw/threat-detection/aw-prompts cp /tmp/gh-aw/aw-prompts/prompt.txt /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt 2>/dev/null || true + if [ ! -s /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt ]; then + echo "::warning::ERR_VALIDATION: Missing or empty detection context prompt at /tmp/gh-aw/threat-detection/aw-prompts/prompt.txt. Ensure the agent artifact includes /tmp/gh-aw/aw-prompts/prompt.txt. Detection will continue with fallback workflow context." + fi cp /tmp/gh-aw/agent_output.json /tmp/gh-aw/threat-detection/agent_output.json 2>/dev/null || true for f in /tmp/gh-aw/aw-*.patch; do [ -f "$f" ] && cp "$f" /tmp/gh-aw/threat-detection/ 2>/dev/null || true @@ -1143,7 +1274,7 @@ jobs: ls -la /tmp/gh-aw/threat-detection/ 2>/dev/null || true - name: Setup threat detection if: always() && steps.detection_guard.outputs.run_detection == 'true' - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" WORKFLOW_DESCRIPTION: "No description provided" @@ -1165,33 +1296,53 @@ jobs: node-version: '24' package-manager-cache: false - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.35 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" 1.0.55 env: GH_HOST: github.com - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.28 + run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.25.58 - name: Execute GitHub Copilot CLI if: always() && steps.detection_guard.outputs.run_detection == 'true' + continue-on-error: true id: detection_agentic_execution # Copilot CLI tool arguments (sorted): timeout-minutes: 20 run: | set -o pipefail + printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt touch /tmp/gh-aw/agent-step-summary.md GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) export GH_AW_NODE_BIN + export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) + printf '%s\n' '{"$schema":"https://github.com/github/gh-aw-firewall/releases/download/v0.25.58/awf-config.schema.json","network":{"allowDomains":["api.business.githubcopilot.com","api.enterprise.githubcopilot.com","api.github.com","api.githubcopilot.com","api.individual.githubcopilot.com","github.com","host.docker.internal","registry.npmjs.org","telemetry.enterprise.githubcopilot.com"]},"apiProxy":{"enabled":true,"enableTokenSteering":true,"maxRuns":500,"maxEffectiveTokens":25000000},"container":{"imageTag":"0.25.58"}}' > "${RUNNER_TEMP}/gh-aw/awf-config.json" + GH_AW_MODEL_MULTIPLIERS_PATH="/tmp/gh-aw/model_multipliers.json" node "${RUNNER_TEMP}/gh-aw/actions/merge_awf_model_multipliers.cjs" + cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json + GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="" + if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then + GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS="--docker-host-path-prefix /tmp/gh-aw" + fi + GH_AW_TOOL_CACHE_MOUNT="" + GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}" + if [ -d "$GH_AW_TOOL_CACHE" ]; then + if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then + GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" + fi + elif [ -d "/home/runner/work/_tool" ]; then + GH_AW_TOOL_CACHE_MOUNT="/home/runner/work/_tool:/home/runner/work/_tool:ro" + fi # shellcheck disable=SC1003 - sudo -E awf --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" --env-all --exclude-env COPILOT_GITHUB_TOKEN --allow-domains api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,github.com,host.docker.internal,telemetry.enterprise.githubcopilot.com --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --image-tag 0.25.28,squid=sha256:844c18280f82cd1b06345eb2f4e91966b34185bfc51c9f237c3e022e848fb474,agent=sha256:a8834e285807654bf680154faa710d43fe4365a0868142f5c20e48c85e137a7a,api-proxy=sha256:93290f2393752252911bd7c39a047f776c0b53063575e7bde4e304962a9a61cb,cli-proxy=sha256:fdf310e4678ce58d248c466b89399e9680a3003038fd19322c388559016aaac7 --skip-pull --enable-api-proxy \ - -- /bin/bash -c 'GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || echo node)"; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_driver.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log + sudo -E awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST_PATH_PREFIX_ARGS} --env-all --exclude-env COPILOT_GITHUB_TOKEN --log-level info --proxy-logs-dir /tmp/gh-aw/sandbox/firewall/logs --audit-dir /tmp/gh-aw/sandbox/firewall/audit --enable-host-access --allow-host-ports 80,443,8080 --skip-pull \ + -- /bin/bash -c 'set +o histexpand; GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:-/opt/hostedtoolcache}"; export PATH="$(find "$GH_AW_TOOL_CACHE" /opt/hostedtoolcache /home/runner/work/_tool -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; "$GH_AW_NODE_EXEC" ${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs /usr/local/bin/copilot --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log env: + AWF_REFLECT_ENABLED: 1 COPILOT_AGENT_RUNNER_TYPE: STANDALONE - COPILOT_API_KEY: dummy-byok-key-for-offline-mode + COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode COPILOT_GITHUB_TOKEN: ${{ secrets.COPILOT_GITHUB_TOKEN }} COPILOT_MODEL: claude-sonnet-4.5 GH_AW_PHASE: detection GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_VERSION: v0.71.1 + GH_AW_VERSION: v0.77.5 GITHUB_API_URL: ${{ github.api_url }} GITHUB_AW: true GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows @@ -1204,6 +1355,7 @@ jobs: GIT_AUTHOR_NAME: github-actions[bot] GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com GIT_COMMITTER_NAME: github-actions[bot] + RUNNER_TEMP: ${{ runner.temp }} XDG_CONFIG_HOME: /home/runner - name: Upload threat detection log if: always() && steps.detection_guard.outputs.run_detection == 'true' @@ -1215,36 +1367,63 @@ jobs: - name: Parse and conclude threat detection id: detection_conclusion if: always() - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + continue-on-error: true + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }} + DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }} GH_AW_DETECTION_CONTINUE_ON_ERROR: "true" with: script: | - const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_threat_detection_results.cjs'); - await main(); + try { + const { setupGlobals } = require('${{ runner.temp }}/gh-aw/actions/setup_globals.cjs'); + setupGlobals(core, github, context, exec, io, getOctokit); + const { main } = require('${{ runner.temp }}/gh-aw/actions/parse_threat_detection_results.cjs'); + await main(); + } catch (loadErr) { + const continueOnError = process.env.GH_AW_DETECTION_CONTINUE_ON_ERROR !== 'false'; + const detectionExecutionFailed = process.env.DETECTION_AGENTIC_EXECUTION_OUTCOME === 'failure'; + const msg = 'ERR_SYSTEM: \u274C Unexpected error loading threat detection module: ' + (loadErr && loadErr.message ? loadErr.message : String(loadErr)); + core.error(msg); + core.setOutput('reason', 'parse_error'); + if (continueOnError && !detectionExecutionFailed) { + core.warning('\u26A0\uFE0F ' + msg); + core.setOutput('conclusion', 'warning'); + core.setOutput('success', 'false'); + } else { + core.setOutput('conclusion', 'failure'); + core.setOutput('success', 'false'); + core.setFailed(msg); + } + } pre_activation: - if: "github.event_name == 'issue_comment' && (startsWith(github.event.comment.body, '/review ') || startsWith(github.event.comment.body, '/review\n') || github.event.comment.body == '/review') && github.event.issue.pull_request != null || !(github.event_name == 'issue_comment')" + if: "(github.event_name != 'issue_comment' && github.event_name != 'pull_request_review_comment' || contains(fromJSON('[\"OWNER\",\"MEMBER\",\"COLLABORATOR\"]'), github.event.comment.author_association)) && (github.event_name == 'issue_comment' && (startsWith(github.event.comment.body, '/review ') || startsWith(github.event.comment.body, '/review\n') || github.event.comment.body == '/review') && github.event.issue.pull_request != null || !(github.event_name == 'issue_comment'))" runs-on: ubuntu-slim outputs: activated: ${{ steps.check_membership.outputs.is_team_member == 'true' && steps.check_command_position.outputs.command_position_ok == 'true' }} matched_command: ${{ steps.check_command_position.outputs.matched_command }} + setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} + setup-span-id: ${{ steps.setup.outputs.span-id }} setup-trace-id: ${{ steps.setup.outputs.trace-id }} steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@239aec45b78c8799417efdd5bc6d8cc036629ec1 # v0.71.1 + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} + env: + GH_AW_SETUP_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/macios-reviewer.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" - name: Check team membership for command workflow id: check_membership - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: - GH_AW_REQUIRED_ROLES: "admin,maintainer,write" + GH_AW_REQUIRED_ROLES: "admin,maintain,write" with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | @@ -1254,7 +1433,7 @@ jobs: await main(); - name: Check command position id: check_command_position - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_COMMANDS: "[\"review\"]" with: @@ -1277,14 +1456,16 @@ jobs: timeout-minutes: 15 env: GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/macios-reviewer" + GH_AW_COMMANDS: "[\"review\"]" GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} GH_AW_ENGINE_ID: "copilot" GH_AW_ENGINE_MODEL: "claude-sonnet-4.5" - GH_AW_ENGINE_VERSION: "1.0.35" + GH_AW_ENGINE_VERSION: "1.0.55" GH_AW_WORKFLOW_ID: "macios-reviewer" GH_AW_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" + GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/macios-reviewer.md" outputs: code_push_failure_count: ${{ steps.process_safe_outputs.outputs.code_push_failure_count }} code_push_failure_errors: ${{ steps.process_safe_outputs.outputs.code_push_failure_errors }} @@ -1295,11 +1476,18 @@ jobs: steps: - name: Setup Scripts id: setup - uses: github/gh-aw-actions/setup@239aec45b78c8799417efdd5bc6d8cc036629ec1 # v0.71.1 + uses: github/gh-aw-actions/setup@3ea13c02d765410340d533515cb31a7eef2baaf0 # v0.77.5 with: destination: ${{ runner.temp }}/gh-aw/actions job-name: ${{ github.job }} trace-id: ${{ needs.activation.outputs.setup-trace-id }} + parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} + env: + GH_AW_SETUP_WORKFLOW_NAME: ".NET for Apple Platforms PR Reviewer" + GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/macios-reviewer.lock.yml@${{ github.ref }} + GH_AW_INFO_VERSION: "1.0.55" + GH_AW_INFO_AWF_VERSION: "v0.25.58" + GH_AW_INFO_ENGINE_ID: "copilot" - name: Download agent output artifact id: download-agent-output continue-on-error: true @@ -1325,13 +1513,14 @@ jobs: echo "GH_HOST=${GH_HOST}" >> "$GITHUB_ENV" - name: Process Safe Outputs id: process_safe_outputs - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} - GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,*.vsblob.vsassets.io,aka.ms,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.nuget.org,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,azuresearch-usnc.nuget.org,azuresearch-ussc.nuget.org,builds.dotnet.microsoft.com,ci.dot.net,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,dc.services.visualstudio.com,dev.azure.com,dist.nuget.org,docs.github.com,dot.net,dotnet.microsoft.com,dotnetcli.blob.core.windows.net,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,microsoft.com,nuget.org,nuget.pkg.github.com,nugetregistryv2prod.blob.core.windows.net,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,oneocsp.microsoft.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,pkgs.dev.azure.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,vsassets.io,www.googleapis.com,www.microsoft.com" + GH_AW_COMMENT_ID: ${{ needs.activation.outputs.comment_id }} + GH_AW_ALLOWED_DOMAINS: "*.githubusercontent.com,*.vsblob.vsassets.io,aka.ms,api.business.githubcopilot.com,api.enterprise.githubcopilot.com,api.github.com,api.githubcopilot.com,api.individual.githubcopilot.com,api.nuget.org,api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,azuresearch-usnc.nuget.org,azuresearch-ussc.nuget.org,builds.dotnet.microsoft.com,ci.dot.net,codeload.github.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,dc.services.visualstudio.com,dev.azure.com,dist.nuget.org,docs.github.com,dot.net,dotnet.microsoft.com,dotnetcli.blob.core.windows.net,github-cloud.githubusercontent.com,github-cloud.s3.amazonaws.com,github.blog,github.com,github.githubassets.com,host.docker.internal,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,lfs.github.com,microsoft.com,nuget.org,nuget.pkg.github.com,nugetregistryv2prod.blob.core.windows.net,objects.githubusercontent.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,oneocsp.microsoft.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,patch-diff.githubusercontent.com,pkgs.dev.azure.com,ppa.launchpad.net,raw.githubusercontent.com,registry.npmjs.org,s.symcb.com,s.symcd.com,security.ubuntu.com,telemetry.enterprise.githubcopilot.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,vsassets.io,www.googleapis.com,www.microsoft.com" GITHUB_SERVER_URL: ${{ github.server_url }} GITHUB_API_URL: ${{ github.api_url }} - GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"create_pull_request_review_comment\":{\"max\":50,\"side\":\"RIGHT\"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"true\"},\"report_incomplete\":{},\"submit_pull_request_review\":{\"allowed_events\":[\"COMMENT\",\"REQUEST_CHANGES\"],\"max\":1}}" + GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"create_pull_request_review_comment\":{\"max\":50,\"side\":\"RIGHT\"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"true\"},\"report_incomplete\":{},\"submit_pull_request_review\":{\"allowed_events\":[\"COMMENT\",\"REQUEST_CHANGES\"],\"max\":1,\"supersede_older_reviews\":true}}" with: github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} script: | diff --git a/.github/workflows/macios-reviewer.md b/.github/workflows/macios-reviewer.md index 72da3cc06bd9..285343536d0c 100644 --- a/.github/workflows/macios-reviewer.md +++ b/.github/workflows/macios-reviewer.md @@ -3,7 +3,10 @@ on: slash_command: name: review events: [pull_request_comment] - roles: [admin, maintainer, write] + roles: [admin, maintain, write] +concurrency: + group: "macios-reviewer-${{ github.event.issue.number || github.event.pull_request.number || github.run_id }}" + cancel-in-progress: false permissions: contents: read pull-requests: read @@ -22,13 +25,14 @@ network: tools: github: toolsets: [pull_requests, repos] - min-integrity: none + min-integrity: approved safe-outputs: create-pull-request-review-comment: max: 50 submit-pull-request-review: max: 1 allowed-events: [COMMENT, REQUEST_CHANGES] + supersede-older-reviews: true --- # .NET for Apple Platforms PR Reviewer @@ -56,6 +60,6 @@ A maintainer commented `/review` on this pull request. Perform a thorough code r - Don't flag what CI catches (compiler errors, linter issues). - Don't review C# code formatting — it is handled automatically. - Avoid false positives — verify concerns given the full file context. -- **Never submit an APPROVE event.** Use COMMENT for clean PRs and REQUEST_CHANGES when issues are found. +- **Never submit an APPROVE event.** Use COMMENT for clean PRs (or re-reviews where previous issues are fixed) and REQUEST_CHANGES only when ❌ error-level issues are found. Submitting COMMENT on a re-review clears any previous REQUEST_CHANGES state. - Prioritize: bugs > breaking changes > binding correctness > safety > performance > missing tests > duplication > consistency > documentation. - Ignore comments from the user 'vs-mobiletools-engineering-service2'. diff --git a/.github/workflows/maestro-changelog.yml b/.github/workflows/maestro-changelog.yml index d69b1124d873..e390cd2d872c 100644 --- a/.github/workflows/maestro-changelog.yml +++ b/.github/workflows/maestro-changelog.yml @@ -1,6 +1,9 @@ name: Add changelog for Maestro bump + on: pull_request +permissions: {} + jobs: add-changelog: name: Add changelog @@ -9,13 +12,12 @@ jobs: # https://docs.opensource.microsoft.com/github/apps/permission-changes/ # https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs permissions: - issues: write - pull-requests: write + pull-requests: write # will add/edit comments contents: read - if: github.actor == 'dotnet-maestro[bot]' + if: github.event.pull_request.user.login == 'dotnet-maestro[bot]' steps: - - uses: actions/setup-dotnet@v5 + - uses: actions/setup-dotnet@c2fa09f4bde5ebb9d1777cf28262a3eb3db3ced7 # v5 with: dotnet-version: '9' @@ -28,7 +30,7 @@ jobs: ./bin/Debug/net9.0/changelog https://github.com/$GITHUB_REPOSITORY/pull/${GITHUB_REF_NAME/\/*/} > /tmp/changelog.txt 2>&1 - name: 'Add changelog' - uses: actions/github-script@v9.0.0 + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: github-token: ${{secrets.GITHUB_TOKEN}} script: | diff --git a/.github/workflows/pwsh-ci.yml b/.github/workflows/pwsh-ci.yml deleted file mode 100644 index dc06a8786d0a..000000000000 --- a/.github/workflows/pwsh-ci.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: CI for pwsh -on: - push: - branches: [ main ] - pull_request: -permissions: - contents: read - -jobs: - test-pwsh: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - name: Run Pester tests - run: | - Set-PSRepository psgallery -InstallationPolicy trusted - Install-Module -Name Pester -Confirm:$false -Force - - Invoke-Pester -Path *.Tests.ps1 - if ($Error[0].Fullyqualifiederrorid -eq 'PesterAssertionFailed') {exit 1} - working-directory: ./tools/devops/automation/scripts - shell: pwsh diff --git a/.github/workflows/update-single-platform-branches.yml b/.github/workflows/update-single-platform-branches.yml index 0944fe689a68..bb0e62bcf29d 100644 --- a/.github/workflows/update-single-platform-branches.yml +++ b/.github/workflows/update-single-platform-branches.yml @@ -19,9 +19,10 @@ jobs: steps: - name: Checkout repo - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: fetch-depth: 0 + persist-credentials: true # need to push changes - name: 'Update branches' run: | diff --git a/.github/workflows/yamllint.yml b/.github/workflows/yamllint.yml index 4a6ab347b175..ccef5822206a 100644 --- a/.github/workflows/yamllint.yml +++ b/.github/workflows/yamllint.yml @@ -4,7 +4,7 @@ on: pull_request permissions: contents: read - pull-requests: write + pull-requests: read jobs: rebase: @@ -13,36 +13,16 @@ jobs: steps: - name: 'Checkout' - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: token: ${{ secrets.GITHUB_TOKEN }} fetch-depth: 0 + persist-credentials: false - name: Install yamllint run: pip install yamllint - name: Lint YAML pipeline files - id: lint-pipeline working-directory: ./tools/devops/automation run: | - RESULT=$(yamllint . -f github) - if [ -n "$RESULT" ]; then - echo "YAML Lint found issues" - echo "$RESULT" - echo "::set-output name=result::$RESULT" - exit 1 - fi - - # only post a comment if the linting fails - - name: Post comment - uses: unsplash/comment-on-pr@v1.3.1 - if: failure() - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - msg: | - [yaml-lint] YamlLint found issues in the pipeline files. - ${{ steps.lint-pipeline.outputs.result }} - check_for_duplicate_msg: true - delete_prev_regex_msg: "YamlLint found issues in the pipeline files." - duplicate_msg_pattern: "YamlLint found issues in the pipeline files." + yamllint . -f github diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml new file mode 100644 index 000000000000..a27c501d6710 --- /dev/null +++ b/.github/workflows/zizmor.yml @@ -0,0 +1,34 @@ +name: zizmor 🌈 + +on: + push: + branches: ["main"] + pull_request: + branches: ["**"] + +permissions: {} + +jobs: + zizmor: + name: zizmor 🌈 + runs-on: ubuntu-latest + permissions: + security-events: write + contents: read + actions: read + steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + with: + persist-credentials: false + + - name: Find workflow files + id: find-files + run: | + files=$(find .github/workflows -name '*.yml' ! -name '*.lock.yml' | sort | tr '\n' ' ') + echo "files=$files" >> "$GITHUB_OUTPUT" + + - name: Run zizmor + uses: zizmorcore/zizmor-action@5f14fd08f7cf1cb1609c1e344975f152c7ee938d # v0.5.6 + with: + inputs: ${{ steps.find-files.outputs.files }} diff --git a/.gitignore b/.gitignore index d7c8df4a40a7..307ac9670f91 100644 --- a/.gitignore +++ b/.gitignore @@ -16,28 +16,18 @@ _build bin obj packages -~.pmcs* .DS_Store jenkins-results .vs *.raw -bcl-test-importer -tests/xharness/System.ValueTuple.xml provisionator.msbuild.props -# bcl auto-generated tests to be ignored until 6680 is completed -tests/bcl-test/BCLTests/generated -tests/bcl-test/generated -tests/bcl-test/BCL\ tests\ group*.csproj -tests/bcl-test/Mac\ OS\ X\ BCL\ \tests*.csproj -tests/bcl-test/mscorlib*.csproj -tests/bcl-test/SystemCoreXunit*.csproj -tests/bcl-test/SystemXunit.csproj global.json .idea provision-shared.csx mono_crash.*.json *.binlog .vscode +*.lscache # Xcode xcuserdata/ .build/ diff --git a/Directory.Build.props b/Directory.Build.props index 5cfb5c2768de..ac90e9e40ed2 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -8,7 +8,7 @@ $(MicrosoftBuildPackageVersion) $(MicrosoftBuildPackageVersion) 3.22.0 - 3.1.15 + 8.0.0 4.7.2 @@ -19,9 +19,18 @@ 21.1.8 18.0.1 0.11.6 - 6.1.0 - 4.7.0 - 4.4.0 + 6.2.0 + 4.13.0 + 4.6.1 + $(NUnitPackageVersion) + 3.8.0 + + + latest + + enable + + true diff --git a/Make.config b/Make.config index 03bbd93b57ab..d2094bc8da7d 100644 --- a/Make.config +++ b/Make.config @@ -1,9 +1,9 @@ include $(TOP)/mk/subdirs.mk -# Detect if we're building on Linux +# Detect if we're building on Linux (which means there's no Xcode) UNAME_S:=$(shell uname -s) ifeq ($(UNAME_S),Linux) -IS_LINUX=1 +NO_XCODE=1 endif # Common cURL command: @@ -50,10 +50,10 @@ include $(TOP)/Make.versions # The value is taken from the name + version of the Ref pack. # Example: given the Ref pack "Microsoft.iOS.Ref.net8.0_17.5" with the version "17.5.8030", the value # to write here would be the part after "Microsoft.iOS.Ref." + "/" + version: "net8.0_17.5/17.5.8030" -STABLE_NUGET_VERSION_iOS=net10.0_26.2/26.2.10233 -STABLE_NUGET_VERSION_tvOS=net10.0_26.2/26.2.10233 -STABLE_NUGET_VERSION_MacCatalyst=net10.0_26.2/26.2.10233 -STABLE_NUGET_VERSION_macOS=net10.0_26.2/26.2.10233 +STABLE_NUGET_VERSION_iOS=net10.0_26.5/26.5.10280 +STABLE_NUGET_VERSION_tvOS=net10.0_26.5/26.5.10280 +STABLE_NUGET_VERSION_MacCatalyst=net10.0_26.5/26.5.10280 +STABLE_NUGET_VERSION_macOS=net10.0_26.5/26.5.10280 PACKAGE_HEAD_REV=$(shell git rev-parse HEAD) @@ -206,12 +206,23 @@ MACCATALYST_NUGET_VERSION_PATCH=$(word 3, $(subst ., ,$(MACCATALYST_NUGET_VERSIO MACCATALYST_NUGET_VERSION_NO_METADATA=$(MACCATALYST_NUGET_VERSION)$(NUGET_PRERELEASE_IDENTIFIER) MACCATALYST_NUGET_VERSION_FULL=$(MACCATALYST_NUGET_VERSION_NO_METADATA)$(NUGET_BUILD_METADATA) +-include $(TOP)/configure.inc + # Xcode version should have both a major and a minor version (even if the minor version is 0) XCODE_VERSION=26.5 XCODE_URL=https://bosstoragemirror.blob.core.windows.net/internal-files/xcodes/Xcode_26.5.xip -ifndef IS_LINUX -XCODE_DEVELOPER_ROOT=/Applications/Xcode_26.5.0.app/Contents/Developer -XCODE_PRODUCT_BUILD_VERSION:=$(shell /usr/libexec/PlistBuddy -c 'Print :ProductBuildVersion' $(XCODE_DEVELOPER_ROOT)/../version.plist 2>/dev/null || echo " $(shell tput setaf 1 2>/dev/null)The required Xcode ($(XCODE_VERSION)) is not installed in $(basename $(basename $(XCODE_DEVELOPER_ROOT)))$(shell tput sgr0 2>/dev/null)" >&2) +ifndef NO_XCODE +XCODE_DEVELOPER_ROOT?=/Applications/Xcode_26.5.0.app/Contents/Developer +ifneq (OK,$(shell test -d $(abspath $(XCODE_DEVELOPER_ROOT)) && echo OK)) +NO_XCODE=1 +$(warning The required Xcode ($(XCODE_VERSION)) is not installed in $(XCODE_DEVELOPER_ROOT) - this directory does not exist. Any parts of the build that require Xcode will be disabled.) +else +XCODE_PRODUCT_BUILD_VERSION:=$(shell /usr/libexec/PlistBuddy -c 'Print :ProductBuildVersion' $(XCODE_DEVELOPER_ROOT)/../version.plist 2>/dev/null) +ifeq (,$(XCODE_PRODUCT_BUILD_VERSION)) +NO_XCODE=1 +$(warning The required Xcode ($(XCODE_VERSION)) is not installed in $(XCODE_DEVELOPER_ROOT) - directory exists, but no version found. Any parts of the build that require Xcode will be disabled.) +endif +endif # We define stable Xcode as the Xcode app being named like "Xcode_#.#[.#].app" # and any other naming is deemed to be a beta. This is the safer approach: any @@ -230,10 +241,8 @@ endif # Tell both Xcode and our build logic which Xcode we're using. export DEVELOPER_DIR=$(XCODE_DEVELOPER_ROOT) -export MD_APPLE_SDK_ROOT=$(abspath $(XCODE_DEVELOPER_ROOT)/../..) else -# On Linux, set placeholder Xcode values but honor XCODE_CHANNEL so we configure bots correctly -XCODE_PRODUCT_BUILD_VERSION= +# Without Xcode, set placeholder Xcode values but honor XCODE_CHANNEL so we configure bots correctly ifeq ($(XCODE_CHANNEL),Beta) XCODE_IS_STABLE=false XCODE_IS_PREVIEW=true @@ -248,6 +257,11 @@ export DOTNET_CLI_WORKLOAD_UPDATE_NOTIFY_DISABLE=true # We don't need to be told we're using preview packages (we pretty much always are). export SuppressNETCoreSdkPreviewMessage=true +# The Arcade SDK imported by the Xamarin.MacDev submodule overrides +# NuGetPackageRoot in CI, breaking the netstandard2.0 build. +# Pass the correct path explicitly. +export NuGetPackageRoot=$(abspath $(TOP)/packages)/ + # Minimum OSX versions for building XI/XM MIN_OSX_BUILD_VERSION=15.3 diff --git a/Make.versions b/Make.versions index 2499d5bb498b..e34932ddad38 100644 --- a/Make.versions +++ b/Make.versions @@ -115,10 +115,10 @@ SUPPORTED_API_VERSIONS_TVOS+=net9.0-18.0 SUPPORTED_API_VERSIONS_MACOS+=net9.0-15.0 SUPPORTED_API_VERSIONS_MACCATALYST+=net9.0-18.0 -SUPPORTED_API_VERSIONS_IOS+=net9.0-26.4 -SUPPORTED_API_VERSIONS_TVOS+=net9.0-26.4 -SUPPORTED_API_VERSIONS_MACOS+=net9.0-26.4 -SUPPORTED_API_VERSIONS_MACCATALYST+=net9.0-26.4 +SUPPORTED_API_VERSIONS_IOS+=net9.0-26.5 +SUPPORTED_API_VERSIONS_TVOS+=net9.0-26.5 +SUPPORTED_API_VERSIONS_MACOS+=net9.0-26.5 +SUPPORTED_API_VERSIONS_MACCATALYST+=net9.0-26.5 SUPPORTED_API_VERSIONS_IOS+=net10.0-26.0 SUPPORTED_API_VERSIONS_TVOS+=net10.0-26.0 diff --git a/Makefile b/Makefile index f60d19b26180..4f8bfa47322b 100644 --- a/Makefile +++ b/Makefile @@ -3,8 +3,8 @@ SUBDIRS=builds include $(TOP)/Make.config include $(TOP)/mk/versions.mk -# On Linux, skip directories that require native compilation or macOS platform -ifndef IS_LINUX +# Without Xcode, skip directories that require native compilation or macOS platform +ifndef NO_XCODE SUBDIRS += runtime endif @@ -16,7 +16,7 @@ endif SUBDIRS += tools -ifndef IS_LINUX +ifndef NO_XCODE SUBDIRS += dotnet endif diff --git a/NuGet.config b/NuGet.config index b14cd27026f0..128c4a3f5b21 100644 --- a/NuGet.config +++ b/NuGet.config @@ -12,7 +12,7 @@ - + @@ -33,20 +33,10 @@ - - - - - - - - - - - - - - + + + + diff --git a/configure b/configure index 4a126a2a5bd1..bf82ee1b84aa 100755 --- a/configure +++ b/configure @@ -29,7 +29,14 @@ Usage: configure [options] --custom-dotnet=[dotnet/runtime] Use a locally built version of dotnet/runtime. Pass the path to an already build checkout of dotnet/runtime. See docs/CORECLR.md for detailed instructions about how to build dotnet/runtime from source. + --xcode=[path] Select the Xcode app or developer root to use for the build. + --xcode-root=[path] Select the Xcode app to use for the build. + --xcode-developer-root=[path] + Select the Xcode developer root to use for the build. + --ignore-unknown-params alters the default behavior to not return an non-zero exit code when an unknown parameter is provided. + + --no-xcode Only do things that don't require Xcode. This won't produce anything useful, but might come in handy once in a blue moon when testing something that doesn't require Xcode somewhere Xcode can't be installed (Linux, older macOS devices, etc.) EOL } @@ -37,6 +44,39 @@ cd "$(dirname "${BASH_SOURCE[0]}")" CONFIGURED_FILE=configure.inc IGNORE_UNKNOWN_PARAMS=false UNKNOWN_PARAMETERS= +NO_XCODE_FLAG= +XCODE_ARG= + +function fail_configure () { + echo "configure: $1" >&2 + rm -f "$CONFIGURED_FILE" + exit 1 +} + +function set_xcode_arg () { + local value="$1" + local option="$2" + + while [[ "$value" == */ ]]; do + value="${value%/}" + done + + if [[ -z "$value" ]]; then + fail_configure "$option requires a non-empty path" + fi + + if [[ ! "$value" =~ ^/[A-Za-z0-9._+/-]+$ ]]; then + fail_configure "$option path contains unsupported characters: '$value'" + fi + + if [[ "$value" == *.app ]]; then + value="$value/Contents/Developer" + elif [[ "$value" != */Contents/Developer ]]; then + fail_configure "$option must point to an Xcode .app bundle or Contents/Developer directory" + fi + + XCODE_ARG="$value" +} rm -f $CONFIGURED_FILE @@ -128,6 +168,17 @@ while test "x$1" != x; do echo "DOTNET_RUNTIME_PATH=$2" >> "$CONFIGURED_FILE" shift 2 ;; + --xcode=*|--xcode-root=*|--xcode-developer-root=*) + set_xcode_arg "${1#*=}" "${1%%=*}" + shift + ;; + --xcode|--xcode-root|--xcode-developer-root) + if [[ $# -lt 2 ]] || [[ "$2" == --* ]]; then + fail_configure "$1 requires a value" + fi + set_xcode_arg "$2" "$1" + shift 2 + ;; --disable-device) echo "INCLUDE_DEVICE=" >> "$CONFIGURED_FILE" shift @@ -149,6 +200,12 @@ while test "x$1" != x; do IGNORE_UNKNOWN_PARAMS=true shift ;; + --no-xcode) + echo "Ignoring Xcode requirement" + NO_XCODE_FLAG=1 + echo "NO_XCODE=1" >> "$CONFIGURED_FILE" + shift + ;; --help|-h) show_help exit 0 @@ -161,6 +218,10 @@ while test "x$1" != x; do esac done +if [[ -n "$NO_XCODE_FLAG" && -n "$XCODE_ARG" ]]; then + fail_configure "--no-xcode cannot be combined with --xcode, --xcode-root, or --xcode-developer-root" +fi + if [[ "$IGNORE_UNKNOWN_PARAMS" = false ]] && [[ -n "$UNKNOWN_PARAMETERS" ]]; then exit 1 fi @@ -169,4 +230,9 @@ if [[ "$IGNORE_UNKNOWN_PARAMS" = true ]] && [[ -n "$UNKNOWN_PARAMETERS" ]]; then echo "The following parameters were ignored: $UNKNOWN_PARAMETERS" fi +if [[ -n "$XCODE_ARG" ]]; then + echo "XCODE_DEVELOPER_ROOT=$XCODE_ARG" >> "$CONFIGURED_FILE" + echo "Xcode developer root set to $XCODE_ARG" +fi + exit 0 diff --git a/docs/ReleaseCheckList.md b/docs/ReleaseCheckList.md index 3f0cc42dc66d..84e9a672070f 100644 --- a/docs/ReleaseCheckList.md +++ b/docs/ReleaseCheckList.md @@ -65,8 +65,13 @@ This happens after the stable version of Xcode has been released and the `xcodeX * [ ] Publish NuGets to nuget.org. * [ ] Publish release notes. * [ ] Update API diff (the `STABLE_NUGET_VERSION_*` variables in `Make.config`) for the `main` branch. Can only be done after the NuGets have been published to nuget.org. + * [ ] Link to PR * [ ] Update docs by executing `docs/sync-mobile-docs.sh`. Beware if docs were modified in the [docs-mobile](https://github.com/dotnet/docs-mobile) repository by somebody else, any such changes will have to be copied back first. + * [ ] Link to dotnet/docs-mobile PR * [ ] Update API / reference docs. See [update-api-docs.md](https://github.com/dotnet/macios/blob/main/docs/update-api-docs.md) for instructions. + * [ ] Create new monikers (add link to dev.azure.com ticket) + * [ ] Add reference docs (add link to dotnet/macios-api-docs PR) + * [ ] Flip the monikers from prerelease to live (add link to dev.azure.com ticket) * [ ] Make sure all items in the milestone for the current release have been closed. * [ ] Close this issue & close the milestone. * [ ] Wonder about life as you consider the impossibility of actually reaching this point, because you can't close the milestone before all issues have been closed, and you can't close this issue until checking off all items, which you can't do until you've closed the milestone. Decide to schedule yet another viewing of [Life of Brian](https://en.wikipedia.org/wiki/Monty_Python%27s_Life_of_Brian) to ~cope~ celebrate the release 🍾. diff --git a/docs/api/AVFoundation/AVAudioRecorder.xml b/docs/api/AVFoundation/AVAudioRecorder.xml index fddc275c262b..2b8dfd9064cb 100644 --- a/docs/api/AVFoundation/AVAudioRecorder.xml +++ b/docs/api/AVFoundation/AVAudioRecorder.xml @@ -22,8 +22,6 @@ recorder.Record (); ]]> - Play Sound - Record Sound - Apple documentation for AVAudioRecorder + Apple documentation for AVAudioRecorder \ No newline at end of file diff --git a/docs/api/AVFoundation/AVAudioSession.xml b/docs/api/AVFoundation/AVAudioSession.xml index ca32d9a704d7..0ddf6c2b49a0 100644 --- a/docs/api/AVFoundation/AVAudioSession.xml +++ b/docs/api/AVFoundation/AVAudioSession.xml @@ -62,7 +62,7 @@ void Setup () ]]> - Apple documentation for AVAudioSession + Apple documentation for AVAudioSession One of diff --git a/docs/api/AVFoundation/AVSpeechSynthesizer.xml b/docs/api/AVFoundation/AVSpeechSynthesizer.xml index 2d3b61b5dec1..3069c1147047 100644 --- a/docs/api/AVFoundation/AVSpeechSynthesizer.xml +++ b/docs/api/AVFoundation/AVSpeechSynthesizer.xml @@ -14,6 +14,6 @@ ss.SpeakUtterance(su); The maintains an internal queue of s. The queue is not accessible to application developers, but the synthesizer can be paused or stopped with and . Events such as or are opportunities for the application developer to modify previously-enqueued sequences. - Apple documentation for AVSpeechSynthesizer + Apple documentation for AVSpeechSynthesizer \ No newline at end of file diff --git a/docs/api/AddressBook/ABPerson.xml b/docs/api/AddressBook/ABPerson.xml index 51f25ef15e0b..9fe9d9ddafb8 100644 --- a/docs/api/AddressBook/ABPerson.xml +++ b/docs/api/AddressBook/ABPerson.xml @@ -229,8 +229,5 @@ monocatalog - Choose a Contact - Create a New Contact - Find a Contact \ No newline at end of file diff --git a/docs/api/AddressBookUI/ABPeoplePickerNavigationController.xml b/docs/api/AddressBookUI/ABPeoplePickerNavigationController.xml index 4643e769edc5..2e71c18d1d82 100644 --- a/docs/api/AddressBookUI/ABPeoplePickerNavigationController.xml +++ b/docs/api/AddressBookUI/ABPeoplePickerNavigationController.xml @@ -272,9 +272,6 @@ public class CompatibleEmailPickerViewController : UIViewController } }]]> . - Choose a Contact - Create a New Contact - Find a Contact Apple documentation for ABPeoplePickerNavigationController \ No newline at end of file diff --git a/docs/api/CoreAnimation/CALayer.xml b/docs/api/CoreAnimation/CALayer.xml index 20e1d7c38cd6..19dae86dbcac 100644 --- a/docs/api/CoreAnimation/CALayer.xml +++ b/docs/api/CoreAnimation/CALayer.xml @@ -191,12 +191,6 @@ public class MyLayer : CALayer { ]]> - Animate a UIView using UIKit - Animate Using Blocks - Create a Keyframe Animation - Create an Animation Block - Create An Explicit Animation - Create an Implicit Animation Apple documentation for CALayer @@ -405,12 +399,6 @@ public class MyLayer : CALayer { - Animate a UIView using UIKit - Animate Using Blocks - Create a Keyframe Animation - Create an Animation Block - Create An Explicit Animation - Create an Implicit Animation Apple documentation for CALayer \ No newline at end of file diff --git a/docs/api/UIKit/NSLayoutManager.xml b/docs/api/UIKit/NSLayoutManager.xml index 1efcbd24773a..df4ce69e3814 100644 --- a/docs/api/UIKit/NSLayoutManager.xml +++ b/docs/api/UIKit/NSLayoutManager.xml @@ -10,7 +10,7 @@ objects, which actually display the text. - Apple documentation for NSLayoutManager + Apple documentation for NSLayoutManager Whether layout can be done for a portion of the document without laying-out being recalculated from the beginning. diff --git a/docs/api/UIKit/NSTextContainer.xml b/docs/api/UIKit/NSTextContainer.xml index 41cac2b068e9..193141e2d971 100644 --- a/docs/api/UIKit/NSTextContainer.xml +++ b/docs/api/UIKit/NSTextContainer.xml @@ -43,6 +43,6 @@ AddSubview(rightHandView); The preceding diagram illustrates the objects directly involved in the two-column layout. The is the responsibility of some external model class and the two-column user-interface is specified by a custom (TwoColumnView). A contains an array of zero or more objects in its property. Text will not be placed within these paths. - Apple documentation for NSTextContainer + Apple documentation for NSTextContainer \ No newline at end of file diff --git a/docs/api/UIKit/NSTextStorage.xml b/docs/api/UIKit/NSTextStorage.xml index 508777500752..ef32c554f095 100644 --- a/docs/api/UIKit/NSTextStorage.xml +++ b/docs/api/UIKit/NSTextStorage.xml @@ -25,6 +25,6 @@ - Apple documentation for NSTextStorage + Apple documentation for NSTextStorage \ No newline at end of file diff --git a/docs/api/UIKit/UICollectionView.xml b/docs/api/UIKit/UICollectionView.xml index 317def4b3f7e..889739ccf465 100644 --- a/docs/api/UIKit/UICollectionView.xml +++ b/docs/api/UIKit/UICollectionView.xml @@ -307,7 +307,6 @@ public class SimpleCollectionViewController : UICollectionViewController - Introduction to Collection Views Apple documentation for UICollectionView diff --git a/docs/api/UIKit/UICollectionViewCell.xml b/docs/api/UIKit/UICollectionViewCell.xml index 4d2e56257ba5..6e62b2a07714 100644 --- a/docs/api/UIKit/UICollectionViewCell.xml +++ b/docs/api/UIKit/UICollectionViewCell.xml @@ -50,7 +50,6 @@ public override UICollectionViewCell GetCell (UICollectionView collectionView, F - Introduction to Collection Views Apple documentation for UICollectionViewCell \ No newline at end of file diff --git a/docs/api/UIKit/UICollectionViewDelegate.xml b/docs/api/UIKit/UICollectionViewDelegate.xml index b7da13af6598..459b8137ffd8 100644 --- a/docs/api/UIKit/UICollectionViewDelegate.xml +++ b/docs/api/UIKit/UICollectionViewDelegate.xml @@ -113,7 +113,6 @@ - Introduction to Collection Views Apple documentation for UICollectionViewDelegate \ No newline at end of file diff --git a/docs/api/UIKit/UICollectionViewFlowLayout.xml b/docs/api/UIKit/UICollectionViewFlowLayout.xml index 9d92d5d43fb5..3404f69fa6ed 100644 --- a/docs/api/UIKit/UICollectionViewFlowLayout.xml +++ b/docs/api/UIKit/UICollectionViewFlowLayout.xml @@ -13,7 +13,6 @@ - Introduction to Collection Views Apple documentation for UICollectionViewFlowLayout \ No newline at end of file diff --git a/docs/api/UIKit/UICollectionViewLayout.xml b/docs/api/UIKit/UICollectionViewLayout.xml index cf10120d210d..9ce2e9538c27 100644 --- a/docs/api/UIKit/UICollectionViewLayout.xml +++ b/docs/api/UIKit/UICollectionViewLayout.xml @@ -73,7 +73,6 @@ - Introduction to Collection Views Apple documentation for UICollectionViewLayout \ No newline at end of file diff --git a/docs/api/UIKit/UICollectionViewLayoutAttributes.xml b/docs/api/UIKit/UICollectionViewLayoutAttributes.xml index 9664e360e08f..032b3c9050e0 100644 --- a/docs/api/UIKit/UICollectionViewLayoutAttributes.xml +++ b/docs/api/UIKit/UICollectionViewLayoutAttributes.xml @@ -34,7 +34,6 @@ public class CircleLayout : UICollectionViewLayout { implements and thus can be used with UI Dynamics. - Introduction to Collection Views Apple documentation for UICollectionViewLayoutAttributes \ No newline at end of file diff --git a/docs/api/UIKit/UIView.xml b/docs/api/UIKit/UIView.xml index 049b1e75a3e6..cd230ee3fc43 100644 --- a/docs/api/UIKit/UIView.xml +++ b/docs/api/UIKit/UIView.xml @@ -991,7 +991,6 @@ public class BlueLayer : CALayer In addition to returning , for a to be focused, it must have a value of , a value of , a value greater than 0, and it must not be obscured by another . - Animate a UIView using UIKit Apple documentation for UIView @@ -1018,7 +1017,6 @@ UIView.CommitAnimations (); - diff --git a/docs/api/UIKit/UIWebView.xml b/docs/api/UIKit/UIWebView.xml index 973647807d25..fd946fa900fc 100644 --- a/docs/api/UIKit/UIWebView.xml +++ b/docs/api/UIKit/UIWebView.xml @@ -1,9 +1,6 @@ A that displays a web browser. - Load a Web Page - Load Local Content - Load Non-Web Documents Apple documentation for UIWebView \ No newline at end of file diff --git a/docs/bindas.md b/docs/bindas.md index 27c7a5ef8130..6ef355d08bd7 100644 --- a/docs/bindas.md +++ b/docs/bindas.md @@ -23,16 +23,16 @@ The sample code is to support a new type for NSValue, the exact code locations w code this is the two functions to convert between NSValue and NSDirectionalEdgeInsets: - `xamarin_nsdirectionaledgeinsets_to_nsvalue`: [trampolines.h#151][2], [trampolines.m#889][3] - `xamarin_nsvalue_to_nsdirectionaledgeinsets`: [trampolines.h#116][4], [trampolines.m#799][5] + `xamarin_nsdirectionaledgeinsets_to_nsvalue`: [trampolines.h#197][2], [trampolines.m#1252][3] + `xamarin_nsvalue_to_nsdirectionaledgeinsets`: [trampolines.h#161][4], [trampolines.m#1192][5] -3. Add a switch entry to [trampolines.m#1007][6] to use the two new conversion functions. +3. Add a switch entry to [trampolines.m#1601][6] to use the two new conversion functions. -4. The registrar also needs to know ([Registrar.cs#687][7]). +4. The registrar also needs to know ([Registrar.cs#794][7]). -5. And the static registrar needs to know too, so that it can call the right native conversion function ([StaticRegistrar.cs#3796][9], [StaticRegistrar.cs#3830][10]). +5. And the static registrar needs to know too, so that it can call the right native conversion function ([StaticRegistrar.cs#4896][9], [StaticRegistrar.cs#4925][10]). -6. Now there's just the generator support left ([generator.cs#1223][11], [generator.cs#1369][12]). +6. Now there's just the generator support left ([Generator.cs#390][11], [Generator.cs#470][12]). 7. Finally run the following tests (at least) @@ -40,15 +40,15 @@ The sample code is to support a new type for NSValue, the exact code locations w * link all on both simulator and device. -[1]: https://github.com/rolfbjarne/xamarin-macios/blob/b38c114fbe8c9d229ec41a312dc36802cb4f027e/tests/test-libraries/testgenerator.cs#L100 -[2]: https://github.com/rolfbjarne/xamarin-macios/blob/b38c114fbe8c9d229ec41a312dc36802cb4f027e/runtime/xamarin/trampolines.h#L151 -[3]: https://github.com/rolfbjarne/xamarin-macios/blob/b38c114fbe8c9d229ec41a312dc36802cb4f027e/runtime/trampolines.m#L889 -[4]: https://github.com/rolfbjarne/xamarin-macios/blob/b38c114fbe8c9d229ec41a312dc36802cb4f027e/runtime/xamarin/trampolines.h#L116 -[5]: https://github.com/rolfbjarne/xamarin-macios/blob/b38c114fbe8c9d229ec41a312dc36802cb4f027e/runtime/trampolines.m#L799 -[6]: https://github.com/rolfbjarne/xamarin-macios/blob/b38c114fbe8c9d229ec41a312dc36802cb4f027e/runtime/trampolines.m#L1007-L1008 -[7]: https://github.com/rolfbjarne/xamarin-macios/blob/b38c114fbe8c9d229ec41a312dc36802cb4f027e/src/ObjCRuntime/Registrar.cs#L687 +[1]: https://github.com/dotnet/macios/blob/18a22fd0812016cfdc8397d9b70981a1fc365fed/tests/test-libraries/testgenerator.cs#L125 +[2]: https://github.com/dotnet/macios/blob/18a22fd0812016cfdc8397d9b70981a1fc365fed/runtime/xamarin/trampolines.h#L197 +[3]: https://github.com/dotnet/macios/blob/18a22fd0812016cfdc8397d9b70981a1fc365fed/runtime/trampolines.m#L1252 +[4]: https://github.com/dotnet/macios/blob/18a22fd0812016cfdc8397d9b70981a1fc365fed/runtime/xamarin/trampolines.h#L161 +[5]: https://github.com/dotnet/macios/blob/18a22fd0812016cfdc8397d9b70981a1fc365fed/runtime/trampolines.m#L1192 +[6]: https://github.com/dotnet/macios/blob/18a22fd0812016cfdc8397d9b70981a1fc365fed/runtime/trampolines.m#L1601-L1602 +[7]: https://github.com/dotnet/macios/blob/18a22fd0812016cfdc8397d9b70981a1fc365fed/src/ObjCRuntime/Registrar.cs#L794 [8]: https://github.com/dotnet/macios/pull/2288/commits/b38c114fbe8c9d229ec41a312dc36802cb4f027e -[9]: https://github.com/rolfbjarne/xamarin-macios/blob/b38c114fbe8c9d229ec41a312dc36802cb4f027e/tools/common/StaticRegistrar.cs#L3796 -[10]: https://github.com/rolfbjarne/xamarin-macios/blob/b38c114fbe8c9d229ec41a312dc36802cb4f027e/tools/common/StaticRegistrar.cs#L3830 -[11]: https://github.com/rolfbjarne/xamarin-macios/blob/b38c114fbe8c9d229ec41a312dc36802cb4f027e/src/generator.cs#L1223 -[12]: https://github.com/rolfbjarne/xamarin-macios/blob/b38c114fbe8c9d229ec41a312dc36802cb4f027e/src/generator.cs#L1369 +[9]: https://github.com/dotnet/macios/blob/18a22fd0812016cfdc8397d9b70981a1fc365fed/tools/common/StaticRegistrar.cs#L4896 +[10]: https://github.com/dotnet/macios/blob/18a22fd0812016cfdc8397d9b70981a1fc365fed/tools/common/StaticRegistrar.cs#L4925 +[11]: https://github.com/dotnet/macios/blob/18a22fd0812016cfdc8397d9b70981a1fc365fed/src/bgen/Generator.cs#L390 +[12]: https://github.com/dotnet/macios/blob/18a22fd0812016cfdc8397d9b70981a1fc365fed/src/bgen/Generator.cs#L470 diff --git a/docs/building-apps/build-items.md b/docs/building-apps/build-items.md index ff18c071b9e6..2fd81202cf18 100644 --- a/docs/building-apps/build-items.md +++ b/docs/building-apps/build-items.md @@ -186,7 +186,8 @@ Only applicable to iOS and tvOS projects. ## ImageAsset -An item group that contains image assets. +An item group that contains image assets, including files inside asset catalogs +(\*.xcassets) and Icon Composer directories (\*.icon). ## InterfaceDefinition diff --git a/docs/building-apps/build-properties.md b/docs/building-apps/build-properties.md index ab6a1742229a..634396282b90 100644 --- a/docs/building-apps/build-properties.md +++ b/docs/building-apps/build-properties.md @@ -559,6 +559,72 @@ See also: * The [AlternateAppIcon](build-items.md#alternateappicon) item group. * The [AppIcon](#appicon) property. +## InlineClassGetHandle + +Controls whether the build system replaces runtime calls to `Class.GetHandle` / +`Class.GetHandleIntrinsic` with direct native references to Objective-C classes +at build time. + +See [docs/code/class-handles.md](../code/class-handles.md) for an overview. + +The valid options are: + +* `compatibility`: Inlines `Class.GetHandle` calls only for types whose declaring + type matches the requested Objective-C class name. +* `strict`: Inlines all `Class.GetHandle` calls unconditionally. Requires using + the static registrar (not the dynamic registrar). +* (empty): Disables inlining of `Class.GetHandle` calls. + +Default value: +* .NET 11+: `strict` when using NativeAOT (`PublishAot=true`), `compatibility` otherwise. +* .NET 10 and earlier: not set (disabled). + +Example: + +```xml + + compatibility + +``` + +Custom behavior for specific Objective-C classes can be set using the [ReferenceNativeSymbol](build-items.md#referencenativesymbol) item group: + +```xml + + + +``` + +## InlineDlfcnMethods + +Controls whether the build system replaces runtime calls to `ObjCRuntime.Dlfcn` methods with direct native symbol lookups at build time, eliminating the overhead of `dlsym` at runtime. + +The valid options are: + +* `compatibility`: Only inlines symbol usages backed by `[Field]` attributes. This is more conservative and avoids link errors for symbols that don't exist at build time. +* `strict`: Inlines dlfcn method calls and creates native references for all symbols. This is more aggressive and may cause link errors if referenced native symbols don't exist. +* (empty): Disables inlining of dlfcn method calls. + +Default value: +* .NET 11+: `strict` when using NativeAOT (`PublishAot=true`), `compatibility` otherwise. +* .NET 10 and earlier: not set (disabled). + +Example: + +```xml + + compatibility + +``` + +Custom behavior for specific symbols can be set using the [ReferenceNativeSymbol](build-items.md#referencenativesymbol) item group: + +```xml + + + +``` + ## iOSMinimumVersion Specifies the minimum iOS version the app can run on. @@ -1103,7 +1169,7 @@ Only applicable to macOS and Mac Catalyst apps. ## ReferenceNativeSymbol -See [ReferenceNativeSymbol](build-items.md#referencenativesymbols) +See [ReferenceNativeSymbol](build-items.md#referencenativesymbol) ## RequireLinkWithAttributeForObjectiveCClassSearch @@ -1234,6 +1300,18 @@ $ dotnet run -p:StandardInputPath=stdin.txt Note: this can also be accomplished by passing `--stdin ...` using the [OpenArguments](#openarguments) property. +## SdkIsDesktop + +This property is a read-only property (setting it will have no effect) that +specifies whether we're building for a desktop platform (macOS or Mac Catalyst). + +This property is `true` when the target platform is macOS or Mac Catalyst, +and is not set for iOS or tvOS builds. + +Like `SdkIsSimulator`, this property is only set after [imports and +properties](/visualstudio/msbuild/build-process-overview#evaluate-imports-and-properties) +have been evaluated. + ## SdkIsDevice This property is a read-only property (setting it will have no effect) that @@ -1247,6 +1325,18 @@ Like `SdkIsSimulator`, this property is only set after [imports and properties](/visualstudio/msbuild/build-process-overview#evaluate-imports-and-properties) have been evaluated. +## SdkIsMobile + +This property is a read-only property (setting it will have no effect) that +specifies whether we're building for a mobile platform (iOS or tvOS). + +This property is `true` when the target platform is iOS or tvOS, and is not +set for macOS or Mac Catalyst builds. + +Like `SdkIsSimulator`, this property is only set after [imports and +properties](/visualstudio/msbuild/build-process-overview#evaluate-imports-and-properties) +have been evaluated. + ## SdkIsSimulator This property is a read-only property (setting it will have no effect) that @@ -1451,6 +1541,21 @@ Consider using the unified [AppBundleResourcePrefix](#appbundleresourceprefix) p See also [IPhoneResourcePrefix](#iphoneresourceprefix) and [MonoMacResourcePrefix](#monomacresourceprefix). +## XcodeLocation + +Specifies the location of Xcode. + +When the build searches for Xcode, it's done in this order: + +1. If the `XcodeLocation` property is set, use that. Note that since all environment variables are automatically MSBuild properties as well, it's also possible to set the `XcodeLocation` environment variable for the same effect. +2. If the `MD_APPLE_SDK_ROOT` environment variable is set, use that. +3. If either of the files `~/Library/Preferences/maui/Settings.plist` or `~/Library/Preferences/Xamarin/Settings.plist` exist, and has the property list value `AppleSdkRoot`, use that. +4. Use the system version of Xcode (as determined by executing `xcode-select --print-path`). + +> [!WARNING] +> Support for the `MD_APPLE_SDK_ROOT` environment variable, and the `~/Library/Preferences/maui/Settings.plist` and `~/Library/Preferences/Xamarin/Settings.plist` files, is deprecated and will be removed in the future. +> Going forward, choose which Xcode to use by either making it the system's version of Xcode (either using `xcode-select --switch ...` on the command line, or in Xcode's settings), or by setting the `XcodeLocation` MSBuild property / environment variable. + ## ZipPath The full path to the `zip` command-line tool. diff --git a/docs/code/class-handles.md b/docs/code/class-handles.md new file mode 100644 index 000000000000..48255fb5aa6a --- /dev/null +++ b/docs/code/class-handles.md @@ -0,0 +1,57 @@ +# Objective-C classes + +Objective-C classes can be referenced from managed code in several ways: + +* Calls to Class.GetHandle / GetHandleIntrinsic + +It's highly desirable to use a direct native reference to Objective-C classes when building a mobile app, for a few reasons: + +* It's faster at runtime, and the app is smaller. +* If the referenced Objective-C class comes from a third-party static library, the + native linker can remove it if it's configured to remove unused code + (because the native linker can't see that the class is in fact used + at runtime) unless there's a direct native reference to the class. + +On the other hand there's one scenario when a direct native reference is not desirable: when the native Objective-C class does not exist. + +In order to create a direct native reference to Objective-C classes, we need to know the names of those Objective-C classes. + +## The `InlineClassGetHandle` property + +This behavior is controlled by the `InlineClassGetHandle` MSBuild property, which +can either be enabled or disabled. + +See the [build properties documentation](../building-apps/build-properties.md) for default values. + +## How it works + +During the build we try to collect the following: + +* Any calls to `Class.GetHandle[Intrinsic]` APIs: we try to collect the class name (this might not always succeed, if the class name is not a constant). + +This is further complicated by the fact that we only want to create native +references for managed references that survive trimming. + +So we do the following: + +1. During trimming, two custom linker steps execute: + + * `InlineClassGetHandleStep`: for every call `Class.GetHandle` we've + collected, this step creates a P/Invoke to a native method that will + return the Objective-C class for that symbol (using a direct native + reference), and modifies the code that fetches that symbol to call said + P/Invoke. + +2. After trimming, we figure out which of those symbols survived: + + * For ILTrim: the `_CollectPostILTrimInformation` MSBuild target inspects + the trimmed assemblies and collects all the inlined P/Invokes that + survived. Per-assembly results are cached to speed up incremental builds. + * For NativeAOT: the `_CollectPostNativeAOTTrimInformation` MSBuild target + inspects the native object file (or static library) produced by NativeAOT, + collects all unresolved native references, and filters them against the + Objective-C classes to determine which survived. + +3. The `_PostTrimmingProcessing` MSBuild target takes the surviving symbols + from either path, generates the corresponding native Objective-C code, and + adds it to the list of files to compile and link into the final executable. diff --git a/docs/code/native-symbols.md b/docs/code/native-symbols.md new file mode 100644 index 000000000000..45aea7239827 --- /dev/null +++ b/docs/code/native-symbols.md @@ -0,0 +1,69 @@ +# Native symbols + +Native symbols can be referenced from managed code in several ways: + +* P/Invokes (DllImports) +* Calls to `dlsym`, which can happen through: + * The various APIs in `ObjCRuntime.Dlfcn` + * The various APIs in `System.Runtime.InteropServices.NativeLibrary` + * A P/Invoke directly into `dlsym` + +It's highly desirable to use a direct native reference to native symbols when building a mobile app, for a few reasons: + +* It's faster at runtime, and the app is smaller. +* If the referenced native symbol comes from a third-party static library, the + native linker can remove it if it's configured to remove unused code + (because the native linker can't see that the native symbol is in fact used + at runtime) unless there's a direct native reference to the symbol. + +On the other hand there's one scenario when a direct native reference is not desirable: when the native symbol does not exist. + +In order to create a direct native reference to native symbols, we need to know the names of those native symbols. + +## The `InlineDlfcnMethods` property + +This behavior is controlled by the `InlineDlfcnMethods` MSBuild property, which +has two modes: + +* `strict`: all calls to `ObjCRuntime.Dlfcn` APIs are inlined. +* `compatibility`: only calls that reference symbols from `[Field]` attributes are inlined. + +See the [build properties documentation](../building-apps/build-properties.md) for default values. + +## How it works + +During the build we try to collect the following: + +* Any property or field with the `[Foundation.Field]` attribute: we collect the symbol name. +* Any calls to the `ObjCRuntime.Dlfcn` APIs: we try to collect the symbol name (this might not always succeed, if the symbol name is not a constant). +* We don't process calls to `System.Runtime.InteropServices.NativeLibrary` at the moment (this may change in the future, if there's need). + +This is further complicated by the fact that we only want to create native +references for symbols that survive trimming. + +So we do the following: + +1. Before or during trimming, we run the inlining steps: + + * `ProcessExportedFields`: collects all members with `[Field]` attributes. + + * `InlineDlfcnMethodsStep`: inspects all calls to `ObjCRuntime.Dlfcn`, and + inlines them depending on the selected mode. If inlined, the step creates + a P/Invoke to a native method that will return the address for that symbol + (using a direct native reference), and modifies the code that fetches that + symbol to call said P/Invoke. + +2. After trimming, we figure out which of those symbols survived: + + * For ILTrim: the `_CollectPostILTrimInformation` MSBuild target inspects + the trimmed assemblies and collects all the inlined dlfcn P/Invokes that + survived. Per-assembly results are cached to speed up incremental builds. + + * For NativeAOT: the `_CollectPostNativeAOTTrimInformation` MSBuild target + inspects the native object file (or static library) produced by NativeAOT, + collects all unresolved native references, and filters them against the + inlined dlfcn symbols to determine which survived. + +3. The `_PostTrimmingProcessing` MSBuild target takes the surviving symbols + from either path, generates the corresponding native C code, and adds it to + the list of files to compile and link into the final executable. diff --git a/docs/guides/HowToBranch.md b/docs/guides/HowToBranch.md index ec95a74c03aa..46048712427c 100644 --- a/docs/guides/HowToBranch.md +++ b/docs/guides/HowToBranch.md @@ -20,8 +20,8 @@ sequence of events would be: 3. `dotnet/macios` branches `release/10.0.1xx-preview42` from `net10.0`: ```shell - $ dotnet checkout net10.0 - $ dotnet checkout -b release/10.0.1xx-preview42 + $ git checkout net10.0 + $ git checkout -b release/10.0.1xx-preview42 ``` Note that release candidates will use values such as `rc.1`, `rc.2`, etc. diff --git a/docs/native-library-interop.md b/docs/native-library-interop.md index eb70f789d4fe..50d7481a56ee 100644 --- a/docs/native-library-interop.md +++ b/docs/native-library-interop.md @@ -5,7 +5,7 @@ Native Library Interop (formerly referred to as the "Slim Binding" approach), re pattern for accessing native SDKs in .NET for iOS, Mac Catalyst, macOS, and tvOS projects. Starting in .NET 9, the .NET for iOS, Mac Catalyst, macOS, and tvOS SDKs support building -Xcode framework projects by using the `@(XcodeProjet)` build action. This is declared in +Xcode framework projects by using the `@(XcodeProject)` build action. This is declared in an MSBuild ItemGroup in a project file: ```xml @@ -19,8 +19,8 @@ the build process will attempt to create an XCFramework from the specified Xcode output will be added as a `@(NativeReference)` to the .NET project so that it can be bound and have its API surfaced via an [API definition][0] file. -Please see the [build-items](build-apps/build-items.md) docs for more information about -the `@(XcodeProjet)` build action. +Please see the [build-items](building-apps/build-items.md) docs for more information about +the `@(XcodeProject)` build action. Additional documentation and references can be found below: diff --git a/docs/os-onboarding.md b/docs/os-onboarding.md index db4f7364a34f..6bb151226afc 100644 --- a/docs/os-onboarding.md +++ b/docs/os-onboarding.md @@ -20,7 +20,7 @@ This involves: ### Bind new APIs -This is technically optional, because we can release support for a new OS version even if we bind any of the new APIs. +This is technically optional, because we can release support for a new OS version even if we don't bind any of the new APIs. Yet we try to bind most of new APIs, because it's hard to predict what users will need. diff --git a/docs/preparing-your-app-for-testflight.md b/docs/preparing-your-app-for-testflight.md index 306a2a32102e..70daa109d997 100644 --- a/docs/preparing-your-app-for-testflight.md +++ b/docs/preparing-your-app-for-testflight.md @@ -26,7 +26,6 @@ Here's an example within a project file that is correctly configured for publish net7.0-maccatalyst maccatalyst-x64;maccatalyst-arm64 Exe - enable true 14.2 YourAppName diff --git a/docs/update-api-docs.md b/docs/update-api-docs.md index b6260c476986..ddb1e000babc 100644 --- a/docs/update-api-docs.md +++ b/docs/update-api-docs.md @@ -24,7 +24,7 @@ The steps are: * Copy our platform assemblies and their xml files into their corresponding directory. * Create a new commit and push it to origin. -4. Go here: [Continuous Integration](https://ops.microsoft.com/#/repos/85f784f4-01e7-ffb8-ed06-a012f7d649c0?tabName=ci) (might need VPN enabled, otherwise sometimes you'll get a 403 error page) and then: +4. Go here: [OPS dotnet/macios-api-docs / Continuous Integration](https://ops.microsoft.com/#/repos/85f784f4-01e7-ffb8-ed06-a012f7d649c0?tabName=ci) (if you have to go through the authentication workflow you'll end up on the OPS homepage, in which case just click the link again) and then: * Expand the '.NET macios API docs' job, and then: * Change `Target Repo` -> `Target Branch` to `netX.Y-xcodeZ.W` (same branch as created above). @@ -49,7 +49,7 @@ The steps are: 7. Create a pull request in the [binaries](https://apidrop.visualstudio.com/_git/binaries) repository for the `netX.Y-xcodeZ.W` we created with the new assemblies (into the `master` branch). -8. The final step is to flip the monikers from prerelease to live monikers (another ticket has to be created for this). +8. The final step is to flip the monikers from prerelease to live monikers (another ticket has to be created for this). Sample ticket: [#540739](https://dev.azure.com/msft-skilling/Content/_workitems/edit/540739). ## How to create new monikers diff --git a/docs/website/binding_types_reference_guide.md b/docs/website/binding_types_reference_guide.md index 78b90f26cbca..ace56aab5bc3 100644 --- a/docs/website/binding_types_reference_guide.md +++ b/docs/website/binding_types_reference_guide.md @@ -1306,28 +1306,9 @@ This should map to Objective-C/clang use of `__attribute__((objc_designated_init ### DisableZeroCopyAttribute -This attribute is applied to string parameters or string properties and -instructs the code generator to not use the zero-copy string marshaling for -this parameter, and instead create a new NSString instance from the C# string. -This attribute is only required on strings if you instruct the generator to use -zero-copy string marshaling using either the `--zero-copy` command -line option or setting the assembly-level attribute `ZeroCopyStringsAttribute`. - -This is necessary in cases where the property is declared in Objective-C to -be a `retain` or `assign` property instead of a `copy` property. These typically -happen in third-party libraries that have been wrongly "optimized" by -developers. In general, `retain` or `assign` `NSString` properties are incorrect -since `NSMutableString` or user-derived classes of `NSString` might alter the -contents of the strings without the knowledge of the library code, subtly -breaking the application. Typically this happens due to premature -optimization. - -The following shows two such properties in Objective-C: - -```csharp -@property(nonatomic,retain) NSString *name; -@property(nonatomic,assign) NSString *name2; -``` +> **Note:** This attribute is obsolete and has no effect. Zero-copy string +> marshaling is no longer supported. The attribute is preserved for source +> compatibility but can be safely removed from binding definitions. @@ -2435,47 +2416,10 @@ This corresponds to `clang` [`__attribute__((objc_requires_super))`](https://cla ### ZeroCopyStringsAttribute -Only available in Xamarin.iOS 5.4 and newer. - -This attribute instructs the generator that the binding for this specific -library (if applied with `[assembly:]`) or type should use the fast -zero-copy string marshaling. This attribute is equivalent to passing the -command line option `--zero-copy` to the generator. - -When using zero-copy for strings, the generator effectively uses the same C# -string as the string that Objective-C consumes without incurring the creation of -a new `NSString` object and avoiding copying the data from the C# strings to the -Objective-C string. The only drawback of using Zero Copy strings is that you -must ensure that any string property that you wrap that happens to be flagged as -`retain` or `copy` has the `[DisableZeroCopy]` attribute set. This is -require because the handle for zero-copy strings is allocated on the stack and -is invalid upon the function return. - -Example: - -```csharp -[ZeroCopyStrings] -[BaseType (typeof (NSObject))] -interface MyBinding { - [Export ("name")] - string Name { get; set; } - - [Export ("domain"), NullAllowed] - string Domain { get; set; } - - [DisablZeroCopy] - [Export ("someRetainedNSString")] - string RetainedProperty { get; set; } -} - -``` - -You can also apply the attribute at the assembly level, and it will apply to -all the types of the assembly: - -```csharp -[assembly:ZeroCopyStrings] -``` +> **Note:** This attribute is obsolete and has no effect. Zero-copy string +> marshaling is no longer supported. The `--use-zero-copy` command line option +> is also no longer supported. The attribute is preserved for source +> compatibility but can be safely removed from binding definitions. ## Strongly-typed dictionaries diff --git a/docs/website/generator-errors.md b/docs/website/generator-errors.md index 1d135ecb476f..365a8964309d 100644 --- a/docs/website/generator-errors.md +++ b/docs/website/generator-errors.md @@ -128,7 +128,7 @@ Please go to [[FieldAttribute]](https://developer.xamarin.com/guides/cross-platf ### BI1026: `*`: Enums attributed with [\*] must have an underlying type of `long` or `ulong` -### BI1027: Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. +### BI1027: Support for ZeroCopy strings is not implemented. The --use-zero-copy option is not supported and will be ignored. ### BI1028: Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/dotnet/DefaultCompilationIncludes.md b/dotnet/DefaultCompilationIncludes.md index 3dec5cdb0a5f..9f14799e6634 100644 --- a/dotnet/DefaultCompilationIncludes.md +++ b/dotnet/DefaultCompilationIncludes.md @@ -33,6 +33,13 @@ All \*.pdf, \*.jpg, \*.png and \*.json files inside asset catalogs (\*.xcassets) in the project directory or any subdirectory are included by default (as `ImageAsset` items). +## Icon Composer files + +All files inside Icon Composer directories (\*.icon) in the project directory +or any subdirectory are included by default (as `ImageAsset` items). Icon +Composer files are created by Xcode's Icon Composer tool (Xcode 26+) and +contain layered app icons with `icon.json` metadata. + ## Atlas Textures All \*.png files inside \*.atlas directories in the project directory or any @@ -52,7 +59,7 @@ included by default (as `Metal` items). All files in the Resources/ subdirectory, except any items in the `Compile` or `EmbeddedResource` item groups, and except the ones mentioned above -(\*.scnassets, \*.storyboard, \*.xib, \*.xcassets, \*.atlas, \*.mlmodel, +(\*.scnassets, \*.storyboard, \*.xib, \*.xcassets, \*.icon, \*.atlas, \*.mlmodel, \*.metal) are included by default (as `BundleResource` items). [1]: https://docs.microsoft.com/en-us/dotnet/core/tools/csproj#default-compilation-includes-in-net-core-projects diff --git a/dotnet/Microsoft.iOS.Sdk/targets/Microsoft.iOS.Sdk.props b/dotnet/Microsoft.iOS.Sdk/targets/Microsoft.iOS.Sdk.props index 563467607ff5..4f21cc40f0a9 100644 --- a/dotnet/Microsoft.iOS.Sdk/targets/Microsoft.iOS.Sdk.props +++ b/dotnet/Microsoft.iOS.Sdk/targets/Microsoft.iOS.Sdk.props @@ -4,6 +4,7 @@ <_PlatformName>iOS <_PlatformRidNoArch>ios + <_UseDesktopTaskAssemblies Condition="'$(_UseDesktopTaskAssemblies)' == '' And '$(BuildingInsideVisualStudio)' == 'true'">true $(MSBuildThisFileDirectory)..\tools\msbuild\net$(BundledNETCoreAppTargetFrameworkVersion)\ $(MSBuildThisFileDirectory)..\tools\msbuild\netstandard2.0\ diff --git a/dotnet/SingleProject.md b/dotnet/SingleProject.md index be4729e9d046..9a20de442520 100644 --- a/dotnet/SingleProject.md +++ b/dotnet/SingleProject.md @@ -18,8 +18,7 @@ Info.plist in the project doesn't already contain entries for these keys): | ApplicationDisplayVersion | CFBundleShortVersionString | Defaults to ApplicationVersion when blank | This is only enabled if the `GenerateApplicationManifest` is set to `true` -(which is the default for `.NET 6`, and not for "legacy" -Xamarin.iOS/Xamarin.Mac) +(which is the default for all supported .NET versions) Additionally, `$(ApplicationDisplayVersion)` will overwrite the value for `$(Version)`, so the following properties will be set with the same value: @@ -30,5 +29,5 @@ so the following properties will be set with the same value: Ref: [Issue #10473][2] -[1]: https://github.com/xamarin/xamarin-android/blob/40cedfa89c2660479fcb5e2482d2463fbcad1d04/Documentation/guides/OneDotNetSingleProject.md +[1]: https://github.com/dotnet/android/blob/main/Documentation/guides/OneDotNetSingleProject.md [2]: https://github.com/dotnet/macios/issues/10473 diff --git a/dotnet/Templates/Microsoft.iOS.Templates/ios/fsharp/SceneDelegate.fs b/dotnet/Templates/Microsoft.iOS.Templates/ios/fsharp/SceneDelegate.fs index 0599e6877171..2a516579203a 100644 --- a/dotnet/Templates/Microsoft.iOS.Templates/ios/fsharp/SceneDelegate.fs +++ b/dotnet/Templates/Microsoft.iOS.Templates/ios/fsharp/SceneDelegate.fs @@ -9,7 +9,7 @@ interface IUIWindowSceneDelegate [] - member val Window : UIWindow = null with get, set + member val Window : UIWindow | null = null with get, set [] member this.WillConnect(scene: UIScene, session: UISceneSession, connectionOptions: UISceneConnectionOptions) = @@ -20,22 +20,28 @@ | :? UIWindowScene as windowScene -> if isNull this.Window then this.Window <- new UIWindow(windowScene) - - // create a UIViewController with a single UILabel - let vc = new UIViewController() - vc.View.AddSubview( - new UILabel( - this.Window.Frame, - BackgroundColor = UIColor.SystemBackground, - TextAlignment = UITextAlignment.Center, - Text = "Hello, iOS!", - AutoresizingMask = UIViewAutoresizing.All - ) - ) - this.Window.RootViewController <- vc - // make the window visible - this.Window.MakeKeyAndVisible() + match this.Window with + | null -> () + | window -> + // create a UIViewController with a single UILabel + let vc = new UIViewController() + match vc.View with + | null -> () + | view -> + view.AddSubview( + new UILabel( + window.Frame, + BackgroundColor = UIColor.SystemBackground, + TextAlignment = UITextAlignment.Center, + Text = "Hello, iOS!", + AutoresizingMask = UIViewAutoresizing.All + ) + ) + window.RootViewController <- vc + + // make the window visible + window.MakeKeyAndVisible() | _ -> () diff --git a/dotnet/targets/Microsoft.Sdk.DefaultItems.template.props b/dotnet/targets/Microsoft.Sdk.DefaultItems.template.props index d705ae3f56c2..afc08fe18531 100644 --- a/dotnet/targets/Microsoft.Sdk.DefaultItems.template.props +++ b/dotnet/targets/Microsoft.Sdk.DefaultItems.template.props @@ -24,7 +24,7 @@ - + $([MSBuild]::MakeRelative ('$(MSBuildProjectDirectory)', '%(FullPath)')) false true @@ -65,6 +65,7 @@ $(DefaultItemExcludes); $(DefaultExcludesInProjectFolder); $(_ResourcePrefix)\**\*.xcassets\**\*.*; + $(_ResourcePrefix)\**\*.icon\**\*.*; $(_ResourcePrefix)\**\*.storyboard;**\*.xib; $(_ResourcePrefix)\**\*.atlas\*.png; $(_ResourcePrefix)\**\*.mlmodel; diff --git a/dotnet/targets/Microsoft.Sdk.Desktop.targets b/dotnet/targets/Microsoft.Sdk.Desktop.targets index 276822e3c2e4..d8d90ab7c46d 100644 --- a/dotnet/targets/Microsoft.Sdk.Desktop.targets +++ b/dotnet/targets/Microsoft.Sdk.Desktop.targets @@ -4,7 +4,7 @@ Name="_PrepareRunDesktop" BeforeTargets="ComputeRunArguments" DependsOnTargets="_ValidateHotReloadConfiguration" - Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'"> + Condition="'$(SdkIsDesktop)' == 'true'"> @@ -145,7 +145,7 @@ Name="_PrepareRunMobile" BeforeTargets="ComputeRunArguments" DependsOnTargets="_ValidateHotReloadConfiguration;_InstallMobile;ComputeMlaunchRunArguments" - Condition="'$(_PlatformName)' != 'macOS' And '$(_PlatformName)' != 'MacCatalyst'"> + Condition="'$(SdkIsDesktop)' != 'true'"> <_FilterDevicesToRuntimeIdentifier Condition="'$(_XamarinUsingDefaultRuntimeIdentifier)' != 'true'">$(RuntimeIdentifier) diff --git a/dotnet/targets/Xamarin.Shared.Sdk.DefaultItems.targets b/dotnet/targets/Xamarin.Shared.Sdk.DefaultItems.targets index 973f26394330..42b125875d12 100644 --- a/dotnet/targets/Xamarin.Shared.Sdk.DefaultItems.targets +++ b/dotnet/targets/Xamarin.Shared.Sdk.DefaultItems.targets @@ -68,37 +68,4 @@ - - - - - - - - - - 6.0.3 - - diff --git a/dotnet/targets/Xamarin.Shared.Sdk.Publish.targets b/dotnet/targets/Xamarin.Shared.Sdk.Publish.targets index 44d97039ff5e..c053793baf15 100644 --- a/dotnet/targets/Xamarin.Shared.Sdk.Publish.targets +++ b/dotnet/targets/Xamarin.Shared.Sdk.Publish.targets @@ -2,8 +2,8 @@ - true - true + true + true $(PublishDir) @@ -21,7 +21,7 @@ /> - - + + diff --git a/dotnet/targets/Xamarin.Shared.Sdk.Trimming.props b/dotnet/targets/Xamarin.Shared.Sdk.Trimming.props index c2b34b5d4c10..02dd815c5f81 100644 --- a/dotnet/targets/Xamarin.Shared.Sdk.Trimming.props +++ b/dotnet/targets/Xamarin.Shared.Sdk.Trimming.props @@ -50,8 +50,11 @@ <_DefaultLinkMode Condition="'$(_DefaultLinkMode)' == '' And '$(_UseNativeAot)' == 'true'">Full - - <_DefaultLinkMode Condition="'$(_DefaultLinkMode)' == '' And '$(UseMonoRuntime)' != 'true'">None + + <_DefaultLinkMode Condition="'$(_DefaultLinkMode)' == '' And '$(UseMonoRuntime)' != 'true' And '$(_PlatformName)' == 'macOS'">None + + + <_DefaultLinkMode Condition="'$(_DefaultLinkMode)' == '' And '$(UseMonoRuntime)' != 'true' And '$(_SdkIsSimulator)' == 'true'">None <_DefaultLinkMode Condition="'$(_DefaultLinkMode)' == '' And '$(_PlatformName)' == 'MacCatalyst' And '$(Configuration)' == 'Release'">SdkOnly @@ -62,10 +65,10 @@ <_DefaultLinkMode Condition="'$(_DefaultLinkMode)' == '' And '$(_PlatformName)' == 'MacCatalyst'">None - - <_DefaultLinkMode Condition="'$(_DefaultLinkMode)' == '' And '$(_SdkIsSimulator)' == 'true' And $(RuntimeIdentifier.Contains('arm64')) And '$(MtouchInterpreter)' == ''">SdkOnly - - <_DefaultLinkMode Condition="'$(_DefaultLinkMode)' == '' And '$(_SdkIsSimulator)' == 'true' And (!$(RuntimeIdentifier.Contains('arm64')) Or '$(MtouchInterpreter)' != '')">None + + <_DefaultLinkMode Condition="'$(_DefaultLinkMode)' == '' And '$(_SdkIsSimulator)' == 'true' And '$(UseMonoRuntime)' == 'true' And $(RuntimeIdentifier.Contains('arm64')) And '$(MtouchInterpreter)' == ''">SdkOnly + + <_DefaultLinkMode Condition="'$(_DefaultLinkMode)' == '' And '$(_SdkIsSimulator)' == 'true' And '$(UseMonoRuntime)' == 'true' And (!$(RuntimeIdentifier.Contains('arm64')) Or '$(MtouchInterpreter)' != '')">None <_DefaultLinkMode Condition="'$(_DefaultLinkMode)' == ''">SdkOnly diff --git a/dotnet/targets/Xamarin.Shared.Sdk.props b/dotnet/targets/Xamarin.Shared.Sdk.props index ae5137fbbf76..ce84e27e899b 100644 --- a/dotnet/targets/Xamarin.Shared.Sdk.props +++ b/dotnet/targets/Xamarin.Shared.Sdk.props @@ -101,6 +101,18 @@ false + + + strict + compatibility + + + + + strict + compatibility + + @@ -148,8 +160,14 @@ $(_SdkIsSimulator) + + true + - true + true + + + true iPhoneSimulator @@ -199,7 +217,7 @@ but the MtouchUseLlvm value is ignored when using the simulator, so it doesn't matter if we set it in all cases. --> - + true diff --git a/dotnet/targets/Xamarin.Shared.Sdk.targets b/dotnet/targets/Xamarin.Shared.Sdk.targets index 341e08ac0808..02926aa4ed8c 100644 --- a/dotnet/targets/Xamarin.Shared.Sdk.targets +++ b/dotnet/targets/Xamarin.Shared.Sdk.targets @@ -18,6 +18,9 @@ + + + @@ -25,6 +28,7 @@ + - - + + @@ -531,8 +535,8 @@ - Otherwise set 'dynamic' --> managed-static - managed-static - managed-static + managed-static + managed-static partial-static dynamic @@ -597,7 +601,7 @@ <_LinkerCacheDirectory Condition="'$(BuildSessionId)' != ''">$(IntermediateOutputPath)linker-cache - <_IsSimulatorFeature Condition="('$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS') And '$(_SdkIsSimulator)' == 'true'">true + <_IsSimulatorFeature Condition="'$(SdkIsMobile)' == 'true' And '$(_SdkIsSimulator)' == 'true'">true <_IsSimulatorFeature Condition="'$(_IsSimulatorFeature)' == ''">false @@ -638,7 +642,10 @@ @(_BundlerEnvironmentVariables -> 'EnvironmentVariable=Overwrite=%(Overwrite)|%(Identity)=%(Value)') @(_XamarinFrameworkAssemblies -> 'FrameworkAssembly=%(Filename)') Interpreter=$(MtouchInterpreter) + InlineClassGetHandle=$(InlineClassGetHandle) + InlineDlfcnMethods=$(InlineDlfcnMethods) IntermediateLinkDir=$(IntermediateLinkDir) + IntermediateOutputPath=$(DeviceSpecificIntermediateOutputPath) InvariantGlobalization=$(InvariantGlobalization) HybridGlobalization=$(HybridGlobalization) ItemsDirectory=$(_LinkerItemsDirectory) @@ -668,6 +675,7 @@ TargetArchitectures=$(TargetArchitectures) TargetFramework=$(_ComputedTargetFrameworkMoniker) TypeMapAssemblyName=$(_TypeMapAssemblyName) + TypeMapFilePath=$(_TypeMapFilePath) TypeMapOutputDirectory=$(_TypeMapOutputDirectory) UseLlvm=$(MtouchUseLlvm) Verbosity=$(_BundlerVerbosity) @@ -785,12 +793,14 @@ <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="MarkStep" Type="Xamarin.Linker.Steps.ApplyPreserveAttributeStep" Condition="'$(_AreAnyAssembliesTrimmed)' == 'true' And '$(_UseLinkDescriptionForApplyPreserveAttribute)' == 'true'" /> <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="MarkStep" Type="Xamarin.Linker.Steps.MarkForStaticRegistrarStep" Condition="'$(_AreAnyAssembliesTrimmed)' == 'true' And '$(_UseDynamicDependenciesForMarkStaticRegistrar)' == 'true'" /> <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="MarkStep" Type="Xamarin.Linker.Steps.MarkNSObjectsStep" Condition="'$(_AreAnyAssembliesTrimmed)' == 'true' And '$(_UseDynamicDependenciesForMarkNSObjects)' == 'true'" /> + <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="MarkStep" Type="Xamarin.Linker.Steps.InlineDlfcnMethodsStep" Condition="'$(InlineDlfcnMethods)' != ''" /> <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="MarkStep" Type="MonoTouch.Tuner.RegistrarRemovalTrackingStep" /> <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="MarkStep" Condition="'$(_AreAnyAssembliesTrimmed)' == 'true'" Type="Xamarin.Linker.Steps.PreMarkDispatcher" /> <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="MarkStep" Type="Xamarin.Linker.ManagedRegistrarStep" Condition="'$(Registrar)' == 'managed-static' Or '$(Registrar)' == 'trimmable-static'" /> <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="MarkStep" Type="Xamarin.Linker.TrimmableRegistrarStep" Condition="'$(Registrar)' == 'trimmable-static'" /> + <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="MarkStep" Type="Xamarin.Linker.Steps.InlineClassGetHandleStep" Condition="'$(InlineClassGetHandle)' != '' And '$(InlineClassGetHandle)' != 'disabled'" /> <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="OutputStep" Type="Xamarin.Linker.Steps.ListExportedSymbols" /> <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="OutputStep" Type="Xamarin.Linker.Steps.PreOutputDispatcher" /> - <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="OutputStep" Type="Xamarin.Linker.ClassHandleRewriterStep" /> + <_TrimmerCustomSteps Include="$(_AdditionalTaskAssembly)" BeforeStep="OutputStep" Type="Xamarin.Linker.ClassHandleRewriterStep" Condition="'$(InlineClassGetHandle)' == '' Or '$(InlineClassGetHandle)' == 'disabled'" /> - <_RunAotCompiler Condition="'$(_SdkIsSimulator)' != 'true' And '$(_PlatformName)' != 'macOS' And '$(_PlatformName)' != 'MacCatalyst'">true + <_RunAotCompiler Condition="'$(_SdkIsSimulator)' != 'true' And '$(SdkIsDesktop)' != 'true'">true <_RunAotCompiler Condition="'$(MtouchInterpreter)' != '' And '$(_PlatformName)' != 'macOS'">true @@ -1272,10 +1282,10 @@ <_IntermediateNativeLibraryDir>$(IntermediateOutputPath)nativelibraries/ <_IntermediateFrameworksDir>$(DeviceSpecificIntermediateOutputPath)frameworks <_IntermediateDecompressionDir>$([MSBuild]::EnsureTrailingSlash('$(DeviceSpecificIntermediateOutputPath)decompressed')) - <_NativeExecutablePublishDir Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS'">$(_RelativeAppBundlePath)\ - <_NativeExecutablePublishDir Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">$(_RelativeAppBundlePath)\Contents\MacOS\ - <_AppBundleFrameworksDir Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS'">$(_RelativeAppBundlePath)\Frameworks\ - <_AppBundleFrameworksDir Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">$(_RelativeAppBundlePath)\Contents\Frameworks\ + <_NativeExecutablePublishDir Condition="'$(SdkIsMobile)' == 'true'">$(_RelativeAppBundlePath)\ + <_NativeExecutablePublishDir Condition="'$(SdkIsDesktop)' == 'true'">$(_RelativeAppBundlePath)\Contents\MacOS\ + <_AppBundleFrameworksDir Condition="'$(SdkIsMobile)' == 'true'">$(_RelativeAppBundlePath)\Frameworks\ + <_AppBundleFrameworksDir Condition="'$(SdkIsDesktop)' == 'true'">$(_RelativeAppBundlePath)\Contents\Frameworks\ <_AOTInputDirectory>$(_IntermediateNativeLibraryDir)aot-input/ <_AOTOutputDirectory>$(_IntermediateNativeLibraryDir)aot-output/ @@ -1308,20 +1318,23 @@ <_LibXamarinDebug Condition="'$(_BundlerDebug)' == 'true'">-debug <_LibXamarinName Condition="'$(_LibXamarinName)' == ''">libxamarin-dotnet$(_LibXamarinRuntime)$(_LibXamarinDebug).$(_LibXamarinExtension) - <_DylibRPath Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS'">@executable_path - <_DylibRPath Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">@executable_path/../$(_CustomBundleName)/ + <_DylibRPath Condition="'$(SdkIsMobile)' == 'true'">@executable_path + <_DylibRPath Condition="'$(SdkIsDesktop)' == 'true'">@executable_path/../$(_CustomBundleName)/ - <_EmbeddedFrameworksRPath Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS'">@executable_path/Frameworks - <_EmbeddedFrameworksRPath Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">@executable_path/../Frameworks/ + <_EmbeddedFrameworksRPath Condition="'$(SdkIsMobile)' == 'true'">@executable_path/Frameworks + <_EmbeddedFrameworksRPath Condition="'$(SdkIsDesktop)' == 'true'">@executable_path/../Frameworks/ <_RuntimeConfigurationFile>runtimeconfig.bin + + + <_TypeMapFilePath Condition="'$(_TypeMapFilePath)' == ''">$(DeviceSpecificIntermediateOutputPath)type-map.txt <_CustomLinkFlags Include="-rpath" /> - <_CustomLinkFlags Include="@executable_path/../../Frameworks" Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS'" /> - <_CustomLinkFlags Include="@executable_path/../../../../Frameworks" Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'" /> + <_CustomLinkFlags Include="@executable_path/../../Frameworks" Condition="'$(SdkIsMobile)' == 'true'" /> + <_CustomLinkFlags Include="@executable_path/../../../../Frameworks" Condition="'$(SdkIsDesktop)' == 'true'" /> @@ -1670,6 +1683,100 @@ + + + <_TrimmedAssembly Include="$(IntermediateLinkDir)*.dll" /> + + + + + + <_ILTrimSurvivingNativeSymbolsFile>$(DeviceSpecificIntermediateOutputPath)inlined-dlfcn\iltrim-surviving-native-symbols.txt + <_NativeAOTSurvivingNativeSymbolsFile>$(DeviceSpecificIntermediateOutputPath)nativeaot-surviving-native-symbols.txt + <_ILTrimSurvivingClassesFile>$(DeviceSpecificIntermediateOutputPath)inlined-class-gethandle\iltrim-classes.txt + <_NativeAOTSurvivingClassesFile>$(DeviceSpecificIntermediateOutputPath)inlined-class-gethandle\nativeaot-classes.txt + + + + + + + + + + + + + + + + + + + <_SurvivingNativeSymbolsFile Include="$(_ILTrimSurvivingNativeSymbolsFile)" Condition="Exists('$(_ILTrimSurvivingNativeSymbolsFile)')" /> + <_SurvivingNativeSymbolsFile Include="$(_NativeAOTSurvivingNativeSymbolsFile)" Condition="Exists('$(_NativeAOTSurvivingNativeSymbolsFile)')" /> + + <_SurvivingClassesFiles Include="$(_ILTrimSurvivingClassesFile)" Condition="Exists('$(_ILTrimSurvivingClassesFile)')" /> + <_SurvivingClassesFiles Include="$(_NativeAOTSurvivingClassesFile)" Condition="Exists('$(_NativeAOTSurvivingClassesFile)')" /> + + + + + + + + <_PostTrimmingSourceFiles> + $(DeviceSpecificIntermediateOutputPath)posttrim-info-compiled/%(Arch)/%(Filename).o + + <_NativeExecutableObjectFiles Include="@(_PostTrimmingSourceFiles -> '%(OutputFile)')" /> + + + + + + + + + + + + <_CompileNativeExecutableDependsOn> $(_CompileNativeExecutableDependsOn); @@ -1726,6 +1833,7 @@ _ReadAppManifest; _WriteAppManifest; _CompileNativeExecutable; + _CompilePostTrimmingFiles; _ReidentifyDynamicLibraries; _AddSwiftLinkerFlags; _ComputeLinkNativeExecutableInputs; @@ -1733,6 +1841,33 @@ + + + + <_NativeAOTUnresolvedSymbolsFile>$(DeviceSpecificIntermediateOutputPath)nativeaot-unresolved-symbols.txt + + + + + + + + + @@ -1903,8 +2038,8 @@ - <_ExecutablePathPrefix Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS'">@executable_path/ - <_ExecutablePathPrefix Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">@executable_path/../../ + <_ExecutablePathPrefix Condition="'$(SdkIsMobile)' == 'true'">@executable_path/ + <_ExecutablePathPrefix Condition="'$(SdkIsDesktop)' == 'true'">@executable_path/../../ @@ -2072,10 +2207,10 @@ Condition="'$(_CanOutputAppBundle)' == 'true'" > - <_AssemblyPublishDir Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS'">$(_RelativeAppBundlePath)\ - <_AssemblyPublishDir Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">$(_RelativeAppBundlePath)\Contents\$(_CustomBundleName)\ - <_DylibPublishDir Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS'">$(_RelativeAppBundlePath)\ - <_DylibPublishDir Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">$(_RelativeAppBundlePath)\Contents\$(_CustomBundleName)\ + <_AssemblyPublishDir Condition="'$(SdkIsMobile)' == 'true'">$(_RelativeAppBundlePath)\ + <_AssemblyPublishDir Condition="'$(SdkIsDesktop)' == 'true'">$(_RelativeAppBundlePath)\Contents\$(_CustomBundleName)\ + <_DylibPublishDir Condition="'$(SdkIsMobile)' == 'true'">$(_RelativeAppBundlePath)\ + <_DylibPublishDir Condition="'$(SdkIsDesktop)' == 'true'">$(_RelativeAppBundlePath)\Contents\$(_CustomBundleName)\ <_ParsedRuntimeConfigFilePath Condition="'$(_ParsedRuntimeConfigFilePath)' == ''">$(DeviceSpecificIntermediateOutputPath)$(_RuntimeConfigurationFile) @@ -2105,7 +2240,7 @@ + Condition="('$(_SdkIsSimulator)' != 'false' Or '$(SdkIsDesktop)' == 'true') And ('%(Extension)' == '.dylib' Or '%(Extension)' == '.so') " /> - 10.0.0-beta.26216.121 - 10.0.0-beta.26216.121 + 10.0.0-beta.26281.104 + 10.0.0-beta.26281.104 0.11.5-alpha.26070.104 - 10.0.0-beta.26216.121 + 10.0.0-beta.26281.104 10.0.3-servicing.26070.104 10.0.3 10.0.3 - 10.0.300-preview.0.26216.121 + 10.0.400-preview.0.26281.104 10.0.3 - 10.0.300-preview.26216.121 + 10.0.400-preview.26281.104 26.0.11017 18.5.9227 - 26.4.9015 + 26.5.9004 26.0.11017 18.5.9227 - 26.4.9015 + 26.5.9004 26.0.11017 15.5.9227 - 26.4.9015 + 26.5.9004 26.0.11017 18.5.9227 - 26.4.9015 + 26.5.9004 - 11.0.0-prerelease.26224.1 + 11.0.0-prerelease.26264.1 18.0.9617 18.0.9617 @@ -53,16 +53,16 @@ This file should be imported by eng/Versions.props $(MicrosoftiOSSdknet100_260PackageVersion) $(MicrosoftiOSSdknet90_185PackageVersion) - $(MicrosoftiOSSdknet90_264PackageVersion) + $(MicrosoftiOSSdknet90_265PackageVersion) $(MicrosoftMacCatalystSdknet100_260PackageVersion) $(MicrosoftMacCatalystSdknet90_185PackageVersion) - $(MicrosoftMacCatalystSdknet90_264PackageVersion) + $(MicrosoftMacCatalystSdknet90_265PackageVersion) $(MicrosoftmacOSSdknet100_260PackageVersion) $(MicrosoftmacOSSdknet90_155PackageVersion) - $(MicrosoftmacOSSdknet90_264PackageVersion) + $(MicrosoftmacOSSdknet90_265PackageVersion) $(MicrosofttvOSSdknet100_260PackageVersion) $(MicrosofttvOSSdknet90_185PackageVersion) - $(MicrosofttvOSSdknet90_264PackageVersion) + $(MicrosofttvOSSdknet90_265PackageVersion) $(MicrosoftDotNetXHarnessiOSSharedPackageVersion) diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 176e4e77385e..f31e396323df 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,8 +1,8 @@ - + https://github.com/dotnet/dotnet - e43cbe04901ea4cf359ed0883b0533abab224ba2 + aec921632e75e1f29327709dd52e98c41f3b55cf https://github.com/dotnet/dotnet @@ -59,22 +59,22 @@ https://github.com/xamarin/xamarin-macios 797d30720e5e629d23eb146935da94cb1b61047e - - + + https://github.com/dotnet/macios - ac80159dab3bdd969c7e38fceb02499d3be92ac4 + 336ee8588b15a460a3ff34c3129d5d359e9d27aa - + https://github.com/dotnet/macios - ac80159dab3bdd969c7e38fceb02499d3be92ac4 + 336ee8588b15a460a3ff34c3129d5d359e9d27aa - + https://github.com/dotnet/macios - ac80159dab3bdd969c7e38fceb02499d3be92ac4 + 336ee8588b15a460a3ff34c3129d5d359e9d27aa - + https://github.com/dotnet/macios - ac80159dab3bdd969c7e38fceb02499d3be92ac4 + 336ee8588b15a460a3ff34c3129d5d359e9d27aa @@ -95,25 +95,25 @@ - + https://github.com/dotnet/dotnet - e43cbe04901ea4cf359ed0883b0533abab224ba2 + aec921632e75e1f29327709dd52e98c41f3b55cf - + https://github.com/dotnet/dotnet - e43cbe04901ea4cf359ed0883b0533abab224ba2 + aec921632e75e1f29327709dd52e98c41f3b55cf - + https://github.com/dotnet/dotnet - e43cbe04901ea4cf359ed0883b0533abab224ba2 + aec921632e75e1f29327709dd52e98c41f3b55cf - + https://github.com/dotnet/xharness - 888ef3e553a0716745ecab689e13b816639b5a5a + 51ca379106cfd749a498cb0822210ef1aa926e41 - + https://github.com/dotnet/dotnet - e43cbe04901ea4cf359ed0883b0533abab224ba2 + aec921632e75e1f29327709dd52e98c41f3b55cf diff --git a/external/Xamarin.MacDev b/external/Xamarin.MacDev index f1300986199f..95ec821da377 160000 --- a/external/Xamarin.MacDev +++ b/external/Xamarin.MacDev @@ -1 +1 @@ -Subproject commit f1300986199f5489191d2c9712e57bf8a0a3d84a +Subproject commit 95ec821da377c2dda841eed4578250cf9469b4ad diff --git a/global.json b/global.json index 5a1a6bf7167f..b2855704689d 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "10.0.300-preview.0.26216.121", + "version": "10.0.400-preview.0.26281.104", "paths": [ "builds/downloads/dotnet", "$host$" @@ -8,9 +8,9 @@ "errorMessage": "The .NET SDK could not be found, please run 'make dotnet -C builds'." }, "tools": { - "dotnet": "10.0.300-preview.0.26216.121" + "dotnet": "10.0.400-preview.0.26281.104" }, "msbuild-sdks": { - "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.26216.121" + "Microsoft.DotNet.Arcade.Sdk": "10.0.0-beta.26281.104" } } diff --git a/macios/Localize/loc/cs/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/cs/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index 620e5dd4fb7f..44c49d101321 100644 --- a/macios/Localize/loc/cs/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/cs/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/cs/macios/src/Resources.resx.lcl b/macios/Localize/loc/cs/macios/src/Resources.resx.lcl index 9549f1d38696..8e1699b9acaf 100644 --- a/macios/Localize/loc/cs/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/cs/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/cs/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/cs/macios/tools/mtouch/Errors.resx.lcl index d66a13518d03..e737c9d8e469 100644 --- a/macios/Localize/loc/cs/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/cs/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/de/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/de/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index b2fc70394ad2..564e87794819 100644 --- a/macios/Localize/loc/de/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/de/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/de/macios/src/Resources.resx.lcl b/macios/Localize/loc/de/macios/src/Resources.resx.lcl index 364c5c515e6e..1c29fc1ad7ee 100644 --- a/macios/Localize/loc/de/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/de/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/de/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/de/macios/tools/mtouch/Errors.resx.lcl index fc5a683a52d9..a92aca87125c 100644 --- a/macios/Localize/loc/de/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/de/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/es/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/es/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index f20f4cb2c0c9..b692e401e9c4 100644 --- a/macios/Localize/loc/es/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/es/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/es/macios/src/Resources.resx.lcl b/macios/Localize/loc/es/macios/src/Resources.resx.lcl index 85246e0ce950..b097266a8d41 100644 --- a/macios/Localize/loc/es/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/es/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/es/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/es/macios/tools/mtouch/Errors.resx.lcl index 71d382396cc5..3040949dddb1 100644 --- a/macios/Localize/loc/es/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/es/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/fr/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/fr/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index fada47500cc4..e47ef87b934e 100644 --- a/macios/Localize/loc/fr/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/fr/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/fr/macios/src/Resources.resx.lcl b/macios/Localize/loc/fr/macios/src/Resources.resx.lcl index 6175b9d20601..d8878181007a 100644 --- a/macios/Localize/loc/fr/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/fr/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/fr/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/fr/macios/tools/mtouch/Errors.resx.lcl index d3a69c437805..57d5b027ef04 100644 --- a/macios/Localize/loc/fr/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/fr/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/it/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/it/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index f1a86dc8993b..c67c30add6ac 100644 --- a/macios/Localize/loc/it/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/it/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/it/macios/src/Resources.resx.lcl b/macios/Localize/loc/it/macios/src/Resources.resx.lcl index 8b231c676455..c6f87770593a 100644 --- a/macios/Localize/loc/it/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/it/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/it/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/it/macios/tools/mtouch/Errors.resx.lcl index ae92e92ba6f7..70d4408c9f26 100644 --- a/macios/Localize/loc/it/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/it/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/ja/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/ja/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index f71a2b3a978f..429efcd0d6a5 100644 --- a/macios/Localize/loc/ja/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/ja/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/ja/macios/src/Resources.resx.lcl b/macios/Localize/loc/ja/macios/src/Resources.resx.lcl index b042a0a70bac..4ec32400c436 100644 --- a/macios/Localize/loc/ja/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/ja/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/ja/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/ja/macios/tools/mtouch/Errors.resx.lcl index ac518a9e3efd..0a5c0969fde0 100644 --- a/macios/Localize/loc/ja/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/ja/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/ko/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/ko/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index 638a95bf9892..8f6a9309a649 100644 --- a/macios/Localize/loc/ko/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/ko/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/ko/macios/src/Resources.resx.lcl b/macios/Localize/loc/ko/macios/src/Resources.resx.lcl index 2a6ec47780f7..b6f9d3f7c969 100644 --- a/macios/Localize/loc/ko/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/ko/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/ko/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/ko/macios/tools/mtouch/Errors.resx.lcl index bc908620c830..073974f830fe 100644 --- a/macios/Localize/loc/ko/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/ko/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/pl/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/pl/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index aff2c57e5e45..10afa0d41504 100644 --- a/macios/Localize/loc/pl/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/pl/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/pl/macios/src/Resources.resx.lcl b/macios/Localize/loc/pl/macios/src/Resources.resx.lcl index 535e5be2e3df..40459f23f097 100644 --- a/macios/Localize/loc/pl/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/pl/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/pl/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/pl/macios/tools/mtouch/Errors.resx.lcl index b51dc49757b8..d81fe2182e28 100644 --- a/macios/Localize/loc/pl/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/pl/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/pt-BR/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/pt-BR/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index e9b8116173e4..b36703f288b6 100644 --- a/macios/Localize/loc/pt-BR/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/pt-BR/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/pt-BR/macios/src/Resources.resx.lcl b/macios/Localize/loc/pt-BR/macios/src/Resources.resx.lcl index d12b83b1ff3e..b7ce10acb40c 100644 --- a/macios/Localize/loc/pt-BR/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/pt-BR/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/pt-BR/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/pt-BR/macios/tools/mtouch/Errors.resx.lcl index d893a87b4e74..7e153e535bc9 100644 --- a/macios/Localize/loc/pt-BR/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/pt-BR/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/ru/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/ru/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index 80fd78c3f715..ff190b437318 100644 --- a/macios/Localize/loc/ru/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/ru/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/ru/macios/src/Resources.resx.lcl b/macios/Localize/loc/ru/macios/src/Resources.resx.lcl index 7bc3cfac722a..095e1f672a82 100644 --- a/macios/Localize/loc/ru/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/ru/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/ru/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/ru/macios/tools/mtouch/Errors.resx.lcl index 80205c40569f..a0a2d50d4c8a 100644 --- a/macios/Localize/loc/ru/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/ru/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/tr/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/tr/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index 94ffb3bad606..3251464cd07f 100644 --- a/macios/Localize/loc/tr/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/tr/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/tr/macios/src/Resources.resx.lcl b/macios/Localize/loc/tr/macios/src/Resources.resx.lcl index 87909f7e2e5e..4cf6e27fa0dc 100644 --- a/macios/Localize/loc/tr/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/tr/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/tr/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/tr/macios/tools/mtouch/Errors.resx.lcl index 0b6e0841f004..2aedad71123b 100644 --- a/macios/Localize/loc/tr/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/tr/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/zh-Hans/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/zh-Hans/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index 00517d08e59d..2e41c4b28761 100644 --- a/macios/Localize/loc/zh-Hans/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/zh-Hans/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/zh-Hans/macios/src/Resources.resx.lcl b/macios/Localize/loc/zh-Hans/macios/src/Resources.resx.lcl index 2d4649df1b79..f5da49efa398 100644 --- a/macios/Localize/loc/zh-Hans/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/zh-Hans/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/zh-Hans/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/zh-Hans/macios/tools/mtouch/Errors.resx.lcl index 08b62dea5624..af179127e37e 100644 --- a/macios/Localize/loc/zh-Hans/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/zh-Hans/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/zh-Hant/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl b/macios/Localize/loc/zh-Hant/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl index b8f65ed4218a..0c5e6cd287eb 100644 --- a/macios/Localize/loc/zh-Hant/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl +++ b/macios/Localize/loc/zh-Hant/macios/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx.lcl @@ -3625,6 +3625,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macios/Localize/loc/zh-Hant/macios/src/Resources.resx.lcl b/macios/Localize/loc/zh-Hant/macios/src/Resources.resx.lcl index 21c2a5d3082f..0074c1598564 100644 --- a/macios/Localize/loc/zh-Hant/macios/src/Resources.resx.lcl +++ b/macios/Localize/loc/zh-Hant/macios/src/Resources.resx.lcl @@ -381,10 +381,13 @@ - + - + + + + diff --git a/macios/Localize/loc/zh-Hant/macios/tools/mtouch/Errors.resx.lcl b/macios/Localize/loc/zh-Hant/macios/tools/mtouch/Errors.resx.lcl index 0063007365b0..69beebeb0b2d 100644 --- a/macios/Localize/loc/zh-Hant/macios/tools/mtouch/Errors.resx.lcl +++ b/macios/Localize/loc/zh-Hant/macios/tools/mtouch/Errors.resx.lcl @@ -4501,6 +4501,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -4552,6 +4633,15 @@ + + + + + + + + + @@ -4882,6 +4972,24 @@ + + + + + + + + + + + + + + + + + + diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.cs.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.cs.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.cs.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.cs.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.de.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.de.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.de.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.de.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.es.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.es.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.es.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.es.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.fr.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.fr.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.fr.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.fr.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.it.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.it.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.it.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.it.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.ja.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.ja.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.ja.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.ja.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.ko.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.ko.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.ko.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.ko.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.pl.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.pl.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.pl.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.pl.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.pt-BR.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.pt-BR.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.pt-BR.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.pt-BR.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.ru.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.ru.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.ru.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.ru.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.tr.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.tr.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.tr.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.tr.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.zh-Hans.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.zh-Hans.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.zh-Hans.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.zh-Hans.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.zh-Hant.resx b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.zh-Hant.resx index 0714444b8e01..9f4afd35224d 100644 --- a/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.zh-Hant.resx +++ b/macios/msbuild/Xamarin.Localization.MSBuild/TranslatedAssemblies/MSBStrings.zh-Hant.resx @@ -1284,4 +1284,31 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + \ No newline at end of file diff --git a/macios/src/TranslatedAssemblies/Resources.cs.resx b/macios/src/TranslatedAssemblies/Resources.cs.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.cs.resx +++ b/macios/src/TranslatedAssemblies/Resources.cs.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/src/TranslatedAssemblies/Resources.de.resx b/macios/src/TranslatedAssemblies/Resources.de.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.de.resx +++ b/macios/src/TranslatedAssemblies/Resources.de.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/src/TranslatedAssemblies/Resources.es.resx b/macios/src/TranslatedAssemblies/Resources.es.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.es.resx +++ b/macios/src/TranslatedAssemblies/Resources.es.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/src/TranslatedAssemblies/Resources.fr.resx b/macios/src/TranslatedAssemblies/Resources.fr.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.fr.resx +++ b/macios/src/TranslatedAssemblies/Resources.fr.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/src/TranslatedAssemblies/Resources.it.resx b/macios/src/TranslatedAssemblies/Resources.it.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.it.resx +++ b/macios/src/TranslatedAssemblies/Resources.it.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/src/TranslatedAssemblies/Resources.ja.resx b/macios/src/TranslatedAssemblies/Resources.ja.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.ja.resx +++ b/macios/src/TranslatedAssemblies/Resources.ja.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/src/TranslatedAssemblies/Resources.ko.resx b/macios/src/TranslatedAssemblies/Resources.ko.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.ko.resx +++ b/macios/src/TranslatedAssemblies/Resources.ko.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/src/TranslatedAssemblies/Resources.pl.resx b/macios/src/TranslatedAssemblies/Resources.pl.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.pl.resx +++ b/macios/src/TranslatedAssemblies/Resources.pl.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/src/TranslatedAssemblies/Resources.pt-BR.resx b/macios/src/TranslatedAssemblies/Resources.pt-BR.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.pt-BR.resx +++ b/macios/src/TranslatedAssemblies/Resources.pt-BR.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/src/TranslatedAssemblies/Resources.ru.resx b/macios/src/TranslatedAssemblies/Resources.ru.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.ru.resx +++ b/macios/src/TranslatedAssemblies/Resources.ru.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/src/TranslatedAssemblies/Resources.tr.resx b/macios/src/TranslatedAssemblies/Resources.tr.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.tr.resx +++ b/macios/src/TranslatedAssemblies/Resources.tr.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/src/TranslatedAssemblies/Resources.zh-Hans.resx b/macios/src/TranslatedAssemblies/Resources.zh-Hans.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.zh-Hans.resx +++ b/macios/src/TranslatedAssemblies/Resources.zh-Hans.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/src/TranslatedAssemblies/Resources.zh-Hant.resx b/macios/src/TranslatedAssemblies/Resources.zh-Hant.resx index f4c1d83d2521..7b439f46e642 100644 --- a/macios/src/TranslatedAssemblies/Resources.zh-Hant.resx +++ b/macios/src/TranslatedAssemblies/Resources.zh-Hant.resx @@ -250,7 +250,7 @@ `{0}`: Enums attributed with [{1}] must have an underlying type of `long` or `ulong` - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. Internal sanity check failed, please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case. diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.cs.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.cs.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.cs.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.cs.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.de.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.de.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.de.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.de.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.es.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.es.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.es.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.es.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.fr.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.fr.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.fr.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.fr.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.it.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.it.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.it.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.it.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.ja.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.ja.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.ja.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.ja.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.ko.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.ko.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.ko.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.ko.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.pl.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.pl.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.pl.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.pl.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.pt-BR.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.pt-BR.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.pt-BR.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.pt-BR.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.ru.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.ru.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.ru.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.ru.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.tr.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.tr.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.tr.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.tr.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.zh-Hans.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.zh-Hans.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.zh-Hans.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.zh-Hans.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/macios/tools/mtouch/TranslatedAssemblies/Errors.zh-Hant.resx b/macios/tools/mtouch/TranslatedAssemblies/Errors.zh-Hant.resx index acaf24817a6d..ce4b85b8b369 100644 --- a/macios/tools/mtouch/TranslatedAssemblies/Errors.zh-Hant.resx +++ b/macios/tools/mtouch/TranslatedAssemblies/Errors.zh-Hant.resx @@ -832,6 +832,34 @@ + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + The linker step '{0}' failed during processing: {1} diff --git a/msbuild/ILMerge.targets b/msbuild/ILMerge.targets index f2e8caa95328..d8c87c68fccf 100644 --- a/msbuild/ILMerge.targets +++ b/msbuild/ILMerge.targets @@ -17,7 +17,7 @@ - + diff --git a/msbuild/Makefile b/msbuild/Makefile index 436e22a2c71c..49c7db013c83 100644 --- a/msbuild/Makefile +++ b/msbuild/Makefile @@ -119,7 +119,7 @@ DOTNET_IOS_WINDOWS_FILES += Messaging/Xamarin.Messaging.Build/obj/$(CONFIG)/Buil .dotnet-windows: .build-stamp .copy-windows-files -ifndef IS_LINUX +ifndef NO_XCODE all-local:: .dotnet-windows dotnet:: .dotnet-windows endif @@ -130,14 +130,14 @@ endif # we must install locally during 'make all', because the F# build depends on the msbuild targets/assemblies. all-local:: $(MSBUILD_PRODUCTS) -ifndef IS_LINUX +ifndef NO_XCODE all-local:: .stamp-test-xml endif # I haven't found a way to execute ilrepack.exe on .NET (it will probably have to be built for .NET), so run it using Mono. .build-stamp: $(ALL_SOURCES) - $(Q) $(DOTNET) build "/bl:$@.binlog" $(XBUILD_VERBOSITY) + $(Q) $(DOTNET) build "/bl:$@.binlog" $(XBUILD_VERBOSITY) /p:NuGetPackageRoot=$(abspath $(TOP)/packages)/ $(Q) touch $@ # make all the target assemblies build when any of the sources have changed diff --git a/msbuild/Messaging/Xamarin.Messaging.Build/Xamarin.Messaging.Build.csproj b/msbuild/Messaging/Xamarin.Messaging.Build/Xamarin.Messaging.Build.csproj index a8473bc9047c..36e5dc8eaa00 100644 --- a/msbuild/Messaging/Xamarin.Messaging.Build/Xamarin.Messaging.Build.csproj +++ b/msbuild/Messaging/Xamarin.Messaging.Build/Xamarin.Messaging.Build.csproj @@ -9,9 +9,6 @@ $(NoWarn);NU1603 $(NoWarn);MSB3277 true - enable - latest - Nullable false LatestMajor diff --git a/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx b/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx index f85052143906..5de6bb55b800 100644 --- a/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx +++ b/msbuild/Xamarin.Localization.MSBuild/MSBStrings.resx @@ -1627,4 +1627,38 @@ The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. + + + The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + + The environment variable '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + + The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + + The settings file '{0}' is deprecated, and will be ignored. Please use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. + + + + The {0} simulator runtime is not installed. This is required by Apple's development tools (even when building for physical devices). Install it by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the required simulator runtime is not installed. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + + Unable to determine if the {0} simulator runtime is installed. If the build fails or hangs, install the {0} simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line. + Shown when we're unable to check for simulator runtime availability. +{0} - The platform name (e.g. "iOS" or "tvOS"). + + + + The installed {0} simulator runtime is not compatible with the current Xcode version. Update the simulator runtime by running 'xcodebuild -downloadPlatform {0}' from the command line, or from Xcode (Settings > Components). + Shown when the tool reports a simulator runtime version mismatch. +{0} - The platform name (e.g. "iOS" or "tvOS"). + diff --git a/msbuild/Xamarin.Localization.MSBuild/Xamarin.Localization.MSBuild.csproj b/msbuild/Xamarin.Localization.MSBuild/Xamarin.Localization.MSBuild.csproj index ff948e805810..519494a39001 100644 --- a/msbuild/Xamarin.Localization.MSBuild/Xamarin.Localization.MSBuild.csproj +++ b/msbuild/Xamarin.Localization.MSBuild/Xamarin.Localization.MSBuild.csproj @@ -4,9 +4,6 @@ netstandard2.0;net$(BundledNETCoreAppTargetFrameworkVersion) true ../../product.snk - enable - latest - Nullable false diff --git a/msbuild/Xamarin.MacDev.Tasks/Decompress.cs b/msbuild/Xamarin.MacDev.Tasks/Decompress.cs index 2d4f755378de..234eb49cd852 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Decompress.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Decompress.cs @@ -108,7 +108,7 @@ public static bool TryDecompress (XamarinTask task, string zip, string resource, var stampFile = decompressedResource.TrimEnd ('\\', '/') + ".stamp"; - if (FileCopier.IsUptodate (zip, stampFile, XamarinTask.GetFileCopierReportErrorCallback (log), XamarinTask.GetFileCopierLogCallback (log), check_stamp: false)) + if (FileCopier.IsUptodate (task, zip, stampFile, check_stamp: false)) return true; // We use 'unzip' to extract on !Windows, and System.IO.Compression to extract on Windows. diff --git a/msbuild/Xamarin.MacDev.Tasks/Sdks.cs b/msbuild/Xamarin.MacDev.Tasks/Sdks.cs deleted file mode 100644 index ca04c9c665f1..000000000000 --- a/msbuild/Xamarin.MacDev.Tasks/Sdks.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.IO; - -using Xamarin.Localization.MSBuild; -using Xamarin.Utils; -using Xamarin.MacDev.Tasks; - -#nullable enable - -namespace Xamarin.MacDev { - public static class Sdks { - public static AppleIPhoneSdk IOS { get; private set; } - public static MacOSXSdk MacOS { get; private set; } - public static AppleTVOSSdk TVOS { get; private set; } - - static Sdks () - { - IOS = new AppleIPhoneSdk (AppleSdkSettings.DeveloperRoot, AppleSdkSettings.DeveloperRootVersionPlist); - TVOS = new AppleTVOSSdk (AppleSdkSettings.DeveloperRoot, AppleSdkSettings.DeveloperRootVersionPlist); - MacOS = new MacOSXSdk (AppleSdkSettings.DeveloperRoot, AppleSdkSettings.DeveloperRootVersionPlist); - } - - public static AppleSdk GetSdk (ApplePlatform framework) - { - switch (framework) { - case ApplePlatform.iOS: - return IOS; - case ApplePlatform.TVOS: - return TVOS; - default: - throw new InvalidOperationException (string.Format (MSBStrings.InvalidFramework, framework)); - } - } - - public static AppleSdk GetSdk (string targetFrameworkMoniker) - { - return GetSdk (PlatformFrameworkHelper.GetFramework (targetFrameworkMoniker)); - } - - public static IAppleSdk GetAppleSdk (ApplePlatform framework) - { - switch (framework) { - case ApplePlatform.iOS: - return IOS; - case ApplePlatform.TVOS: - return TVOS; - case ApplePlatform.MacCatalyst: - case ApplePlatform.MacOSX: - return MacOS; - default: - throw new InvalidOperationException (string.Format (MSBStrings.InvalidFramework, framework)); - } - } - - public static IAppleSdk GetAppleSdk (string targetFrameworkMoniker) - { - return GetAppleSdk (PlatformFrameworkHelper.GetFramework (targetFrameworkMoniker)); - } - - } -} diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/ACTool.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/ACTool.cs index 38d87d918f9f..829b904260e9 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/ACTool.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/ACTool.cs @@ -248,12 +248,12 @@ IEnumerable GetCompiledBundleResources (PDictionary output, string in yield break; } - void FindXCAssetsDirectory (string main, string secondary, out string mainResult, out string secondaryResult) + void FindAssetCatalogDirectory (string main, string secondary, out string mainResult, out string secondaryResult) { mainResult = main; secondaryResult = secondary; - while (!string.IsNullOrEmpty (mainResult) && !mainResult.EndsWith (".xcassets", StringComparison.OrdinalIgnoreCase)) { + while (!string.IsNullOrEmpty (mainResult) && !mainResult.EndsWith (".xcassets", StringComparison.OrdinalIgnoreCase) && !mainResult.EndsWith (".icon", StringComparison.OrdinalIgnoreCase)) { mainResult = Path.GetDirectoryName (mainResult)!; if (!string.IsNullOrEmpty (secondaryResult)) secondaryResult = Path.GetDirectoryName (secondaryResult)!; @@ -292,14 +292,14 @@ public override bool Execute () var vpath = BundleResource.GetVirtualProjectPath (this, imageAsset); var catalogFullPath = imageAsset.GetMetadata ("FullPath"); - // get the parent (which will typically be .appiconset, .launchimage, .imageset, .iconset, etc) + // get the parent (which will typically be .appiconset, .launchimage, .imageset, .iconset, .icon, etc) var catalog = Path.GetDirectoryName (vpath)!; catalogFullPath = Path.GetDirectoryName (catalogFullPath)!; var assetType = Path.GetExtension (catalog).TrimStart ('.'); - // keep walking up the directory structure until we get to the .xcassets directory - FindXCAssetsDirectory (catalog, catalogFullPath, out var catalog2, out var catalogFullPath2); + // keep walking up the directory structure until we get to the .xcassets or .icon directory + FindAssetCatalogDirectory (catalog, catalogFullPath, out var catalog2, out var catalogFullPath2); catalog = catalog2; catalogFullPath = catalogFullPath2; @@ -325,11 +325,11 @@ public override bool Execute () continue; } - // filter out everything except paths containing a Contents.json file since our main processing loop only cares about these - if (Path.GetFileName (vpath) != "Contents.json") - continue; - - items.Add (asset); + // Handle both Contents.json (for .xcassets) and icon.json (for .icon folders) + var fileName = Path.GetFileName (vpath); + if (fileName == "Contents.json" || fileName == "icon.json") { + items.Add (asset); + } } // clone any *.xcassets dirs that need cloning @@ -370,18 +370,20 @@ public override bool Execute () File.Copy (src, dest, true); - // filter out everything except paths containing a Contents.json file since our main processing loop only cares about these - if (Path.GetFileName (vpath) != "Contents.json") + // Handle both Contents.json (for .xcassets) and icon.json (for .icon folders) + var fileName = Path.GetFileName (vpath); + if (fileName != "Contents.json" && fileName != "icon.json") continue; item = new TaskItem (dest); assetItem.CopyMetadataTo (item); item.SetMetadata ("Link", vpath); - FindXCAssetsDirectory (Path.GetFullPath (dest), "", out var catalogFullPath, out var _); + FindAssetCatalogDirectory (Path.GetFullPath (dest), "", out var catalogFullPath, out var _); items.Add (new AssetInfo (item, vpath, asset.Catalog, catalogFullPath, asset.AssetType)); } else { - // filter out everything except paths containing a Contents.json file since our main processing loop only cares about these - if (Path.GetFileName (vpath) != "Contents.json") + // Handle both Contents.json (for .xcassets) and icon.json (for .icon folders) + var fileName = Path.GetFileName (vpath); + if (fileName != "Contents.json" && fileName != "icon.json") continue; items.Add (asset); @@ -389,7 +391,7 @@ public override bool Execute () } } - // Note: `items` contains only the Contents.json files at this point + // Note: `items` contains only the Contents.json and icon.json files at this point for (int i = 0; i < items.Count; i++) { var asset = items [i]; var assetItem = asset.Item; @@ -397,16 +399,19 @@ public override bool Execute () var catalog = asset.Catalog; var path = assetItem.GetMetadata ("FullPath"); var assetType = asset.AssetType; + var vpathDirNameWithoutExtension = Path.GetFileNameWithoutExtension (Path.GetDirectoryName (vpath)!); if (Platform == ApplePlatform.TVOS) { - if (assetType.Equals ("imagestack", StringComparison.OrdinalIgnoreCase)) { - imageStacksInAssets.Add (Path.GetFileNameWithoutExtension (Path.GetDirectoryName (vpath)!)); - } else if (assetType.Equals ("brandassets", StringComparison.OrdinalIgnoreCase)) { - brandAssetsInAssets.Add (Path.GetFileNameWithoutExtension (Path.GetDirectoryName (vpath)!)); + if (assetType.Equals ("imagestack", StringComparison.OrdinalIgnoreCase) || assetType.Equals ("icon", StringComparison.OrdinalIgnoreCase)) { + imageStacksInAssets.Add (vpathDirNameWithoutExtension); + } + if (assetType.Equals ("brandassets", StringComparison.OrdinalIgnoreCase) || assetType.Equals ("icon", StringComparison.OrdinalIgnoreCase)) { + brandAssetsInAssets.Add (vpathDirNameWithoutExtension); } } else { - if (assetType.Equals ("appiconset", StringComparison.OrdinalIgnoreCase)) - appIconsInAssets.Add (Path.GetFileNameWithoutExtension (Path.GetDirectoryName (vpath)!)); + if (assetType.Equals ("appiconset", StringComparison.OrdinalIgnoreCase) || assetType.Equals ("icon", StringComparison.OrdinalIgnoreCase)) { + appIconsInAssets.Add (vpathDirNameWithoutExtension); + } } if (unique.Add (catalog)) { @@ -416,7 +421,8 @@ public override bool Execute () catalogs.Add (item); } - if (SdkPlatform != "WatchSimulator") { + // Only process Contents.json files for on-demand resources (not icon.json files) + if (SdkPlatform != "WatchSimulator" && Path.GetFileName (vpath) == "Contents.json") { var text = File.ReadAllText (assetItem.ItemSpec); if (string.IsNullOrEmpty (text)) @@ -505,7 +511,7 @@ public override bool Execute () Log.LogError (MSBStrings.E0093, Path.GetFullPath (partialAppManifestPath)); try { - var manifestOutput = PDictionary.FromFile (manifest.ItemSpec)!; + var manifestOutput = PDictionary.OpenFile (manifest.ItemSpec); LogWarningsAndErrors (manifestOutput, catalogs [0]); diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/Archive.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/Archive.cs index f59676f4517d..61fad59d004c 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/Archive.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/Archive.cs @@ -120,7 +120,7 @@ public override bool Execute () var archiveDir = CreateArchiveDirectory (); try { - var plist = PDictionary.FromFile (PlatformFrameworkHelper.GetAppManifestPath (Platform, AppBundleDir.ItemSpec)); + var plist = PDictionary.OpenFile (PlatformFrameworkHelper.GetAppManifestPath (Platform, AppBundleDir.ItemSpec)); var productsDir = Path.Combine (archiveDir, "Products"); // Archive the OnDemandResources... @@ -293,7 +293,7 @@ protected string CreateArchiveDirectory () void ArchiveAppExtension (ITaskItem appex, string archiveDir) { - var plist = PDictionary.FromFile (Path.Combine (appex.ItemSpec, "Info.plist")!)!; + var plist = PDictionary.OpenFile (Path.Combine (appex.ItemSpec, "Info.plist")); if (IsWatchAppExtension (appex, plist, out var watchAppBundleDir)) { var wk = Path.Combine (watchAppBundleDir, "_WatchKitStub", "WK"); @@ -384,7 +384,7 @@ static bool IsWatchAppExtension (ITaskItem appex, PDictionary plist, [NotNullWhe if (!File.Exists (Path.Combine (bundle, "Info.plist"))) continue; - plist = PDictionary.FromFile (Path.Combine (bundle, "Info.plist"))!; + plist = PDictionary.OpenFile (Path.Combine (bundle, "Info.plist")); if (!plist.TryGetValue ("CFBundleIdentifier", out var bundleIdentifier)) continue; diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/BGen.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/BGen.cs index 1dce72ab1386..cfa8c01e85cf 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/BGen.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/BGen.cs @@ -55,8 +55,6 @@ public class BGen : XamarinTask, ICancelableTask { public string ExtraArgs { get; set; } = string.Empty; - public int Verbosity { get; set; } - public string GeneratedSourcesDir { get; set; } = string.Empty; public string GeneratedSourcesFileList { get; set; } = string.Empty; @@ -229,7 +227,7 @@ public virtual List GenerateCommandLineArguments () } } - cmd.AddRange (VerbosityUtils.Merge (ExtraArgs, (LoggerVerbosity) Verbosity)); + VerbosityUtils.RenderVerbosity (cmd, Verbosity); return CommandLineArgumentBuilder.CreateResponseFile (this, ResponseFilePath, cmd, null); } diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/Codesign.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/Codesign.cs index cf5a9f923574..e4b0e50212a8 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/Codesign.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/Codesign.cs @@ -619,7 +619,7 @@ IEnumerable GetCodesignedFiles (ITaskItem item) var manifestPath = Path.Combine (item.ItemSpec, "Info.plist"); if (File.Exists (manifestPath)) { - var bundleExecutable = PDictionary.FromFile (manifestPath).GetCFBundleExecutable (); + var bundleExecutable = PDictionary.OpenFile (manifestPath).GetCFBundleExecutable (); if (!string.IsNullOrEmpty (bundleExecutable)) executableName = bundleExecutable; diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/CollectPostILTrimInformation.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/CollectPostILTrimInformation.cs new file mode 100644 index 000000000000..7f2baaad79e3 --- /dev/null +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/CollectPostILTrimInformation.cs @@ -0,0 +1,144 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.IO; +using System.Linq; + +using Microsoft.Build.Framework; + +using Mono.Cecil; + +using Xamarin.Bundler; +using Xamarin.Utils; + +#nullable enable + +namespace Xamarin.MacDev.Tasks { + /// + /// Scans trimmed assemblies to collect information that survived trimming. + /// See docs/code/native-symbols.md and docs/code/class-handles.md for an overview of native symbol handling. + /// + public class CollectPostILTrimInformation : XamarinTask { + [Required] + public ITaskItem [] TrimmedAssemblies { get; set; } = []; + + /// + /// Output file listing the inlined dlfcn symbols that survived trimming. + /// + [Required] + public string SurvivingNativeSymbolsFile { get; set; } = ""; + + /// + /// Output file listing the Class.GetHandle calls that survived trimming. + /// + [Required] + public string SurvivingClassesFile { get; set; } = ""; + + /// + /// Directory for per-assembly cache files, to avoid re-scanning unchanged assemblies. + /// + [Required] + public string CacheDirectory { get; set; } = ""; + + public override bool Execute () + { + Directory.CreateDirectory (CacheDirectory); + + CollectSurvivingNativeSymbols (); + + return !Log.HasLoggedErrors; + } + + void CollectSurvivingNativeSymbols () + { + // Scan trimmed assemblies for surviving P/Invoke methods, using per-assembly caching. + var survivingSymbols = new HashSet (); + foreach (var item in TrimmedAssemblies) { + var assemblyPath = item.ItemSpec; + if (!File.Exists (assemblyPath)) + continue; + + var assemblyName = Path.GetFileNameWithoutExtension (assemblyPath); + var cacheFile = Path.Combine (CacheDirectory, assemblyName + ".internal-symbols.cache"); + + string []? cachedSymbols = null; + if (File.Exists (cacheFile) && File.GetLastWriteTimeUtc (cacheFile) >= File.GetLastWriteTimeUtc (assemblyPath)) { + cachedSymbols = File.ReadAllLines (cacheFile); + Log.LogMessage (MessageImportance.Low, "Using cached internal symbols for {0}", assemblyName); + + survivingSymbols.UnionWith (cachedSymbols); + } else { + var assemblySymbols = new HashSet (); + CollectInternalSymbolsFromAssembly (assemblyPath, assemblySymbols); + + // Write per-assembly cache (sorted for stability). + var sortedAssemblySymbols = assemblySymbols.OrderBy (s => s).ToArray (); + File.WriteAllLines (cacheFile, sortedAssemblySymbols); + + survivingSymbols.UnionWith (assemblySymbols); + } + } + + WriteSymbolsToFile (this, SurvivingNativeSymbolsFile, FilterToDlfcnSymbols (survivingSymbols)); + WriteSymbolsToFile (this, SurvivingClassesFile, FilterToClassSymbols (survivingSymbols)); + } + + public static void WriteSymbolsToFile (XamarinTask task, string file, IEnumerable unsortedSymbols) + { + // Write the combined results only if contents changed (sorted for stability). + var sorted = unsortedSymbols.OrderBy (s => s).ToArray (); + + if (File.Exists (file)) { + var existing = File.ReadAllLines (file); + if (existing.SequenceEqual (sorted)) { + task.Log.LogMessage (MessageImportance.Low, "The file {0} is already up-to-date with {1} symbols", file, sorted.Length); + return; + } + } + + PathUtils.CreateDirectoryForFile (file); + File.WriteAllLines (file, sorted); + task.Log.LogMessage (MessageImportance.Low, "Wrote {0} symbols to {1}", sorted.Length, file); + } + + public static IEnumerable FilterToDlfcnSymbols (IEnumerable symbols) + { + return FilterTo (symbols, "_xamarin_Dlfcn_", "_Native"); + } + + public static IEnumerable FilterToClassSymbols (IEnumerable symbols) + { + return FilterTo (symbols, "_xamarin_Class_GetHandle_", "_Native"); + } + + static IEnumerable FilterTo (IEnumerable symbols, string prefix, string suffix) + { + return symbols + .Where (symbol => symbol.StartsWith (prefix, StringComparison.Ordinal) && symbol.EndsWith (suffix, StringComparison.Ordinal)) + .Select (symbol => symbol.Substring (prefix.Length, symbol.Length - prefix.Length - suffix.Length)); + } + + static void CollectInternalSymbolsFromAssembly (string assemblyPath, HashSet survivingSymbols) + { + using var assembly = AssemblyDefinition.ReadAssembly (assemblyPath, new ReaderParameters { ReadSymbols = false }); + foreach (var module in assembly.Modules) { + if (!module.HasModuleReferences) + continue; + if (!module.ModuleReferences.Any (mr => mr.Name == "__Internal")) + continue; + foreach (var type in module.Types) { + if (!type.HasMethods) + continue; + foreach (var method in type.Methods) { + if (!method.IsPInvokeImpl) + continue; + if (method.PInvokeInfo?.Module?.Name != "__Internal") + continue; + survivingSymbols.Add (Symbol.Prefix + (method.PInvokeInfo.EntryPoint ?? method.Name)); + } + } + } + } + } +} diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/CollectUnresolvedNativeSymbols.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/CollectUnresolvedNativeSymbols.cs new file mode 100644 index 000000000000..dea681874825 --- /dev/null +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/CollectUnresolvedNativeSymbols.cs @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.IO; +using System.Linq; + +using Microsoft.Build.Framework; + +#nullable enable + +namespace Xamarin.MacDev.Tasks { + // See docs/code/native-symbols.md and docs/code/class-handles.md for an overview of native symbol handling. + public class CollectUnresolvedNativeSymbols : XamarinTask { + public ITaskItem? StaticLibrary { get; set; } + + [Required] + public string OutputFile { get; set; } = ""; + + public override bool Execute () + { + if (StaticLibrary is null) { + Log.LogError ("StaticLibrary is required."); + return false; + } + + var path = StaticLibrary.ItemSpec; + if (!File.Exists (path)) { + Log.LogError ("Static library not found: {0}", path); + return false; + } + + var symbols = Xamarin.StaticLibrary.GetUnresolvedSymbols (path); + Log.LogMessage (MessageImportance.Low, "Found {0} unresolved symbols in {1}", symbols.Count, path); + + var lines = symbols.OrderBy (s => s).ToArray (); + if (File.Exists (OutputFile)) { + var existing = File.ReadAllLines (OutputFile); + if (existing.SequenceEqual (lines)) + return !Log.HasLoggedErrors; + } + + var dir = Path.GetDirectoryName (OutputFile); + if (!string.IsNullOrEmpty (dir)) + Directory.CreateDirectory (dir); + File.WriteAllLines (OutputFile, lines); + + return !Log.HasLoggedErrors; + } + } +} diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileAppManifest.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileAppManifest.cs index 4ba5f04dc0de..f9650087d607 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileAppManifest.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileAppManifest.cs @@ -102,7 +102,7 @@ public override bool Execute () plist = new PDictionary (); } else if (File.Exists (appManifest)) { try { - plist = PDictionary.FromFile (appManifest)!; + plist = PDictionary.OpenFile (appManifest); } catch (Exception ex) { LogAppManifestError (MSBStrings.E0010, appManifest, ex.Message); return false; @@ -236,7 +236,7 @@ bool SetMinimumOSVersion (PDictionary plist) if (Platform == ApplePlatform.MacCatalyst && !string.IsNullOrEmpty (SupportedOSPlatformVersion)) { // SupportedOSPlatformVersion is the iOS version for Mac Catalyst. // But we need to store the macOS version in the app manifest, so convert it to the macOS version here. - if (!MacCatalystSupport.TryGetMacOSVersion (Sdks.GetAppleSdk (Platform).GetSdkPath (SdkVersion), SupportedOSPlatformVersion, out var convertedVersion, out var knowniOSVersions)) { + if (!MacCatalystSupport.TryGetMacOSVersion (CurrentSdk.GetSdkPath (SdkVersion), SupportedOSPlatformVersion, out var convertedVersion, out var knowniOSVersions)) { Log.LogError (MSBStrings.E0188, SupportedOSPlatformVersion, string.Join (", ", knowniOSVersions.OrderBy (v => v))); return false; } @@ -250,7 +250,7 @@ bool SetMinimumOSVersion (PDictionary plist) var minimumiOSVersionInManifest = plist.Get (ManifestKeys.MinimumOSVersion)?.Value; if (!string.IsNullOrEmpty (minimumiOSVersionInManifest)) { // Convert to the macOS version - if (!MacCatalystSupport.TryGetMacOSVersion (Sdks.GetAppleSdk (Platform).GetSdkPath (SdkVersion), minimumiOSVersionInManifest!, out var convertedVersion, out var knowniOSVersions)) { + if (!MacCatalystSupport.TryGetMacOSVersion (CurrentSdk.GetSdkPath (SdkVersion), minimumiOSVersionInManifest!, out var convertedVersion, out var knowniOSVersions)) { Log.LogError (MSBStrings.E0188, minimumiOSVersionInManifest, string.Join (", ", knowniOSVersions.OrderBy (v => v))); return false; } @@ -258,11 +258,7 @@ bool SetMinimumOSVersion (PDictionary plist) } } -#if NET - if (string.IsNullOrEmpty (minimumOSVersionInManifest)) { -#else - if (string.IsNullOrEmpty (minimumOSVersionInManifest) || minimumOSVersionInManifest is null) { -#endif + if (StringUtils.IsNullOrEmpty (minimumOSVersionInManifest)) { // Nothing is specified in the Info.plist - use SupportedOSPlatformVersion, and if that's not set, then use the sdkVersion if (!string.IsNullOrEmpty (convertedSupportedOSPlatformVersion)) { minimumOSVersion = convertedSupportedOSPlatformVersion; @@ -313,14 +309,12 @@ bool Compile (PDictionary plist) return false; } - var currentSDK = Sdks.GetAppleSdk (Platform); - sdkVersion = AppleSdkVersion.Parse (DefaultSdkVersion); - if (!currentSDK.SdkIsInstalled (sdkVersion, SdkIsSimulator)) { + if (!CurrentSdk.SdkIsInstalled (sdkVersion, SdkIsSimulator)) { Log.LogError (null, null, null, null, 0, 0, 0, 0, MSBStrings.E0013, Platform, sdkVersion); return false; } - SetXcodeValues (plist, currentSDK); + SetXcodeValues (plist, CurrentSdk); } switch (Platform) { @@ -397,7 +391,7 @@ public static void MergePartialPLists (Task task, PDictionary plist, IEnumerable var overwrite = !string.Equals (template.GetMetadata ("Overwrite"), "false", StringComparison.OrdinalIgnoreCase); try { - partial = PDictionary.FromFile (template.ItemSpec)!; + partial = PDictionary.OpenFile (template.ItemSpec); } catch (Exception ex) { task.Log.LogError (MSBStrings.E0107, template.ItemSpec, ex.Message); continue; @@ -428,7 +422,7 @@ void Validation (PDictionary plist) GetMinimumOSVersion (plist, out var minimumOSVersion); if (minimumOSVersion < new Version (11, 0)) { string miniOSVersion = "?"; - if (MacCatalystSupport.TryGetiOSVersion (Sdks.GetAppleSdk (Platform).GetSdkPath (SdkVersion), minimumOSVersion, out var iOSVersion, out var _)) + if (MacCatalystSupport.TryGetiOSVersion (CurrentSdk.GetSdkPath (SdkVersion), minimumOSVersion, out var iOSVersion, out var _)) miniOSVersion = iOSVersion?.ToString () ?? "?"; LogAppManifestError (MSBStrings.E7099 /* The UIDeviceFamily value '6' requires macOS 11.0. Please set the 'SupportedOSPlatformVersion' in the project file to at least 14.0 (the Mac Catalyst version equivalent of macOS 11.0). The current value is {0} (equivalent to macOS {1}). */, miniOSVersion, minimumOSVersion); } @@ -514,7 +508,7 @@ void SetXcodeValues (PDictionary plist, IAppleSdk currentSDK) SetValueIfNotNull (plist, "DTPlatformName", PlatformUtils.GetTargetPlatform (SdkPlatform, false)); SetValueIfNotNull (plist, "DTPlatformVersion", dtSettings.DTPlatformVersion); SetValueIfNotNull (plist, "DTSDKName", sdkSettings.CanonicalName); - SetValueIfNotNull (plist, "DTXcode", AppleSdkSettings.DTXcode); + SetValueIfNotNull (plist, "DTXcode", GetXcodeLocator ().DTXcode); SetValueIfNotNull (plist, "DTXcodeBuild", dtSettings.DTXcodeBuild); } diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileEntitlements.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileEntitlements.cs index 0db654e7addc..3e2e85074957 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileEntitlements.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileEntitlements.cs @@ -117,7 +117,7 @@ string DefaultEntitlementsPath { return "Entitlements.plist"; } - return Path.Combine (Sdks.GetAppleSdk (TargetFrameworkMoniker).GetSdkPath (SdkVersion, false), "Entitlements.plist"); + return Path.Combine (CurrentSdk.GetSdkPath (SdkVersion, false), "Entitlements.plist"); } } @@ -526,7 +526,7 @@ public override bool Execute () } if (injectDefaultEntitlements) { try { - var defaultEntitlements = PDictionary.FromFile (DefaultEntitlementsPath)!; + var defaultEntitlements = PDictionary.OpenFile (DefaultEntitlementsPath); templates.Add (defaultEntitlements); Log.LogMessage (MessageImportance.Low, $"Loading default entitlements from: {DefaultEntitlementsPath}"); } catch (Exception ex) { @@ -541,7 +541,7 @@ public override bool Execute () Log.LogError (MSBStrings.E0112, Entitlements); return false; } - var projectEntitlements = PDictionary.FromFile (Entitlements)!; + var projectEntitlements = PDictionary.OpenFile (Entitlements); templates.Add (projectEntitlements); Log.LogMessage (MessageImportance.Low, $"Loading user requested entitlements from: {Entitlements}"); } catch (Exception ex) { @@ -609,7 +609,7 @@ bool SaveArchivedExpandedEntitlements (PDictionary archived) var path = Path.Combine (EntitlementBundlePath, "archived-expanded-entitlements.xcent"); if (File.Exists (path)) { - var plist = PDictionary.FromFile (path)!; + var plist = PDictionary.OpenFile (path); var src = archived.ToXml (); var dest = plist.ToXml (); @@ -789,6 +789,7 @@ static Dictionary GetAllEntitlements () new EntitlementData ("com.apple.developer.on-demand-install-capable", iOS, EntitlementType.Boolean ), new EntitlementData ("com.apple.developer.parent-application-identifiers", iOS, EntitlementType.ArrayOfStrings ), new EntitlementData ("com.apple.developer.pass-type-identifiers", iOS, EntitlementType.ArrayOfStrings ), + new EntitlementData ("com.apple.developer.payment-pass-provisioning", iOS, EntitlementType.Boolean ), new EntitlementData ("com.apple.developer.persistent-content-capture", desktop, EntitlementType.Boolean ), new EntitlementData ("com.apple.developer.playable-content", iOS, EntitlementType.Boolean ), new EntitlementData ("com.apple.developer.proximity-reader.identity.display", iOS, EntitlementType.Boolean ), diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileITunesMetadata.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileITunesMetadata.cs index 11f35be9658f..2dd7fc5e2e2d 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileITunesMetadata.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileITunesMetadata.cs @@ -46,7 +46,7 @@ public override bool Execute () var path = ITunesMetadata [0].GetMetadata ("FullPath"); try { - metadata = PDictionary.FromFile (path)!; + metadata = PDictionary.OpenFile (path); } catch (Exception ex) { Log.LogError (null, null, null, path, 0, 0, 0, 0, MSBStrings.E0010, path, ex.Message); return false; diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileNativeCode.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileNativeCode.cs index affd9e1f3fae..f3816db30ddb 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileNativeCode.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileNativeCode.cs @@ -136,6 +136,10 @@ public override bool Execute () arguments.Add ("-o"); arguments.Add (outputFile); + var outputDirectory = Path.GetDirectoryName (outputFile); + if (!string.IsNullOrEmpty (outputDirectory)) + Directory.CreateDirectory (outputDirectory); + arguments.Add ("-c"); arguments.Add (src); diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileProductDefinition.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileProductDefinition.cs index d2990986873c..5107ad17f868 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileProductDefinition.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/CompileProductDefinition.cs @@ -42,7 +42,7 @@ public override bool Execute () if (File.Exists (ProductDefinition)) { try { - plist = PDictionary.FromFile (ProductDefinition)!; + plist = PDictionary.OpenFile (ProductDefinition); } catch (Exception ex) { LogProductDefinitionError (MSBStrings.E0010, ProductDefinition, ex.Message); return false; @@ -95,17 +95,12 @@ public override bool Execute () PDictionary plist; try { - plist = PDictionary.FromFile (AppManifest)!; + plist = PDictionary.OpenFile (AppManifest); } catch (Exception ex) { Log.LogError (null, null, null, AppManifest, 0, 0, 0, 0, MSBStrings.E0010, AppManifest, ex.Message); return null; } - if (plist is null) { - Log.LogError (null, null, null, AppManifest, 0, 0, 0, 0, MSBStrings.E0122, AppManifest); - return null; - } - return plist.GetMinimumSystemVersion (); } diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/ComputeNativeAOTSurvivingNativeSymbols.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/ComputeNativeAOTSurvivingNativeSymbols.cs new file mode 100644 index 000000000000..136e6c321b8f --- /dev/null +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/ComputeNativeAOTSurvivingNativeSymbols.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.IO; +using System.Linq; + +using Microsoft.Build.Framework; + +#nullable enable + +namespace Xamarin.MacDev.Tasks { + /// + /// Takes the list of unresolved native symbols from a NativeAOT static library and computes + /// which inlined dlfcn native symbols survived trimming. The output file has the same format + /// as CollectPostILTrimInformation's surviving symbols file. + /// See docs/code/native-symbols.md and docs/code/class-handles.md for an overview of native symbol handling. + /// + public class ComputeNativeAOTSurvivingNativeSymbols : XamarinTask { + /// + /// The file listing all unresolved native symbols from the NativeAOT static library. + /// + [Required] + public string UnresolvedSymbolsFile { get; set; } = ""; + + /// + /// Output file listing the native symbols that survived NativeAOT trimming. + /// + [Required] + public string SurvivingNativeSymbolsFile { get; set; } = ""; + + /// + /// Output file listing the Class.GetHandle calls that survived trimming. + /// + [Required] + public string SurvivingClassesFile { get; set; } = ""; + + public override bool Execute () + { + var unresolvedSymbols = File.Exists (UnresolvedSymbolsFile) ? File.ReadAllLines (UnresolvedSymbolsFile) : []; + CollectPostILTrimInformation.WriteSymbolsToFile (this, SurvivingNativeSymbolsFile, CollectPostILTrimInformation.FilterToDlfcnSymbols (unresolvedSymbols)); + CollectPostILTrimInformation.WriteSymbolsToFile (this, SurvivingClassesFile, CollectPostILTrimInformation.FilterToClassSymbols (unresolvedSymbols)); + return !Log.HasLoggedErrors; + } + } +} diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateAssetPackManifest.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateAssetPackManifest.cs index 8771e6989522..b7cde30bd592 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateAssetPackManifest.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateAssetPackManifest.cs @@ -70,7 +70,7 @@ public override bool Execute () foreach (var dir in Directory.EnumerateDirectories (onDemandResourcesDir)) { var path = Path.Combine (dir, "Info.plist"); - PDictionary info; + PDictionary? info; if (!File.Exists (path)) continue; @@ -80,11 +80,8 @@ public override bool Execute () updateOnDemandResources = updateOnDemandResources || mtime > onDemandResourcesStamp; updateManifest = updateManifest || mtime > manifestStamp; - try { - info = PDictionary.FromFile (path)!; - } catch { + if (!PDictionary.TryOpenFile (path, out info)) continue; - } var bundleIdentifier = info.GetCFBundleIdentifier (); var primaryContentHash = new PDictionary (); diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateBindingResourcePackage.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateBindingResourcePackage.cs index 17d859c5ae4d..722104a9e119 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateBindingResourcePackage.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateBindingResourcePackage.cs @@ -107,7 +107,7 @@ public override bool Execute () Log.LogMessage (MSBStrings.M0121, bindingResourcePath); Directory.CreateDirectory (bindingResourcePath); foreach (var nativeRef in NativeReferences) { - Xamarin.Bundler.FileCopier.UpdateDirectory (nativeRef.ItemSpec, bindingResourcePath, FileCopierReportErrorCallback, FileCopierLogCallback); + Xamarin.Bundler.FileCopier.UpdateDirectory (this, nativeRef.ItemSpec, bindingResourcePath); var bindingOutputPath = Path.Combine (bindingResourcePath, Path.GetFileName (nativeRef.ItemSpec)); if (Directory.Exists (bindingOutputPath)) { diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateDebugSettings.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateDebugSettings.cs index 021aca10f145..f86f41b3c99d 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateDebugSettings.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateDebugSettings.cs @@ -35,7 +35,7 @@ public override bool Execute () if (File.Exists (path)) { try { - plist = PDictionary.FromFile (path)!; + plist = PDictionary.OpenFile (path); } catch (Exception ex) { Log.LogError (MSBStrings.E0024, Path.GetFileName (AppBundleDir), ex.Message); return false; diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateInstallerPackage.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateInstallerPackage.cs index b69a273f24cf..2c718ebcc6c7 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateInstallerPackage.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/CreateInstallerPackage.cs @@ -62,17 +62,12 @@ public class CreateInstallerPackage : XamarinTask, ICancelableTask { PDictionary plist; try { - plist = PDictionary.FromFile (AppManifest)!; + plist = PDictionary.OpenFile (AppManifest); } catch (Exception ex) { Log.LogError (null, null, null, AppManifest, 0, 0, 0, 0, MSBStrings.E0010, AppManifest, ex.Message); return null; } - if (plist is null) { - Log.LogError (null, null, null, AppManifest, 0, 0, 0, 0, MSBStrings.E0122, AppManifest); - return null; - } - return plist.GetCFBundleShortVersionString (); } diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/DetectSdkLocation.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/DetectSdkLocation.cs index 1f393504e6a8..f06f132d6a7b 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/DetectSdkLocation.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/DetectSdkLocation.cs @@ -29,6 +29,7 @@ public string SdkRoot { get; set; } = ""; + // this is input too (the variable 'XcodeLocation') [Output] public new string SdkDevPath { get => base.SdkDevPath; @@ -59,12 +60,6 @@ public string XcodeVersion { #endregion Outputs - protected IAppleSdk CurrentSdk { - get { - return Sdks.GetAppleSdk (Platform); - } - } - IAppleSdkVersion GetDefaultSdkVersion () { switch (Platform) { @@ -145,33 +140,40 @@ bool ExecuteImpl () return ExecuteRemotely (); } - AppleSdkSettings.Init (); - - if (EnsureAppleSdkRoot ()) - EnsureSdkPath (); - EnsureXamarinSdkRoot (); + var isNet11OrNewer = TargetFramework.Version.Major >= 11; + var appleSdkSettings = GetXcodeLocator (initialDiscovery: true, (locator) => { + locator.SupportEnvironmentVariableLookup = !isNet11OrNewer; + locator.SupportSettingsFileLookup = !isNet11OrNewer; + }); + SetXcodeLocator (appleSdkSettings); + SdkDevPath = appleSdkSettings.DeveloperRoot; + XcodeVersion = appleSdkSettings.XcodeVersion.ToString (); + + if (appleSdkSettings.SystemHasEnvironmentVariable) { + if (isNet11OrNewer) { + Log.LogWarning (MSBStrings.W7172 /* The environment variable '{0}' is deprecated, and will be ignored. Please set use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. */, XcodeLocator.EnvironmentVariableName); + } else { + Log.LogWarning (MSBStrings.W7171 /* The environment variable '{0}' is deprecated, and will be ignored in .NET 11+. Please set use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. */, XcodeLocator.EnvironmentVariableName); + } + } + foreach (var file in appleSdkSettings.SystemExistingSettingsFiles) { + if (isNet11OrNewer) { + Log.LogWarning (MSBStrings.W7174 /* The settings file '{0}' is deprecated, and will be ignored. Please set use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. */, file); + } else { + Log.LogWarning (MSBStrings.W7173 /* The settings file '{0}' is deprecated, and will be ignored in .NET 11+. Please set use the 'DEVELOPER_DIR' environment variable or the 'XcodeLocation' MSBuild property to choose which Xcode to use. */, file); + } + } - XcodeVersion = AppleSdkSettings.XcodeVersion.ToString (); + if (Log.HasLoggedErrors) + return false; - return !Log.HasLoggedErrors; - } + Log.LogMessage (MessageImportance.Low, "DeveloperRoot: {0}", CurrentSdk.DeveloperRoot); + Log.LogMessage (MessageImportance.Low, "GetPlatformPath: {0}", CurrentSdk.GetPlatformPath (SdkIsSimulator)); - protected bool EnsureAppleSdkRoot () - { - var currentSdk = CurrentSdk; - if (!currentSdk.IsInstalled) { - Log.LogError (MSBStrings.E0044v2 /* Could not find a valid Xcode app bundle at '{0}'. Please verify that 'xcode-select -p' points to your Xcode installation. For more information see https://aka.ms/macios-missing-xcode. */, AppleSdkSettings.InvalidDeveloperRoot); - return false; - } - Log.LogMessage (MessageImportance.Low, "DeveloperRoot: {0}", currentSdk.DeveloperRoot); - Log.LogMessage (MessageImportance.Low, "GetPlatformPath: {0}", currentSdk.GetPlatformPath (SdkIsSimulator)); + EnsureSdkPath (); + EnsureXamarinSdkRoot (); - SdkDevPath = currentSdk.DeveloperRoot; - if (string.IsNullOrEmpty (SdkDevPath)) { - Log.LogError (MSBStrings.E0086 /* Could not find a valid Xcode developer path */); - return false; - } - return true; + return !Log.HasLoggedErrors; } protected string? DirExists (string checkingFor, params string [] paths) diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/DetectSigningIdentity.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/DetectSigningIdentity.cs index 96bd8d1455b3..8718934d6918 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/DetectSigningIdentity.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/DetectSigningIdentity.cs @@ -29,12 +29,6 @@ public class DetectSigningIdentity : XamarinTask, ITaskCallback, ICancelableTask static readonly string [] macDirectDistributionPrefixes = { "Developer ID Application" }; static readonly string [] macDevelopmentPrefixes = { "Mac Developer", "Apple Development" }; - protected string DeveloperRoot { - get { - return Sdks.GetAppleSdk (TargetFrameworkMoniker).DeveloperRoot; - } - } - protected string [] DevelopmentPrefixes { get { switch (Platform) { @@ -186,7 +180,7 @@ public bool HasEntitlements { hasEntitlements = false; } else { // Check the file to see if there are any entitlements inside - var entitlements = PDictionary.FromFile (CodesignEntitlements!.ItemSpec)!; + var entitlements = PDictionary.OpenFile (CodesignEntitlements!.ItemSpec); hasEntitlements = entitlements.Count > 0; } } @@ -583,7 +577,7 @@ bool ExecuteImpl () else if (ProvisioningProfile == AutomaticAdHocProvision) type = MobileProvisionDistributionType.AdHoc; - DetectedCodesignAllocate = Path.Combine (DeveloperRoot, "Toolchains", "XcodeDefault.xctoolchain", "usr", "bin", "codesign_allocate"); + DetectedCodesignAllocate = Path.Combine (CurrentSdk.DeveloperRoot, "Toolchains", "XcodeDefault.xctoolchain", "usr", "bin", "codesign_allocate"); DetectedDistributionType = type.ToString (); identity.BundleId = BundleIdentifier; diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/FilterStaticFrameworks.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/FilterStaticFrameworks.cs index 2bc6874fd2e6..5689a1614fcb 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/FilterStaticFrameworks.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/FilterStaticFrameworks.cs @@ -44,17 +44,14 @@ static string GetFrameworkExecutablePath (string frameworkPath, ApplePlatform pl var infoPlistPath = GetFrameworkInfoPlistPath (frameworkPath, platform); if (File.Exists (infoPlistPath)) { - try { - var plist = PDictionary.FromFile (infoPlistPath); - if (plist is not null) { - var bundleExecutable = plist.GetCFBundleExecutable (); - if (!string.IsNullOrEmpty (bundleExecutable)) { - return Path.Combine (frameworkPath, bundleExecutable); - } + if (PDictionary.TryOpenFile (infoPlistPath, out var plist)) { + var bundleExecutable = plist.GetCFBundleExecutable (); + if (!string.IsNullOrEmpty (bundleExecutable)) { + return Path.Combine (frameworkPath, bundleExecutable); } - } catch (Exception ex) { + } else { // Log exceptions from malformed plist files and fall back to default behavior - log?.LogMessage (MessageImportance.Low, $"Failed to parse Info.plist for framework '{frameworkPath}': {ex.Message}"); + log?.LogMessage (MessageImportance.Low, $"Failed to parse Info.plist for framework '{frameworkPath}'"); } } diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/GetAvailableDevices.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/GetAvailableDevices.cs index eda5380ab2d9..8046bf247001 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/GetAvailableDevices.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/GetAvailableDevices.cs @@ -2,13 +2,13 @@ using System.IO; using System.Collections.Generic; using System.Linq; -using System.Text.Json; using System.Threading; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Xamarin.Localization.MSBuild; +using Xamarin.MacDev.Models; using Xamarin.Messaging.Build.Client; using Xamarin.Utils; @@ -60,7 +60,7 @@ public override bool Execute () // filter to values we find in the app manifest, if it exists if (File.Exists (AppBundleManifestPath)) { - var appManifest = PDictionary.FromFile (AppBundleManifestPath)!; + var appManifest = PDictionary.OpenFile (AppBundleManifestPath); var uiDeviceFamily = appManifest.GetUIDeviceFamily (); // an iPhone app can run on an iPad, but an iPad app cannot run on an iPhone @@ -161,265 +161,218 @@ protected virtual async System.Threading.Tasks.Task ExecuteCtlAsync (par } } - async System.Threading.Tasks.Task ExecuteCtlToJsonAsync (params string [] args) - { - var json = await ExecuteCtlAsync (args); - var options = new JsonDocumentOptions { - AllowTrailingCommas = true, - CommentHandling = JsonCommentHandling.Skip, - }; - return JsonDocument.Parse (string.IsNullOrEmpty (json) ? "{}" : json, options); - } - async System.Threading.Tasks.Task> RunDeviceCtlAsync () { - var doc = await ExecuteCtlToJsonAsync ("devicectl", "list", "devices"); - var array = doc.FindProperty ("result", "devices")?.EnumerateIfArray (); + var json = await ExecuteCtlAsync ("devicectl", "list", "devices"); var rv = new List (); - if (array is not null) { - foreach (var device in array) { - var name = device.GetStringPropertyOrEmpty ("deviceProperties", "name"); - var udid = device.GetStringPropertyOrEmpty ("hardwareProperties", "udid"); - var identifier = device.GetStringPropertyOrEmpty ("identifier"); - - var deviceProperties = device.GetNullableProperty ("deviceProperties"); - var buildVersion = deviceProperties.GetStringPropertyOrEmpty ("osBuildUpdate"); - var productVersion = deviceProperties.GetStringPropertyOrEmpty ("osVersionNumber"); - - var hardwareProperties = device.GetNullableProperty ("hardwareProperties"); - var deviceClass = hardwareProperties.GetStringPropertyOrEmpty ("deviceType"); - var hardwareModel = hardwareProperties.GetStringPropertyOrEmpty ("hardwareModel"); - var hardwarePlatform = hardwareProperties.GetStringPropertyOrEmpty ("platform"); - var productType = hardwareProperties.GetStringPropertyOrEmpty ("productType"); - var serialNumber = hardwareProperties.GetStringPropertyOrEmpty ("serialNumber"); - var uniqueChipID = hardwareProperties.GetUInt64Property ("ecid"); - - var cpuType = hardwareProperties.GetNullableProperty ("cpuType"); - var cpuArchitecture = cpuType.GetStringPropertyOrEmpty ("name"); - - var connectionProperties = device.GetNullableProperty ("connectionProperties"); - var transportType = connectionProperties.GetStringPropertyOrEmpty ("transportType"); - var pairingState = connectionProperties.GetStringPropertyOrEmpty ("pairingState"); - - if (string.IsNullOrEmpty (udid)) - udid = identifier; - - if (string.IsNullOrEmpty (udid)) - udid = $""; - - var item = new TaskItem (udid); - item.SetMetadata ("Name", name); - item.SetMetadata ("BuildVersion", buildVersion); - item.SetMetadata ("DeviceClass", deviceClass); - item.SetMetadata ("HardwareModel", hardwareModel); - item.SetMetadata ("Platform", hardwarePlatform); - item.SetMetadata ("ProductType", productType); - item.SetMetadata ("SerialNumber", serialNumber); - item.SetMetadata ("UniqueChipID", uniqueChipID?.ToString () ?? string.Empty); - item.SetMetadata ("CPUArchitecture", cpuArchitecture); - item.SetMetadata ("TransportType", transportType); - item.SetMetadata ("PairingState", pairingState); - - // we provide the following metadata for both simulator and device - item.SetMetadata ("Description", name); - item.SetMetadata ("Type", "Device"); - item.SetMetadata ("OSVersion", productVersion); - item.SetMetadata ("UDID", udid); - - // compute the platform and runtime identifier - var runtimeIdentifier = ""; - ApplePlatform platform; - IPhoneDeviceType deviceType; - var discardedReason = ""; - switch (deviceClass.ToLowerInvariant ()) { - case "iphone": - case "ipod": - runtimeIdentifier += "ios-"; - platform = ApplePlatform.iOS; - deviceType = IPhoneDeviceType.IPhone; - break; - case "ipad": - runtimeIdentifier += "ios-"; - platform = ApplePlatform.iOS; - deviceType = IPhoneDeviceType.IPad; - break; - case "appletv": - runtimeIdentifier += "tvos-"; - platform = ApplePlatform.TVOS; - deviceType = IPhoneDeviceType.TV; + + // Use shared parser from Xamarin.MacDev for devicectl JSON extraction + var parsedDevices = DeviceCtlOutputParser.ParseDevices (json); + + foreach (var device in parsedDevices) { + var udid = device.Udid; + + if (string.IsNullOrEmpty (udid)) + udid = $""; + + var item = new TaskItem (udid); + item.SetMetadata ("Name", device.Name); + item.SetMetadata ("BuildVersion", device.BuildVersion); + item.SetMetadata ("DeviceClass", device.DeviceClass); + item.SetMetadata ("HardwareModel", device.HardwareModel); + item.SetMetadata ("Platform", device.Platform); + item.SetMetadata ("ProductType", device.ProductType); + item.SetMetadata ("SerialNumber", device.SerialNumber); + item.SetMetadata ("UniqueChipID", device.UniqueChipID?.ToString () ?? string.Empty); + item.SetMetadata ("CPUArchitecture", device.CpuArchitecture); + item.SetMetadata ("TransportType", device.TransportType); + item.SetMetadata ("PairingState", device.PairingState); + + // we provide the following metadata for both simulator and device + item.SetMetadata ("Description", device.Name); + item.SetMetadata ("Type", "Device"); + item.SetMetadata ("OSVersion", device.OSVersion); + item.SetMetadata ("UDID", udid); + + // compute the platform and runtime identifier + var runtimeIdentifier = ""; + ApplePlatform platform; + IPhoneDeviceType deviceType; + var discardedReason = ""; + switch (device.DeviceClass.ToLowerInvariant ()) { + case "iphone": + case "ipod": + runtimeIdentifier += "ios-"; + platform = ApplePlatform.iOS; + deviceType = IPhoneDeviceType.IPhone; + break; + case "ipad": + runtimeIdentifier += "ios-"; + platform = ApplePlatform.iOS; + deviceType = IPhoneDeviceType.IPad; + break; + case "appletv": + runtimeIdentifier += "tvos-"; + platform = ApplePlatform.TVOS; + deviceType = IPhoneDeviceType.TV; + break; + case "applewatch": + case "visionos": + default: + platform = ApplePlatform.None; + deviceType = IPhoneDeviceType.NotSet; + discardedReason = $"'{device.DeviceClass}' devices are not supported"; + break; + } + + if (string.IsNullOrEmpty (discardedReason)) { + switch (device.CpuArchitecture.ToLowerInvariant ()) { + case "arm64": + case "arm64e": + // arm64 and arm64e are both arm64 for our purposes + runtimeIdentifier += "arm64"; break; - case "applewatch": - case "visionos": default: - platform = ApplePlatform.None; - deviceType = IPhoneDeviceType.NotSet; - discardedReason = $"'{deviceClass}' devices are not supported"; + discardedReason = $"Unknown CPU architecture '{device.CpuArchitecture}'"; break; } + } - if (string.IsNullOrEmpty (discardedReason)) { - switch (cpuArchitecture.ToLowerInvariant ()) { - case "arm64": - case "arm64e": - // arm64 and arm64e are both arm64 for our purposes - runtimeIdentifier += "arm64"; - break; - default: - discardedReason = $"Unknown CPU architecture '{cpuArchitecture}'"; - break; - } - } - - Version.TryParse (productVersion, out var minimumOSVersion); - var maximumOSVersion = new Version (65535, 255, 255); + Version.TryParse (device.OSVersion, out var minimumOSVersion); + var maximumOSVersion = new Version (65535, 255, 255); - rv.Add (new DeviceInfo (item, [runtimeIdentifier], platform, deviceType, minimumOSVersion ?? new Version (0, 0), maximumOSVersion, discardedReason)); - } + rv.Add (new DeviceInfo (item, [runtimeIdentifier], platform, deviceType, minimumOSVersion ?? new Version (0, 0), maximumOSVersion, discardedReason)); } return rv; } async System.Threading.Tasks.Task> RunSimCtlAsync () { - var doc = await ExecuteCtlToJsonAsync ("simctl", "list", "--json"); + var json = await ExecuteCtlAsync ("simctl", "list", "--json"); var rv = new List (); - var runtimes = new Dictionary (); - if (doc.TryGetProperty ("runtimes", out var runtimesElement)) { - foreach (var runtime in runtimesElement.EnumerateIfArray ()) { - var name = runtime.GetStringProperty ("identifier") ?? string.Empty; - runtimes [name] = runtime; - } - } - - var deviceTypes = new Dictionary (); - if (doc.TryGetProperty ("devicetypes", out var deviceTypesElement)) { - foreach (var deviceType in deviceTypesElement.EnumerateIfArray ()) { - var name = deviceType.GetStringProperty ("identifier") ?? string.Empty; - deviceTypes [name] = deviceType; - } - } + // Use shared parser from Xamarin.MacDev for device and runtime extraction + var parsedDevices = SimctlOutputParser.ParseDevices (json); + var parsedRuntimes = SimctlOutputParser.ParseRuntimes (json); + + // Index runtimes by identifier for SupportedArchitectures lookup + var runtimesByIdentifier = new Dictionary (); + foreach (var rt in parsedRuntimes) + runtimesByIdentifier [rt.Identifier] = rt; + + // Use shared parser for devicetypes (productFamily, min/maxRuntime) + var parsedDeviceTypes = SimctlOutputParser.ParseDeviceTypes (json); + var deviceTypes = new Dictionary (); + foreach (var dt in parsedDeviceTypes) + deviceTypes [dt.Identifier] = dt; + + foreach (var device in parsedDevices) { + var hasRuntime = runtimesByIdentifier.TryGetValue (device.RuntimeIdentifier, out var runtimeInfo); + var runtimePlatform = hasRuntime ? runtimeInfo!.Platform : string.Empty; + var runtimeVersion = hasRuntime ? runtimeInfo!.Version : device.OSVersion; + var supportedArchitectures = hasRuntime ? runtimeInfo!.SupportedArchitectures : new List (); + + var item = new TaskItem (device.Udid); + item.SetMetadata ("Runtime", device.RuntimeIdentifier); + item.SetMetadata ("IsAvailable", device.IsAvailable.ToString ()); + item.SetMetadata ("AvailabilityError", device.AvailabilityError); + item.SetMetadata ("DeviceTypeIdentifier", device.DeviceTypeIdentifier); + item.SetMetadata ("State", device.State); + item.SetMetadata ("Name", device.Name); + item.SetMetadata ("SupportedArchitectures", string.Join (",", supportedArchitectures)); + + // we provide the following metadata for both simulator and device + item.SetMetadata ("Description", device.Name); + item.SetMetadata ("Type", "Simulator"); + item.SetMetadata ("OSVersion", runtimeVersion); + item.SetMetadata ("UDID", device.Udid); + + var discardedReason = ""; + var runtimeIdentifier = ""; + var runtimeIdentifiers = new List (); + if (device.IsAvailable) { + switch (runtimePlatform.ToLowerInvariant ()) { + case "ios": + runtimeIdentifier += "iossimulator-"; + break; + case "tvos": + runtimeIdentifier += "tvossimulator-"; + break; + default: + discardedReason = $"'{runtimePlatform}' simulators are not supported"; + break; + } - if (doc.TryGetProperty ("devices", out var devicesElement)) { - foreach (var runtime in devicesElement.EnumerateObject ()) { - var runtimeName = runtime.Name; - var hasRuntime = runtimes.TryGetValue (runtimeName, out var runtimeElement); - var runtimePlatform = hasRuntime ? runtimeElement.GetStringProperty ("platform") ?? string.Empty : string.Empty; - var runtimeVersion = hasRuntime ? runtimeElement.GetStringProperty ("version") ?? string.Empty : string.Empty; - var supportedArchitectures = hasRuntime ? runtimeElement.GetProperty ("supportedArchitectures").EnumerateIfArray ().Select (v => v.GetString () ?? "") : Enumerable.Empty (); - foreach (var element in runtime.Value.EnumerateIfArray ()) { - var udid = element.GetStringProperty ("udid") ?? string.Empty; - var isAvailable = element.GetBooleanProperty ("isAvailable") ?? false; - var availabilityError = element.GetStringProperty ("availabilityError") ?? string.Empty; - var deviceTypeIdentifier = element.GetStringProperty ("deviceTypeIdentifier") ?? string.Empty; - var state = element.GetStringProperty ("state") ?? string.Empty; - var name = element.GetStringProperty ("name") ?? string.Empty; - - var item = new TaskItem (udid); - item.SetMetadata ("Runtime", runtimeName); - item.SetMetadata ("IsAvailable", isAvailable.ToString ()); - item.SetMetadata ("AvailabilityError", availabilityError); - item.SetMetadata ("DeviceTypeIdentifier", deviceTypeIdentifier); - item.SetMetadata ("State", state); - item.SetMetadata ("Name", name); - item.SetMetadata ("SupportedArchitectures", string.Join (",", supportedArchitectures)); - - // we provide the following metadata for both simulator and device - item.SetMetadata ("Description", name); - item.SetMetadata ("Type", "Simulator"); - item.SetMetadata ("OSVersion", runtimeVersion); - item.SetMetadata ("UDID", udid); - - var discardedReason = ""; - var runtimeIdentifier = ""; - var runtimeIdentifiers = new List (); - if (isAvailable) { - switch (runtimePlatform.ToLowerInvariant ()) { - case "ios": - runtimeIdentifier += "iossimulator-"; + // pick the first architecture as the simulator architecture + if (string.IsNullOrEmpty (discardedReason)) { + foreach (var arch in supportedArchitectures) { + switch (arch.ToLowerInvariant ()) { + case "x64": + case "x86_64": + runtimeIdentifiers.Add (runtimeIdentifier + "x64"); break; - case "tvos": - runtimeIdentifier += "tvossimulator-"; + case "arm64": + runtimeIdentifiers.Add (runtimeIdentifier + "arm64"); + if (!CanRunArm64) + discardedReason = $"Can't run an arm64 simulator on an x86_64 macOS desktop."; break; default: - discardedReason = $"'{runtimePlatform}' simulators are not supported"; + discardedReason = $"Unknown CPU architecture '{arch}'"; break; } - - // pick the first architecture as the simulator architecture - if (string.IsNullOrEmpty (discardedReason)) { - foreach (var arch in supportedArchitectures) { - switch (arch.ToLowerInvariant ()) { - case "x64": - case "x86_64": - runtimeIdentifiers.Add (runtimeIdentifier + "x64"); - break; - case "arm64": - runtimeIdentifiers.Add (runtimeIdentifier + "arm64"); - if (!CanRunArm64) - discardedReason = $"Can't run an arm64 simulator on an x86_64 macOS desktop."; - break; - default: - discardedReason = $"Unknown CPU architecture '{arch}'"; - break; - } - } - } - } else { - discardedReason = $"Device is not available: {availabilityError}"; } + } + } else { + discardedReason = $"Device is not available: {device.AvailabilityError}"; + } - var platformName = runtimeName.Replace ("com.apple.CoreSimulator.SimRuntime.", "").Split ('-') [0]; - var platform = ApplePlatform.None; - if (string.IsNullOrEmpty (discardedReason)) { - switch (platformName.ToLowerInvariant ()) { - case "ios": - platform = ApplePlatform.iOS; - break; - case "tvos": - platform = ApplePlatform.TVOS; - break; - case "watchos": - case "visionos": - default: - discardedReason = $"'{platformName}' simulators are not supported"; - break; - } - } - var deviceType = IPhoneDeviceType.NotSet; - var minimumOSVersion = new Version (0, 0); - var maximumOSVersion = new Version (65535, 255, 255); - if (string.IsNullOrEmpty (discardedReason)) { - if (deviceTypes.TryGetValue (deviceTypeIdentifier, out var deviceTypeElement)) { - var productFamily = deviceTypeElement.GetStringProperty ("productFamily") ?? string.Empty; - switch (productFamily.ToLowerInvariant ()) { - case "iphone": - case "ipod": - deviceType = IPhoneDeviceType.IPhone; - break; - case "ipad": - deviceType = IPhoneDeviceType.IPad; - break; - case "appletv": - case "apple tv": - deviceType = IPhoneDeviceType.TV; - break; - default: - discardedReason = $"Unknown product family '{productFamily}'"; - break; - } - if (Version.TryParse (deviceTypeElement.GetStringProperty ("minRuntimeVersionString"), out var parsedMinimumOSVersion)) - minimumOSVersion = parsedMinimumOSVersion; - if (Version.TryParse (deviceTypeElement.GetStringProperty ("maxRuntimeVersionString"), out var parsedMaximumOSVersion)) - maximumOSVersion = parsedMaximumOSVersion; - } else { - discardedReason = $"Unknown device type identifier '{deviceTypeIdentifier}'"; - } + var platform = ApplePlatform.None; + if (string.IsNullOrEmpty (discardedReason)) { + switch (device.Platform.ToLowerInvariant ()) { + case "ios": + platform = ApplePlatform.iOS; + break; + case "tvos": + platform = ApplePlatform.TVOS; + break; + case "watchos": + case "visionos": + default: + discardedReason = $"'{device.Platform}' simulators are not supported"; + break; + } + } + var deviceType = IPhoneDeviceType.NotSet; + var minimumOSVersion = new Version (0, 0); + var maximumOSVersion = new Version (65535, 255, 255); + if (string.IsNullOrEmpty (discardedReason)) { + if (deviceTypes.TryGetValue (device.DeviceTypeIdentifier, out var deviceTypeInfo)) { + switch (deviceTypeInfo.ProductFamily.ToLowerInvariant ()) { + case "iphone": + case "ipod": + deviceType = IPhoneDeviceType.IPhone; + break; + case "ipad": + deviceType = IPhoneDeviceType.IPad; + break; + case "appletv": + case "apple tv": + deviceType = IPhoneDeviceType.TV; + break; + default: + discardedReason = $"Unknown product family '{deviceTypeInfo.ProductFamily}'"; + break; } - - rv.Add (new DeviceInfo (item, runtimeIdentifiers, platform, deviceType, minimumOSVersion, maximumOSVersion, discardedReason)); + if (Version.TryParse (deviceTypeInfo.MinRuntimeVersionString, out var parsedMinimumOSVersion)) + minimumOSVersion = parsedMinimumOSVersion; + if (Version.TryParse (deviceTypeInfo.MaxRuntimeVersionString, out var parsedMaximumOSVersion)) + maximumOSVersion = parsedMaximumOSVersion; + } else { + discardedReason = $"Unknown device type identifier '{device.DeviceTypeIdentifier}'"; } } + + rv.Add (new DeviceInfo (item, runtimeIdentifiers, platform, deviceType, minimumOSVersion, maximumOSVersion, discardedReason)); } return rv; } diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/GetMlaunchArguments.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/GetMlaunchArguments.cs index 3b0f1b6115b6..73b687c6e728 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/GetMlaunchArguments.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/GetMlaunchArguments.cs @@ -53,7 +53,7 @@ public IPhoneDeviceType DeviceType { switch (Platform) { case ApplePlatform.iOS: case ApplePlatform.TVOS: - var plist = PDictionary.FromFile (AppManifestPath); + var plist = PDictionary.OpenFile (AppManifestPath); return plist.GetUIDeviceFamily (); default: throw new InvalidOperationException (string.Format (MSBStrings.InvalidPlatform, Platform)); diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/GetNativeExecutableName.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/GetNativeExecutableName.cs index 7237af4ec240..77a388d2b48a 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/GetNativeExecutableName.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/GetNativeExecutableName.cs @@ -33,7 +33,7 @@ public override bool Execute () PDictionary plist; try { - plist = PDictionary.FromFile (AppManifest)!; + plist = PDictionary.OpenFile (AppManifest); } catch (Exception ex) { Log.LogError (MSBStrings.E0055, ex.Message); return false; diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/GetPropertyListValue.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/GetPropertyListValue.cs index 95294ffee6c8..7255100d2d98 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/GetPropertyListValue.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/GetPropertyListValue.cs @@ -43,7 +43,7 @@ public override bool Execute () } try { - value = dict = PDictionary.FromFile (PropertyListFile); + value = dict = PDictionary.OpenFile (PropertyListFile); } catch (Exception ex) { Log.LogError (MSBStrings.E0010, PropertyListFile, ex.Message); return false; diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/IBTool.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/IBTool.cs index d8e349b2cdcf..9c7a1fb905ea 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/IBTool.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/IBTool.cs @@ -157,13 +157,11 @@ static bool LogExists (string path) if (!File.Exists (path)) return false; - try { - PDictionary.FromFile (path); + if (PDictionary.TryOpenFile (path, out _)) return true; - } catch { - File.Delete (path); - return false; - } + + File.Delete (path); + return false; } static bool InterfaceDefinitionChanged (ITaskItem interfaceDefinition, ITaskItem log) @@ -226,7 +224,7 @@ bool CompileInterfaceDefinitions (IEnumerable interfaceDefinitions, s } try { - var dict = PDictionary.FromFile (manifest.ItemSpec)!; + var dict = PDictionary.OpenFile (manifest.ItemSpec); LogWarningsAndErrors (dict, item); } catch (Exception ex) { diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/LinkNativeCode.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/LinkNativeCode.cs index fb7a540cd330..d914b72c8352 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/LinkNativeCode.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/LinkNativeCode.cs @@ -287,17 +287,14 @@ string ConvertEntitlementsToDerEntitlements (string entitlements) static bool EntitlementsRequireLinkerFlags (string path) { - try { - var plist = PDictionary.FromFile (path)!; - - // FIXME: most keys do not require linking in the entitlements file, so we - // could probably add some smarter logic here to iterate over all of the - // keys in order to determine whether or not we really need to link with - // the entitlements or not. - return plist.Count != 0; - } catch { + if (!PDictionary.TryOpenFile (path, out var plist)) return false; - } + + // FIXME: most keys do not require linking in the entitlements file, so we + // could probably add some smarter logic here to iterate over all of the + // keys in order to determine whether or not we really need to link with + // the entitlements or not. + return plist.Count != 0; } // We should avoid copying files from the output path because those already exist on the Mac diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/MergeAppBundles.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/MergeAppBundles.cs index dd9f8bf3ad13..591180e66f26 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/MergeAppBundles.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/MergeAppBundles.cs @@ -215,7 +215,7 @@ public void CopyTo (string outputDirectory, string? subDirectory = null) } } else { Directory.CreateDirectory (Path.GetDirectoryName (outputFile)!); - if (!FileCopier.IsUptodate (FullPath, outputFile, Task.FileCopierReportErrorCallback, Task.FileCopierLogCallback)) + if (!FileCopier.IsUptodate (Task, FullPath, outputFile)) File.Copy (FullPath, outputFile, true); } @@ -246,7 +246,7 @@ public override bool Execute () sourceDirectory += Path.DirectorySeparatorChar; Log.LogMessage (MessageImportance.Low, $"Copying the single input directory {sourceDirectory} to {targetDirectory}"); - FileCopier.UpdateDirectory (sourceDirectory, targetDirectory, FileCopierReportErrorCallback, FileCopierLogCallback); + FileCopier.UpdateDirectory (this, sourceDirectory, targetDirectory); return !Log.HasLoggedErrors; } @@ -428,7 +428,7 @@ void MergeMachOFiles (string output, IList input) var sourceFiles = input.Select (v => v.FullPath).ToArray (); - if (FileCopier.IsUptodate (sourceFiles, new string [] { output }, FileCopierReportErrorCallback, FileCopierLogCallback)) + if (FileCopier.IsUptodate (this, sourceFiles, new string [] { output })) return; Log.LogMessage (MessageImportance.Low, $"Lipoing '{input [0].RelativePath}' for the merged app bundle from the following sources:\n\t{string.Join ("\n\t", input.Select (v => v.FullPath))}"); diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/ParseBundlerArguments.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/ParseBundlerArguments.cs index 3da5e058b86a..3f2ba75108b7 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/ParseBundlerArguments.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/ParseBundlerArguments.cs @@ -64,7 +64,7 @@ public class ParseBundlerArguments : XamarinTask { public string? SkipMarkingNSObjectsInUserAssemblies { get; set; } [Output] - public string? Verbosity { get; set; } + public string? BundlerVerbosity { get; set; } [Output] public string? Warn { get; set; } @@ -307,7 +307,7 @@ public override bool Execute () } if (verbosity.HasValue) - Verbosity = verbosity.Value.ToString (); + BundlerVerbosity = verbosity.Value.ToString (); } return !Log.HasLoggedErrors; diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs new file mode 100644 index 000000000000..bb65800df942 --- /dev/null +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/PostTrimmingProcessing.cs @@ -0,0 +1,263 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +using Microsoft.Build.Framework; + +using Xamarin.Bundler; +using Xamarin.Utils; + +#nullable enable + +namespace Xamarin.MacDev.Tasks { + /// + /// Performs post-trimming processing, generating native code only for symbols that survived trimming. + /// See docs/code/native-symbols.md and docs/code/class-handles.md for an overview of native symbol handling. + /// + public class PostTrimmingProcessing : XamarinTask { + [Required] + public string Architecture { get; set; } = ""; + + [Required] + public string OutputDirectory { get; set; } = ""; + + public ITaskItem [] ReferenceNativeSymbol { get; set; } = []; + + /// + /// Files listing calls to Class.GetHandle that survived trimming. Each file contains one symbol name per line. + /// These can come from either ILTrim (CollectPostILTrimInformation) or NativeAOT + /// (ComputeNativeAOTSurvivingNativeSymbols). + /// + public ITaskItem [] SurvivingClassesFiles { get; set; } = []; + + /// + /// Files listing native symbols that survived trimming. Each file contains one symbol name per line. + /// These can come from either ILTrim (CollectPostILTrimInformation) or NativeAOT + /// (ComputeNativeAOTSurvivingNativeSymbols). + /// + public ITaskItem [] SurvivingNativeSymbolsFiles { get; set; } = []; + + // Type map + public string TypeMapFilePath { get; set; } = ""; + + /// + /// Output native source files to be compiled and linked. + /// + [Output] + public ITaskItem []? NativeSourceFiles { get; set; } + + HashSet? ignoredSymbols; + + HashSet IgnoredSymbols { + get { + if (ignoredSymbols is null) { + ignoredSymbols = new HashSet (); + foreach (var rns in ReferenceNativeSymbol) { + var nativeSymbol = rns.ItemSpec; + var symbolMode = rns.GetMetadata ("SymbolMode"); + if (!string.Equals (symbolMode, "Ignore", StringComparison.OrdinalIgnoreCase)) + continue; + var symbolType = rns.GetMetadata ("SymbolType").ToLowerInvariant (); + switch (symbolType) { + case "objectivecclass": + nativeSymbol = Symbol.ObjectiveCPrefix + nativeSymbol; + break; + case "function": + case "field": + break; + default: + Log.LogMessage (MessageImportance.Low, "Ignoring symbol '{0}' with unknown SymbolType '{1}'", nativeSymbol, symbolType); + continue; + } + ignoredSymbols.Add (nativeSymbol); + } + } + return ignoredSymbols; + } + } + + public override bool Execute () + { + var nativeSourceFiles = new List (); + + Directory.CreateDirectory (OutputDirectory); + GenerateInlinedDlfcnNativeCode (nativeSourceFiles); + GenerateInlinedClassGetHandleNativeCode (nativeSourceFiles); + + NativeSourceFiles = nativeSourceFiles.Select (path => { + var item = new Microsoft.Build.Utilities.TaskItem (path); + item.SetMetadata ("Arch", Architecture.ToLowerInvariant ()); + return item; + }).ToArray (); + + return !Log.HasLoggedErrors; + } + + static HashSet ReadUniqueLinesFromFiles (IEnumerable files) + { + var lines = new HashSet (); + foreach (var file in files) { + var path = file.ItemSpec; + if (!File.Exists (path)) + continue; + lines.UnionWith (File.ReadAllLines (path)); + } + return lines; + } + + List FilterOutIgnoredSymbols (HashSet survivingSymbols, bool filterObjectiveCClasses) + { + var rv = new HashSet (survivingSymbols); + + foreach (var rns in ReferenceNativeSymbol) { + var nativeSymbol = rns.ItemSpec; + var symbolMode = rns.GetMetadata ("SymbolMode"); + if (!string.Equals (symbolMode, "Ignore", StringComparison.OrdinalIgnoreCase)) + continue; + + var symbolType = rns.GetMetadata ("SymbolType").ToLowerInvariant (); + switch (symbolType) { + case "objectivecclass": + if (filterObjectiveCClasses && rv.Remove (nativeSymbol)) { + Log.LogMessage (MessageImportance.Low, "Ignoring Objective-C class '{0}'", nativeSymbol); + } + break; + case "function": + case "field": + if (!filterObjectiveCClasses && rv.Remove (nativeSymbol)) { + Log.LogMessage (MessageImportance.Low, "Ignoring native symbol '{0}'", nativeSymbol); + } + break; + default: + Log.LogMessage (MessageImportance.Low, "Ignoring symbol '{0}' with unknown SymbolType '{1}'", nativeSymbol, symbolType); + continue; + } + } + + rv.Remove (""); // no empty symbols + + return rv.OrderBy (v => v).ToList (); + } + + void GenerateInlinedClassGetHandleNativeCode (List items) + { + // Collect all surviving symbols from all input files. + var classes = FilterOutIgnoredSymbols (ReadUniqueLinesFromFiles (SurvivingClassesFiles), filterObjectiveCClasses: true); + + if (classes.Count == 0) { + Log.LogMessage (MessageImportance.Low, "There were no surviving Objective-C classes that require inlined Class.GetHandle native code."); + return; + } + + if (string.IsNullOrEmpty (TypeMapFilePath) || !File.Exists (TypeMapFilePath)) { + Log.LogError ("The type map file '{0}' does not exist. This file is generated by the linker's CoreTypeMapStep. Ensure that trimming ran successfully.", TypeMapFilePath ?? ""); + return; + } + + var typeMapEntries = File.ReadAllLines (TypeMapFilePath) + .Select (line => { + var parts = line.Split ('|'); + string className = ""; + string framework = ""; + string introduced = ""; + bool iswrapper = false; + bool isstubclass = false; + foreach (var part in parts) { + var kvp = part.Split (new char [] { '=' }, 2); + if (kvp.Length != 2) + continue; + var key = kvp [0].Trim (); + var value = kvp [1].Trim (); + switch (key) { + case "Class": + className = value; + break; + case "Framework": + framework = value; + break; + case "Introduced": + introduced = value; + break; + case "IsWrapper": + iswrapper = string.Equals (value, "true", StringComparison.OrdinalIgnoreCase); + break; + case "IsStubClass": + isstubclass = string.Equals (value, "true", StringComparison.OrdinalIgnoreCase); + break; + } + } + return (Class: className, Framework: framework, Introduced: introduced, IsWrapper: iswrapper, IsStubClass: isstubclass); + }) + .ToArray (); + + var typeMap = new Dictionary (); + foreach (var entry in typeMapEntries) { + if (string.IsNullOrEmpty (entry.Class)) + continue; + if (typeMap.ContainsKey (entry.Class)) { + Log.LogError ("Duplicate class '{0}' found in the type map file '{1}'.", entry.Class, TypeMapFilePath); + return; + } + typeMap [entry.Class] = entry; + } + + var sb = new StringBuilder (); + sb.AppendLine ($"#include "); + sb.AppendLine ($"#include "); + foreach (var objectiveCClassName in classes) { + // We don't want to import every header under the sun to find the @interface definitions for each class, so we generate + // a forward declaration for each class. To avoid potential issues with missing classes at runtime, we mark each declaration with __attribute__((weak_import)). + // The only exception is that we need to #include Foundation, which means we can't create declarations for Foundation classes. + if (!typeMap.TryGetValue (objectiveCClassName, out var info)) { + sb.AppendLine ($"__attribute__((weak_import)) @interface {objectiveCClassName} : NSObject @end // no objc type found"); + } else if (info.IsWrapper && info.Framework == "Foundation") { + // This is a special case for wrapper classes in the Foundation framework. Since we need to #include Foundation, we can't create a forward declaration for these classes. However, since they are wrappers, we know they won't be missing at runtime, so we don't need to mark them with __attribute__((weak_import)). + sb.AppendLine ($"// The class '{objectiveCClassName}' comes from the Foundation framework, so no generated @interface declaration."); + } else { + if (info.IsStubClass) + sb.AppendLine ("__attribute__((objc_class_stub)) __attribute__((objc_subclassing_restricted))"); + sb.AppendLine ($"__attribute__((weak_import)) @interface {objectiveCClassName} : NSObject @end // is stub: {info.IsStubClass}"); + } + sb.AppendLine ($"Class xamarin_Class_GetHandle_{objectiveCClassName}_Native ();"); + sb.AppendLine ($"Class xamarin_Class_GetHandle_{objectiveCClassName}_Native () {{ return [{objectiveCClassName} class]; }}"); + sb.AppendLine (); + } + + var outputPath = Path.Combine (OutputDirectory, "inlined-class-gethandle.m"); + FileUtils.WriteIfDifferent (outputPath, sb.ToString (), (msg) => Log.LogMessage (MessageImportance.Low, msg)); + + items.Add (outputPath); + } + + void GenerateInlinedDlfcnNativeCode (List items) + { + var survivingSymbols = FilterOutIgnoredSymbols (ReadUniqueLinesFromFiles (SurvivingNativeSymbolsFiles), filterObjectiveCClasses: false); + + if (survivingSymbols.Count == 0) { + Log.LogMessage (MessageImportance.Low, "There were no surviving symbols that require inlined dlfcn native code."); + return; + } + + var sb = new StringBuilder (); + // The generated C code uses 'extern void*' declarations and returns the address of the symbol. + // This is intentional: it allows the native linker to resolve the symbol at link time, which + // is the whole point of this optimization (avoiding dlsym at runtime). + foreach (var field in survivingSymbols.OrderBy (s => s)) { + // Using 'void*' as a stand-in type since we only need the address + sb.AppendLine ($"extern void* {field};"); + sb.AppendLine ($"void* xamarin_Dlfcn_{field}_Native ();"); + sb.AppendLine ($"void* xamarin_Dlfcn_{field}_Native () {{ return &{field}; }}"); + sb.AppendLine (); + } + + var outputPath = Path.Combine (OutputDirectory, "inlined-dlfcn.c"); + FileUtils.WriteIfDifferent (outputPath, sb.ToString (), (msg) => Log.LogMessage (MessageImportance.Low, msg)); + + items.Add (outputPath); + } + } +} diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/ReadAppManifest.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/ReadAppManifest.cs index 4a18efd376ea..6e70959e2d15 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/ReadAppManifest.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/ReadAppManifest.cs @@ -56,7 +56,7 @@ public override bool Execute () if (!string.IsNullOrEmpty (AppManifest?.ItemSpec)) { try { - plist = PDictionary.FromFile (AppManifest!.ItemSpec); + plist = PDictionary.OpenFile (AppManifest!.ItemSpec); } catch (Exception ex) { Log.LogError (null, null, null, AppManifest!.ItemSpec, 0, 0, 0, 0, MSBStrings.E0010, AppManifest.ItemSpec, ex.Message); return false; @@ -73,7 +73,7 @@ public override bool Execute () if (Platform == ApplePlatform.MacCatalyst) { // The minimum version in the Info.plist is the macOS version. However, the rest of our tooling // expects the iOS version, so expose that. - if (!MacCatalystSupport.TryGetiOSVersion (Sdks.GetAppleSdk (Platform).GetSdkPath (), MinimumOSVersion!, out var convertedVersion, out var knownMacOSVersions)) + if (!MacCatalystSupport.TryGetiOSVersion (CurrentSdk.GetSdkPath (), MinimumOSVersion!, out var convertedVersion, out var knownMacOSVersions)) Log.LogError (MSBStrings.E0187, MinimumOSVersion, string.Join (", ", knownMacOSVersions.OrderBy (v => v))); MinimumOSVersion = convertedVersion; } diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/ValidateAppBundle.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/ValidateAppBundle.cs index d2044d0ec6ed..19b6dfef984e 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/ValidateAppBundle.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/ValidateAppBundle.cs @@ -34,7 +34,7 @@ void ValidateAppExtension (string path, string mainBundleIdentifier, string main return; } - var plist = PDictionary.FromFile (info)!; + var plist = PDictionary.OpenFile (info); var bundleIdentifier = plist.GetCFBundleIdentifier (); if (string.IsNullOrEmpty (bundleIdentifier)) { @@ -129,7 +129,7 @@ void ValidateWatchApp (string path, string mainBundleIdentifier, string mainShor return; } - var plist = PDictionary.FromFile (info)!; + var plist = PDictionary.OpenFile (info); var bundleIdentifier = plist.GetCFBundleIdentifier (); if (string.IsNullOrEmpty (bundleIdentifier)) { Log.LogError (7015, info, MSBStrings.E7015, name); @@ -202,7 +202,7 @@ void ValidateWatchExtension (string path, string watchAppBundleIdentifier, strin return; } - var plist = PDictionary.FromFile (info)!; + var plist = PDictionary.OpenFile (info); var bundleIdentifier = plist.GetCFBundleIdentifier (); if (string.IsNullOrEmpty (bundleIdentifier)) { @@ -290,7 +290,7 @@ public override bool Execute () return false; } - var plist = PDictionary.FromFile (mainInfoPath)!; + var plist = PDictionary.OpenFile (mainInfoPath); var bundleIdentifier = plist.GetCFBundleIdentifier (); if (string.IsNullOrEmpty (bundleIdentifier)) { diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/WriteAppManifest.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/WriteAppManifest.cs index 6e56f518a1a4..4f397922057c 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/WriteAppManifest.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/WriteAppManifest.cs @@ -32,7 +32,7 @@ public override bool Execute () var firstManifest = AppManifests! [0].ItemSpec; try { - plist = PDictionary.FromFile (firstManifest)!; + plist = PDictionary.OpenFile (firstManifest); } catch (Exception ex) { Log.LogError (null, null, null, firstManifest, 0, 0, 0, 0, MSBStrings.E0010, ex.Message); return false; diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/WriteAssetPackManifest.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/WriteAssetPackManifest.cs index 516e75a63ca8..380ab4fc40a8 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/WriteAssetPackManifest.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/WriteAssetPackManifest.cs @@ -31,7 +31,7 @@ public override bool Execute () if (ShouldExecuteRemotely ()) return ExecuteRemotely (); - var template = PDictionary.FromFile (TemplatePath!.ItemSpec)!; + var template = PDictionary.OpenFile (TemplatePath!.ItemSpec); var resources = template.GetArray ("resources"); foreach (var resource in resources.OfType ()) { diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/XamarinTask.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/XamarinTask.cs index 603f85252b07..3cd5a9386821 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/XamarinTask.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/XamarinTask.cs @@ -9,6 +9,7 @@ using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; +using Xamarin.Bundler; using Xamarin.Localization.MSBuild; using Xamarin.Messaging.Build.Client; using Xamarin.Utils; @@ -17,7 +18,7 @@ #nullable enable namespace Xamarin.MacDev.Tasks { - public abstract class XamarinTask : Task, IHasSessionId, ICustomLogger { + public abstract class XamarinTask : Task, IHasSessionId, ICustomLogger, IToolLog { public string SessionId { get; set; } = string.Empty; @@ -25,6 +26,16 @@ public abstract class XamarinTask : Task, IHasSessionId, ICustomLogger { public string SdkDevPath { get; set; } = string.Empty; + int? verbosity; + public int Verbosity { + get { + if (!verbosity.HasValue) + verbosity = VerbosityUtils.GetVerbosityLevel (Environment.CommandLine); + return verbosity.Value; + } + set => verbosity = value; + } + public string GetSdkDevPath () { if (string.IsNullOrEmpty (SdkDevPath)) { @@ -35,6 +46,52 @@ public string GetSdkDevPath () return SdkDevPath; } + XcodeLocator? xcodeLocator = null; + public XcodeLocator GetXcodeLocator (bool initialDiscovery = false, Action? preprocess = null) + { + if (xcodeLocator is null) { + if (!initialDiscovery && string.IsNullOrEmpty (SdkDevPath)) { + Log.LogError (MSBStrings.E7169, /* The task '{0}' requires the property '{1}' to be set. Please file an issue at https://github.com/dotnet/macios/issues/new/choose. */ GetType ().Name, "SdkDevPath"); + } + + var xcodeLocator = new XcodeLocator (this); + preprocess?.Invoke (xcodeLocator); + if (!xcodeLocator.TryLocatingXcode (SdkDevPath)) + Log.LogError (MSBStrings.E0086 /* Could not find a valid Xcode developer path */); + this.xcodeLocator = xcodeLocator; + } + return xcodeLocator; + } + + protected void SetXcodeLocator (XcodeLocator xcodeLocator) + { + this.xcodeLocator = xcodeLocator; + } + + IAppleSdk? currentSdk; + public IAppleSdk CurrentSdk { + get { + if (currentSdk is null) { + var xcodeLocator = GetXcodeLocator (); + switch (Platform) { + case ApplePlatform.iOS: + currentSdk = new AppleIPhoneSdk (xcodeLocator.DeveloperRoot, xcodeLocator.DeveloperRootVersionPlist); + break; + case ApplePlatform.TVOS: + currentSdk = new AppleTVOSSdk (xcodeLocator.DeveloperRoot, xcodeLocator.DeveloperRootVersionPlist); + break; + case ApplePlatform.MacCatalyst: + case ApplePlatform.MacOSX: + currentSdk = new MacOSXSdk (xcodeLocator.DeveloperRoot, xcodeLocator.DeveloperRootVersionPlist); + break; + default: + throw new InvalidOperationException (string.Format (MSBStrings.InvalidPlatform, Platform)); + } + } + return currentSdk; + } + } + void VerifyTargetFrameworkMoniker () { if (!string.IsNullOrEmpty (TargetFrameworkMoniker)) @@ -232,48 +289,6 @@ internal static bool CopyInputsToRemoteServerAsync (T task) where T : Task, I } } - internal protected static ReportErrorCallback GetFileCopierReportErrorCallback (TaskLoggingHelper log) - { - return new ReportErrorCallback ((int code, string format, object? [] arguments) => { - FileCopierReportErrorCallback (log, code, format, arguments); - }); - } - - internal protected static void FileCopierReportErrorCallback (TaskLoggingHelper log, int code, string format, params object? [] arguments) - { - log.LogError (format, arguments); - } - - protected void FileCopierReportErrorCallback (int code, string format, params object? [] arguments) - { - FileCopierReportErrorCallback (Log, code, format, arguments); - } - - internal protected static LogCallback GetFileCopierLogCallback (TaskLoggingHelper log) - { - return new LogCallback ((int min_verbosity, string format, object? [] arguments) => { - FileCopierLogCallback (log, min_verbosity, format, arguments); - }); - } - - protected static void FileCopierLogCallback (TaskLoggingHelper log, int min_verbosity, string format, params object? [] arguments) - { - MessageImportance importance; - if (min_verbosity <= 0) { - importance = MessageImportance.High; - } else if (min_verbosity <= 1) { - importance = MessageImportance.Normal; - } else { - importance = MessageImportance.Low; - } - log.LogMessage (importance, format, arguments); - } - - protected void FileCopierLogCallback (int min_verbosity, string format, params object? [] arguments) - { - FileCopierLogCallback (Log, min_verbosity, format, arguments); - } - protected string GetNonEmptyStringOrFallback (ITaskItem item, string metadataName, string fallbackValue, string? fallbackName = null, bool required = false) { return GetNonEmptyStringOrFallback (item, metadataName, out var _, fallbackValue, fallbackName, required); @@ -352,27 +367,50 @@ protected static string GetExecutable (List arguments, string toolName, } #region Xamarin.MacDev.ICustomLogger - void ICustomLogger.LogError (string message, Exception ex) + void ICustomLogger.LogError (string message, Exception? ex) { - Log.LogError (message); + if (!string.IsNullOrEmpty (message)) + Log.LogError (message); if (ex is not null) Log.LogErrorFromException (ex); } - void ICustomLogger.LogWarning (string messageFormat, params object [] args) + void ICustomLogger.LogWarning (string messageFormat, params object? [] args) { Log.LogWarning (messageFormat, args); } - void ICustomLogger.LogInfo (string messageFormat, object [] args) + void ICustomLogger.LogInfo (string messageFormat, params object? [] args) { Log.LogMessage (MessageImportance.Normal, messageFormat, args); } - void ICustomLogger.LogDebug (string messageFormat, params object [] args) + void ICustomLogger.LogDebug (string messageFormat, params object? [] args) { Log.LogMessage (MessageImportance.Low, messageFormat, args); } #endregion + + #region Xamarin.Bundler.IToolLog + void IToolLog.Log (string message) + { + ((ICustomLogger) this).LogInfo (message); + } + + void IToolLog.LogError (string message) + { + ((ICustomLogger) this).LogError (message, null); + } + + void IToolLog.LogException (Exception exception) + { + ((ICustomLogger) this).LogError ("", exception); + } + + void IToolLog.LogError (Exception exception) + { + ((ICustomLogger) this).LogError ("", exception); + } + #endregion } } diff --git a/msbuild/Xamarin.MacDev.Tasks/Tasks/XcodeCompilerToolTask.cs b/msbuild/Xamarin.MacDev.Tasks/Tasks/XcodeCompilerToolTask.cs index e86af43215b6..c189dde986e5 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Tasks/XcodeCompilerToolTask.cs +++ b/msbuild/Xamarin.MacDev.Tasks/Tasks/XcodeCompilerToolTask.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Text; @@ -13,6 +14,7 @@ using Xamarin.Localization.MSBuild; using Xamarin.MacDev; +using Xamarin.MacDev.Models; using Xamarin.Messaging.Build.Client; using Xamarin.Utils; @@ -154,6 +156,92 @@ static bool IsTranslated () return translated.Value; } + // Cache simulator runtime check results to avoid running simctl multiple times. + // Key includes SdkDevPath because different Xcode installations may have different runtimes. + static ConcurrentDictionary simulatorRuntimeCache = new (); + + /// + /// Returns the platform name used by simctl for the current build platform, or null if no simulator is needed. + /// + string? GetSimulatorPlatformName () + { + switch (Platform) { + case ApplePlatform.iOS: + case ApplePlatform.MacCatalyst: + // Mac Catalyst uses the iOS-based toolchain, so it also needs the iOS simulator runtime. + return "iOS"; + case ApplePlatform.TVOS: + return "tvOS"; + case ApplePlatform.MacOSX: + default: + return null; + } + } + + /// + /// Checks if the required simulator runtime is installed and emits a diagnostic if not. + /// Apple's Xcode tools (actool, ibtool, etc.) require the simulator runtime to function, + /// even when building for physical devices. Call this after a tool failure to provide + /// actionable guidance to the user. + /// + void CheckSimulatorRuntimeAvailable () + { + var simPlatform = GetSimulatorPlatformName (); + if (simPlatform is null) + return; + + var cacheKey = $"{simPlatform}:{SdkDevPath}"; + if (simulatorRuntimeCache.TryGetValue (cacheKey, out var cachedResult)) { + if (!cachedResult) + Log.LogError (MSBStrings.E7175, simPlatform); + return; + } + + var jsonOutputFile = Path.GetTempFileName (); + try { + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource (cancellationTokenSource.Token); + timeoutCts.CancelAfter (TimeSpan.FromMinutes (1)); + var args = new List { + "simctl", + "list", + "runtimes", + "-j", + "--json-output=" + jsonOutputFile + }; + var rv = ExecuteAsync ("xcrun", args, showErrorIfFailure: false, cancellationToken: timeoutCts.Token).Result; + + if (rv.ExitCode != 0) { + Log.LogWarning (MSBStrings.W7176, simPlatform); + return; + } + + var json = File.ReadAllText (jsonOutputFile); + var runtimes = SimctlOutputParser.ParseRuntimes (json); + + var hasRuntime = runtimes.Any (r => + string.Equals (r.Platform, simPlatform, StringComparison.OrdinalIgnoreCase) && r.IsAvailable); + + simulatorRuntimeCache [cacheKey] = hasRuntime; + if (!hasRuntime) + Log.LogError (MSBStrings.E7175, simPlatform); + } catch (OperationCanceledException) when (cancellationTokenSource.IsCancellationRequested) { + // User cancelled - don't emit diagnostics + } catch (AggregateException ae) when (ae.InnerException is OperationCanceledException && cancellationTokenSource.IsCancellationRequested) { + // User cancelled - don't emit diagnostics + } catch (OperationCanceledException) { + // Timeout + Log.LogWarning (MSBStrings.W7176, simPlatform); + } catch (AggregateException ae) when (ae.InnerException is OperationCanceledException) { + // Timeout + Log.LogWarning (MSBStrings.W7176, simPlatform); + } catch (Exception ex) { + Log.LogWarning (MSBStrings.W7176, simPlatform); + Log.LogMessage (MessageImportance.Low, "Exception while checking simulator runtime: {0}", ex.Message); + } finally { + File.Delete (jsonOutputFile); + } + } + protected int Compile (ITaskItem [] items, string output, ITaskItem manifest) { var environment = new Dictionary (); @@ -193,7 +281,7 @@ protected int Compile (ITaskItem [] items, string output, ITaskItem manifest) if (Log.HasLoggedErrors) return 1; - var rv = ExecuteAsync (executable, args, environment: environment, cancellationToken: cancellationTokenSource.Token).Result; + var rv = ExecuteAsync (executable, args, showErrorIfFailure: true, environment: environment, cancellationToken: cancellationTokenSource.Token).Result; var exitCode = rv.ExitCode; var messages = rv.Output.StandardOutput; File.WriteAllText (manifest.ItemSpec, messages); @@ -206,12 +294,10 @@ protected int Compile (ITaskItem [] items, string output, ITaskItem manifest) if (errors.Length > 0) Log.LogError (null, null, null, items [0].ItemSpec, 0, 0, 0, 0, "{0}", errors); - Log.LogError (MSBStrings.E0117, ToolName, exitCode); - // Note: If the log file exists and is parseable, log those warnings/errors as well... if (File.Exists (manifest.ItemSpec)) { try { - var plist = PDictionary.FromFile (manifest.ItemSpec)!; + var plist = PDictionary.OpenFile (manifest.ItemSpec); LogWarningsAndErrors (plist, items [0]); } catch (Exception ex) { @@ -220,6 +306,9 @@ protected int Compile (ITaskItem [] items, string output, ITaskItem manifest) File.Delete (manifest.ItemSpec); } + + // Check if the failure might be caused by a missing simulator runtime. + CheckSimulatorRuntimeAvailable (); } return exitCode; @@ -285,8 +374,14 @@ protected void LogWarningsAndErrors (PDictionary plist, ITaskItem file) if (plist.TryGetValue (string.Format ("com.apple.{0}.errors", ToolName), out array)) { foreach (var item in array.OfType ()) { - if (item.TryGetValue ("description", out message)) + if (item.TryGetValue ("description", out message)) { Log.LogError (ToolName, null, null, file.ItemSpec, 0, 0, 0, 0, "{0}", message.Value); + if (IsSimulatorRuntimeVersionError (message.Value)) { + var simPlatform = GetSimulatorPlatformName (); + if (simPlatform is not null) + Log.LogError (MSBStrings.E7177, simPlatform); + } + } } } @@ -298,6 +393,15 @@ protected void LogWarningsAndErrors (PDictionary plist, ITaskItem file) } } + /// + /// Detects error messages like "No simulator runtime version from [...] available to use with ... SDK version ..." + /// which indicate an incompatible or missing simulator runtime version. + /// + static bool IsSimulatorRuntimeVersionError (string message) + { + return message.IndexOf ("simulator runtime", StringComparison.OrdinalIgnoreCase) >= 0; + } + public void Cancel () { if (ShouldExecuteRemotely ()) { diff --git a/msbuild/Xamarin.MacDev.Tasks/VerbosityUtils.cs b/msbuild/Xamarin.MacDev.Tasks/VerbosityUtils.cs index f0797ef078fd..02211f93bcc3 100644 --- a/msbuild/Xamarin.MacDev.Tasks/VerbosityUtils.cs +++ b/msbuild/Xamarin.MacDev.Tasks/VerbosityUtils.cs @@ -10,39 +10,28 @@ namespace Xamarin.MacDev.Tasks { // needs to be verbosity-aware public static class VerbosityUtils { - // verbosity can be set in multiple ways - // this makes it a consistent interpretation of them - static public string [] Merge (string extraArguments, LoggerVerbosity taskVerbosity) + public static void RenderVerbosity (IList arguments, int taskVerbosity) { - string [] result = Array.Empty (); - var empty_extra = String.IsNullOrEmpty (extraArguments); - // We give the priority to the extra arguments given to the tools - if (empty_extra || (!empty_extra && !extraArguments.Contains ("-q") && !extraArguments.Contains ("-v"))) { - // if nothing is specified fall back to msbuild settings - // first check if some were supplied on the command-line - result = GetVerbosityLevel (Environment.CommandLine); - // if not then use the default from the msbuild config files, which Visual Studio for Mac can override (to match the IDE setting for msbuild) - if (result.Length == 0) - result = GetVerbosityLevel (taskVerbosity); - } - return result; + if (taskVerbosity == 0) + return; + + for (var i = 0; i < Math.Abs (taskVerbosity); i++) + arguments.Add (taskVerbosity < 0 ? "-q" : "-v"); } // // This is an hack, since there can be multiple loggers. - // However it's the most common use case and `mtouch` logs - // are often the most important to gather and developers expect - // a single change (in verbosity) to do the job and be consistent in CI. + // However it should cover most use cases. // // msbuild argument format // -verbosity: Display this amount of information in the event log. // The available verbosity levels are: q[uiet], m[inimal], // n[ormal], d[etailed], and diag[nostic]. (Short form: -v) // - static public string [] GetVerbosityLevel (string commandLine) + public static int GetVerbosityLevel (string commandLine) { if (!StringUtils.TryParseArguments (commandLine, out var args, out _)) - return GetVerbosityLevel (LoggerVerbosity.Normal); + return 0; var hasBinaryLog = false; foreach (var arg in args) { @@ -99,20 +88,20 @@ static public string [] GetVerbosityLevel (string commandLine) // The values here come from: https://github.com/mono/monodevelop/blob/143f9b6617123a0841a5cc5a2a4e13b309535792/main/src/core/MonoDevelop.Projects.Formats.MSBuild/MonoDevelop.Projects.MSBuild.Shared/RemoteBuildEngineMessages.cs#L186 // Assume 'Normal (2)' is the default verbosity (no change), and the other values follow from there. - static public string [] GetVerbosityLevel (LoggerVerbosity v) + public static int GetVerbosityLevel (LoggerVerbosity v) { switch ((LoggerVerbosity) v) { case LoggerVerbosity.Quiet: - return new [] { "-q", "-q", "-q", "-q" }; + return -4; case LoggerVerbosity.Minimal: - return new [] { "-q", "-q" }; + return -2; case LoggerVerbosity.Normal: default: - return Array.Empty (); + return 0; case LoggerVerbosity.Detailed: - return new [] { "-v", "-v" }; + return 2; case LoggerVerbosity.Diagnostic: - return new [] { "-v", "-v", "-v", "-v" }; + return 4; } } } diff --git a/msbuild/Xamarin.MacDev.Tasks/Xamarin.MacDev.Tasks.csproj b/msbuild/Xamarin.MacDev.Tasks/Xamarin.MacDev.Tasks.csproj index 24caeb9ef41a..713db306ebef 100644 --- a/msbuild/Xamarin.MacDev.Tasks/Xamarin.MacDev.Tasks.csproj +++ b/msbuild/Xamarin.MacDev.Tasks/Xamarin.MacDev.Tasks.csproj @@ -7,14 +7,12 @@ true ../../product.snk true - latest - true $(DefineConstants);MSBUILD_TASKS $(NoWarn);NU1603 $(NoWarn);NU1701 $(NoWarn);MSB3277 $(NoWarn);8002 - enable + $(NoWarn);CS0618 true @@ -77,9 +75,15 @@ JsonExtensions.cs + + IToolLog.cs + StringUtils.cs + + Symbols.cs + FileCopier.cs diff --git a/msbuild/Xamarin.Shared/Xamarin.Mac.AppExtension.Common.targets b/msbuild/Xamarin.Shared/Xamarin.Mac.AppExtension.Common.targets index 569a2dbac1d9..7e7fb0796862 100644 --- a/msbuild/Xamarin.Shared/Xamarin.Mac.AppExtension.Common.targets +++ b/msbuild/Xamarin.Shared/Xamarin.Mac.AppExtension.Common.targets @@ -25,17 +25,6 @@ Copyright (C) 2013-2014 Xamarin. All rights reserved. - - - - - - - - - Entitlements.plist - - diff --git a/msbuild/Xamarin.Shared/Xamarin.Shared.props b/msbuild/Xamarin.Shared/Xamarin.Shared.props index 92e9e93ea55c..43b3f5fa0091 100644 --- a/msbuild/Xamarin.Shared/Xamarin.Shared.props +++ b/msbuild/Xamarin.Shared/Xamarin.Shared.props @@ -99,7 +99,7 @@ Copyright (C) 2020 Microsoft. All rights reserved. <_CanArchive>false - <_CanArchive Condition="('$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst') And '$(OutputType)' == 'Exe' And '$(IsAppExtension)' == 'false'">true + <_CanArchive Condition="'$(SdkIsDesktop)' == 'true' And '$(OutputType)' == 'Exe' And '$(IsAppExtension)' == 'false'">true <_CanArchive Condition="'$(OutputType)' == 'Exe' And '$(SdkIsDevice)' == 'true' And '$(IsAppExtension)' == 'false'">true @@ -122,7 +122,7 @@ Copyright (C) 2020 Microsoft. All rights reserved. $(MtouchNoSymbolStrip) true - true + true true false @@ -131,7 +131,7 @@ Copyright (C) 2020 Microsoft. All rights reserved. $(MtouchNoDSymUtil) - true + true true false @@ -182,7 +182,7 @@ Copyright (C) 2020 Microsoft. All rights reserved. <_EmbeddedResourcePrefix Condition="'$(_PlatformName)' == 'macOS'">xammac <_EmbeddedResourcePrefix Condition="'$(_PlatformName)' != 'macOS'">monotouch - <_AppBundleManifestRelativePath Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">Contents/ + <_AppBundleManifestRelativePath Condition="'$(SdkIsDesktop)' == 'true'">Contents/ .xpc .appex @@ -191,7 +191,7 @@ Copyright (C) 2020 Microsoft. All rights reserved. all - <_AppBundleName Condition="'$(_AppBundleName)' == '' And $([MSBuild]::VersionGreaterThanOrEquals($(TargetFrameworkVersion), 10.0)) And ('$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst')">$(ApplicationTitle) + <_AppBundleName Condition="'$(_AppBundleName)' == '' And $([MSBuild]::VersionGreaterThanOrEquals($(TargetFrameworkVersion), 10.0)) And '$(SdkIsDesktop)' == 'true'">$(ApplicationTitle) <_AppBundleName Condition="'$(_AppBundleName)' == ''">$(AssemblyName) @@ -233,15 +233,6 @@ Copyright (C) 2020 Microsoft. All rights reserved. true - - latest - true diff --git a/msbuild/Xamarin.Shared/Xamarin.Shared.targets b/msbuild/Xamarin.Shared/Xamarin.Shared.targets index c5139ca6acc1..8307a85ebf48 100644 --- a/msbuild/Xamarin.Shared/Xamarin.Shared.targets +++ b/msbuild/Xamarin.Shared/Xamarin.Shared.targets @@ -115,7 +115,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. - False + False @@ -294,7 +294,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. - + @@ -302,7 +302,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. @@ -320,7 +320,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. @@ -348,7 +348,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. - + - - + + %(BundleResource.Link) + + + %(Content.Link) + @@ -684,6 +692,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. ProjectDir="$(MSBuildProjectDirectory)" ResourcePrefix="$(_ResourcePrefix)" ResourceRules="$(_PreparedResourceRules)" + SdkDevPath="$(_SdkDevPath)" SdkIsSimulator="$(_SdkIsSimulator)" SdkVersion="$(_SdkVersion)" SupportedOSPlatformVersion="$(SupportedOSPlatformVersion)" @@ -710,6 +719,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. Condition="'$(IsMacEnabled)' == 'true' And '$(_BundleOriginalResources)' != 'true'" SessionId="$(BuildSessionId)" AppManifest="$(_TemporaryAppManifest)" + SdkDevPath="$(_SdkDevPath)" TargetFrameworkMoniker="$(_ComputedTargetFrameworkMoniker)" > @@ -784,7 +794,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. DependsOnTargets="$(_CompileEntitlementsDependsOn)" Outputs="$(_CompiledEntitlementsPath)"> - + @@ -797,6 +807,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. Entitlements="$(CodesignEntitlements)" CompiledEntitlements="$(_CompiledEntitlementsPath)" ProvisioningProfile="$(_ProvisioningProfile)" + SdkDevPath="$(_SdkDevPath)" SdkIsSimulator="$(_SdkIsSimulator)" SdkPlatform="$(_SdkPlatform)" SdkVersion="$(_SdkVersion)" @@ -1278,7 +1289,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. will apply to Xamarin.Mac as well. --> - <_PkgInfoPath Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">$(_AppBundlePath)Contents\PkgInfo + <_PkgInfoPath Condition="'$(SdkIsDesktop)' == 'true'">$(_AppBundlePath)Contents\PkgInfo <_PkgInfoPath Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS' Or '$(_PlatformName)' == 'watchOS'">$(_AppBundlePath)PkgInfo @@ -2069,6 +2080,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. SdkIsSimulator="$(_SdkIsSimulator)" SdkPlatform="$(_SdkPlatform)" ProvisioningProfile="$(CodesignProvision)" + SdkDevPath="$(_SdkDevPath)" SigningKey="$(_SpecifiedCodesignKey)" DetectedCodeSigningKey="$(_CodeSigningKey)" TargetFrameworkMoniker="$(_ComputedTargetFrameworkMoniker)" @@ -2082,7 +2094,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. - <_EmbeddedProvisionProfilePath Condition="'$(_EmbeddedProvisionProfilePath)' == '' And ('$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst')">$(_AppBundlePath)Contents\embedded.provisionprofile + <_EmbeddedProvisionProfilePath Condition="'$(_EmbeddedProvisionProfilePath)' == '' And '$(SdkIsDesktop)' == 'true'">$(_AppBundlePath)Contents\embedded.provisionprofile <_EmbeddedProvisionProfilePath Condition="'$(_EmbeddedProvisionProfilePath)' == '' And ('$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS' Or '$(_PlatformName)' == 'watchOS')">$(_AppBundlePath)embedded.mobileprovision @@ -2091,6 +2103,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. @@ -2302,7 +2315,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. - + @@ -2574,7 +2587,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. > - true + true false @@ -2676,6 +2689,10 @@ Copyright (C) 2018 Microsoft. All rights reserved. + + + + true - + @@ -2736,6 +2753,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. @@ -2790,12 +2808,12 @@ Copyright (C) 2018 Microsoft. All rights reserved. <_NativeExecutableRelativePath Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS' Or '$(_PlatformName)' == 'watchOS'">$(_ExecutableName) - <_NativeExecutableRelativePath Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">Contents\MacOS\$(_ExecutableName) + <_NativeExecutableRelativePath Condition="'$(SdkIsDesktop)' == 'true'">Contents\MacOS\$(_ExecutableName) <_NativeExecutable>$(_AppBundlePath)$(_NativeExecutableRelativePath) - - + @@ -3252,30 +3270,30 @@ Copyright (C) 2018 Microsoft. All rights reserved. <_AppBundlePath>$(AppBundleDir) <_AppBundlePath Condition="$([System.IO.Path]::IsPathRooted('$(AppBundleDir)'))">$([MSBuild]::MakeRelative('$(MSBuildProjectDirectory)','$(AppBundleDir)')) <_AppBundlePath>$([MSBuild]::EnsureTrailingSlash('$(_AppBundlePath)')) - <_AppResourcesRelativePath Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">Contents\Resources\ + <_AppResourcesRelativePath Condition="'$(SdkIsDesktop)' == 'true'">Contents\Resources\ <_AppResourcesRelativePath Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS' Or '$(_PlatformName)' == 'watchOS'"> <_AppResourcesPath>$(_AppBundlePath)$(_AppResourcesRelativePath) - <_AppContentsRelativePath Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">Contents\$(_CustomBundleName) + <_AppContentsRelativePath Condition="'$(SdkIsDesktop)' == 'true'">Contents\$(_CustomBundleName) <_AppContentsRelativePath Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS' Or '$(_PlatformName)' == 'watchOS'"> <_AppContentsPath>$(_AppBundlePath)$(_AppContentsRelativePath) - <_AppFrameworksRelativePath Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">Contents\Frameworks\ + <_AppFrameworksRelativePath Condition="'$(SdkIsDesktop)' == 'true'">Contents\Frameworks\ <_AppFrameworksRelativePath Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS' Or '$(_PlatformName)' == 'watchOS'">Frameworks\ <_AppFrameworksPath>$(_AppBundlePath)$(_AppFrameworksRelativePath) - <_AppCodeSignatureRelativePath Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">Contents\ + <_AppCodeSignatureRelativePath Condition="'$(SdkIsDesktop)' == 'true'">Contents\ <_AppCodeSignatureRelativePath Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS' Or '$(_PlatformName)' == 'watchOS'"> <_AppCodeSignaturePath>$(_AppBundlePath)$(_AppCodeSignatureRelativePath) - <_AppPlugInsRelativeLocation Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">Contents\ - <_AppPlugInsRelativeLocation Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS'"> + <_AppPlugInsRelativeLocation Condition="'$(SdkIsDesktop)' == 'true'">Contents\ + <_AppPlugInsRelativeLocation Condition="'$(SdkIsMobile)' == 'true'"> <_AppPlugInsRelativePath>$(_AppPlugInsRelativeLocation)PlugIns\ <_AppExtensionRoot>$(_AppBundlePath)$(_AppPlugInsRelativeLocation) <_AppPlugInsPath>$(_AppBundlePath)$(_AppPlugInsRelativePath) - <_AppXpcServicesRelativePath Condition="'$(_PlatformName)' == 'macOS' Or '$(_PlatformName)' == 'MacCatalyst'">Contents\XPCServices\ + <_AppXpcServicesRelativePath Condition="'$(SdkIsDesktop)' == 'true'">Contents\XPCServices\ <_AppXpcServicesRelativePath Condition="'$(_PlatformName)' == 'iOS' Or '$(_PlatformName)' == 'tvOS' Or '$(_PlatformName)' == 'watchOS'">XPCServices\ <_AppXpcServicesPath>$(_AppBundlePath)$(_AppXpcServicesRelativePath) @@ -3375,7 +3393,7 @@ Copyright (C) 2018 Microsoft. All rights reserved. - + diff --git a/msbuild/Xamarin.Shared/Xamarin.TVOS.AppExtension.Common.targets b/msbuild/Xamarin.Shared/Xamarin.TVOS.AppExtension.Common.targets index f2348586feab..78ab53ef731a 100644 --- a/msbuild/Xamarin.Shared/Xamarin.TVOS.AppExtension.Common.targets +++ b/msbuild/Xamarin.Shared/Xamarin.TVOS.AppExtension.Common.targets @@ -33,11 +33,6 @@ Copyright (C) 2014-2016 Xamarin. All rights reserved. - - - - - diff --git a/msbuild/Xamarin.Shared/Xamarin.iOS.AppExtension.Common.targets b/msbuild/Xamarin.Shared/Xamarin.iOS.AppExtension.Common.targets index 2c2584b6b595..67cd4bfe4602 100644 --- a/msbuild/Xamarin.Shared/Xamarin.iOS.AppExtension.Common.targets +++ b/msbuild/Xamarin.Shared/Xamarin.iOS.AppExtension.Common.targets @@ -26,11 +26,6 @@ Copyright (C) 2014-2016 Xamarin. All rights reserved. - - - - - diff --git a/msbuild/Xamarin.Shared/Xamarin.iOS.Common.targets b/msbuild/Xamarin.Shared/Xamarin.iOS.Common.targets index f7686070a0a6..bb7c9955349b 100644 --- a/msbuild/Xamarin.Shared/Xamarin.iOS.Common.targets +++ b/msbuild/Xamarin.Shared/Xamarin.iOS.Common.targets @@ -235,7 +235,7 @@ Copyright (C) 2013-2016 Xamarin. All rights reserved. diff --git a/msbuild/Xamarin.iOS.Tasks.Windows/Xamarin.Messaging.Apple.targets b/msbuild/Xamarin.iOS.Tasks.Windows/Xamarin.Messaging.Apple.targets index 6e5b721f0aca..38dae88a7f8b 100644 --- a/msbuild/Xamarin.iOS.Tasks.Windows/Xamarin.Messaging.Apple.targets +++ b/msbuild/Xamarin.iOS.Tasks.Windows/Xamarin.Messaging.Apple.targets @@ -20,7 +20,7 @@ True - False + False diff --git a/msbuild/Xamarin.iOS.Tasks.Windows/Xamarin.iOS.Tasks.Windows.csproj b/msbuild/Xamarin.iOS.Tasks.Windows/Xamarin.iOS.Tasks.Windows.csproj index dccb118d4a4e..7db8e29d17b0 100644 --- a/msbuild/Xamarin.iOS.Tasks.Windows/Xamarin.iOS.Tasks.Windows.csproj +++ b/msbuild/Xamarin.iOS.Tasks.Windows/Xamarin.iOS.Tasks.Windows.csproj @@ -9,11 +9,8 @@ ../../product.snk $(NoWarn);8002 win - latest - Nullable $(NoWarn);NU1603 $(NoWarn);NU1701 - enable diff --git a/runtime/bindings-generator.csproj b/runtime/bindings-generator.csproj index 4348bb7b6941..d2b274015314 100644 --- a/runtime/bindings-generator.csproj +++ b/runtime/bindings-generator.csproj @@ -4,8 +4,6 @@ Exe net$(BundledNETCoreAppTargetFrameworkVersion) enable - enable - latest false false diff --git a/runtime/coreclr-bridge.m b/runtime/coreclr-bridge.m index 8554e64980c9..1368766a6040 100644 --- a/runtime/coreclr-bridge.m +++ b/runtime/coreclr-bridge.m @@ -213,10 +213,6 @@ * Ref: https://github.com/dotnet/designs/blob/1bb5844c165195e2f633cb1dbe042c4b92aefc4d/accepted/2021/objectivec-interop.md */ -struct TrackedObjectInfo { - struct NSObjectData* data; -}; - void xamarin_bridge_setup () { @@ -296,10 +292,10 @@ // But we can access the native memory given to us when the object was toggled // (and which is passed as the 'ptr' argument), so let's get the data we need from there. int rv = 0; - struct TrackedObjectInfo *info = (struct TrackedObjectInfo *) ptr; - enum NSObjectFlags flags = (enum NSObjectFlags) info->data->flags; + struct NSObjectData *data = (struct NSObjectData *) ptr; + enum NSObjectFlags flags = (enum NSObjectFlags) data->flags; bool isRegisteredToggleRef = (flags & NSObjectFlagsRegisteredToggleRef) == NSObjectFlagsRegisteredToggleRef; - id handle = info->data->handle; + id handle = data->handle; MonoToggleRefStatus res = (MonoToggleRefStatus) 0; if (isRegisteredToggleRef) { @@ -337,9 +333,9 @@ void xamarin_coreclr_reference_tracking_tracked_object_entered_finalization (void* ptr) { - struct TrackedObjectInfo *info = (struct TrackedObjectInfo *) ptr; - info->data->flags = (enum NSObjectFlags) (info->data->flags | NSObjectFlagsInFinalizerQueue); - LOG_CORECLR (stderr, "%s (%p) flags: %i\n", __func__, ptr, (int) info->flags); + struct NSObjectData *data = (struct NSObjectData *) ptr; + data->flags = (enum NSObjectFlags) (data->flags | NSObjectFlagsInFinalizerQueue); + LOG_CORECLR (stderr, "%s (%p) flags: %i\n", __func__, ptr, (int) data->flags); } void @@ -511,6 +507,10 @@ LOG_CORECLR (stderr, "xamarin_vm_initialize (%i, %p, %p): rv: %i domainId: %i handle: %p\n", combinedPropertyCount, combinedPropertyKeys, combinedPropertyValues, rv, coreclr_domainId, coreclr_handle); + if (rv != 0) { + LOG (PRODUCT ": The call to 'coreclr_initialize' failed: %i (%p)\n", rv, rv); + } + return rv == 0; } #endif // !defined (NATIVEAOT) diff --git a/runtime/xamarin/runtime.h b/runtime/xamarin/runtime.h index 774713b78dd7..60c461f1b4af 100644 --- a/runtime/xamarin/runtime.h +++ b/runtime/xamarin/runtime.h @@ -367,10 +367,9 @@ extern xamarin_register_assemblies_callback xamarin_register_assemblies; // This has a managed equivalent in NSObject.cs struct NSObjectData { id handle; - struct objc_super* super; uint32_t /* NSObjectFlags */ flags; // if this structure ever changes, the encoding for this method will likely have to be updated in Registrar.RegistrarTypeUnsafe, currently it's: - // Signature = "^{NSObjectData=@^{objc_super}I}:", + // Signature = "^{NSObjectData=@I}:", }; #ifdef __cplusplus diff --git a/scripts/Directory.Build.props b/scripts/Directory.Build.props index a68c92a6c121..e27c492ad8e6 100644 --- a/scripts/Directory.Build.props +++ b/scripts/Directory.Build.props @@ -3,7 +3,6 @@ Exe enable - enable false diff --git a/scripts/create-windows-html-report/create-windows-html-report.csproj b/scripts/create-windows-html-report/create-windows-html-report.csproj index 93254ca37ca7..efde66adac7a 100644 --- a/scripts/create-windows-html-report/create-windows-html-report.csproj +++ b/scripts/create-windows-html-report/create-windows-html-report.csproj @@ -3,7 +3,6 @@ Exe net$(BundledNETCoreAppTargetFrameworkVersion) enable - enable diff --git a/scripts/generate-frameworks-constants/generate-frameworks-constants.cs b/scripts/generate-frameworks-constants/generate-frameworks-constants.cs index a6489d4b5cca..979f62b473cb 100644 --- a/scripts/generate-frameworks-constants/generate-frameworks-constants.cs +++ b/scripts/generate-frameworks-constants/generate-frameworks-constants.cs @@ -32,7 +32,7 @@ static ApplePlatform GetPlatform (string platform) static int Fix (ApplePlatform platform, string output) { - var frameworks = Frameworks.GetFrameworks (platform, false).Values.Where (v => !v.Unavailable); + var frameworks = Frameworks.GetFrameworks (platform, false)!.Values.Where (v => !v.IsFrameworkUnavailable ()); var sb = new StringBuilder (); sb.AppendLine ("namespace ObjCRuntime {"); diff --git a/src/AVFoundation/AVAudioBuffer.cs b/src/AVFoundation/AVAudioBuffer.cs index b680d770eb7b..c89ef42d6f03 100644 --- a/src/AVFoundation/AVAudioBuffer.cs +++ b/src/AVFoundation/AVAudioBuffer.cs @@ -12,7 +12,7 @@ namespace AVFoundation { /// A buffer for audio data. /// To be added. - /// Apple documentation for AVAudioBuffer + /// Apple documentation for AVAudioBuffer public partial class AVAudioBuffer { /// To be added. /// To be added. diff --git a/src/AVFoundation/AVAudioChannelLayout.cs b/src/AVFoundation/AVAudioChannelLayout.cs index 3c4eda653773..361fa3bc45bd 100644 --- a/src/AVFoundation/AVAudioChannelLayout.cs +++ b/src/AVFoundation/AVAudioChannelLayout.cs @@ -20,7 +20,7 @@ namespace AVFoundation { /// Corresponds to a channel layout. /// To be added. - /// Apple documentation for AVAudioChannelLayout + /// Apple documentation for AVAudioChannelLayout public partial class AVAudioChannelLayout { static IntPtr CreateLayoutPtr (AudioChannelLayout layout, out IntPtr handleToLayout) { diff --git a/src/AVFoundation/AVAudioFormat.cs b/src/AVFoundation/AVAudioFormat.cs index cd07b31b5f98..a1fb22592a0a 100644 --- a/src/AVFoundation/AVAudioFormat.cs +++ b/src/AVFoundation/AVAudioFormat.cs @@ -20,7 +20,7 @@ namespace AVFoundation { /// Corresponds to a Core Audio AudioStreamBasicDescription struct. /// To be added. - /// Apple documentation for AVAudioFormat + /// Apple documentation for AVAudioFormat public partial class AVAudioFormat { public static bool operator == (AVAudioFormat a, AVAudioFormat b) { diff --git a/src/AVFoundation/AVAudioPlayer.cs b/src/AVFoundation/AVAudioPlayer.cs index 1b8c72356371..9ce72af4277b 100644 --- a/src/AVFoundation/AVAudioPlayer.cs +++ b/src/AVFoundation/AVAudioPlayer.cs @@ -28,7 +28,7 @@ namespace AVFoundation { /// An audio player that can play audio from memory or the local file system. /// To be added. /// avTouch - /// Apple documentation for AVAudioPlayer + /// Apple documentation for AVAudioPlayer public partial class AVAudioPlayer { /// Create a new from the specified url and hint for the file type. /// The url of a local audio file. diff --git a/src/AVFoundation/AVAudioSessionDataSourceDescription.cs b/src/AVFoundation/AVAudioSessionDataSourceDescription.cs index 6895fb55efc7..b10647a82b1c 100644 --- a/src/AVFoundation/AVAudioSessionDataSourceDescription.cs +++ b/src/AVFoundation/AVAudioSessionDataSourceDescription.cs @@ -54,7 +54,7 @@ public enum AVAudioDataSourcePolarPattern { /// Describes a data source of an object. /// To be added. - /// Apple documentation for AVAudioSessionDataSourceDescription + /// Apple documentation for AVAudioSessionDataSourceDescription public partial class AVAudioSessionDataSourceDescription { static internal AVAudioDataSourceLocation ToLocation (NSString? l) { diff --git a/src/AVFoundation/AVAudioSessionPortDescription.cs b/src/AVFoundation/AVAudioSessionPortDescription.cs index 29d9e0f50e62..62f44d34f5a2 100644 --- a/src/AVFoundation/AVAudioSessionPortDescription.cs +++ b/src/AVFoundation/AVAudioSessionPortDescription.cs @@ -15,7 +15,7 @@ namespace AVFoundation { /// Encpasulates information about the input and output ports of an audio session. /// To be added. - /// Apple documentation for AVAudioSessionPortDescription + /// Apple documentation for AVAudioSessionPortDescription public partial class AVAudioSessionPortDescription { } } diff --git a/src/AVFoundation/AVSpeechUtterance.cs b/src/AVFoundation/AVSpeechUtterance.cs index 2c494bd25a83..4c0fb566ac1c 100644 --- a/src/AVFoundation/AVSpeechUtterance.cs +++ b/src/AVFoundation/AVSpeechUtterance.cs @@ -31,7 +31,7 @@ public enum AVSpeechUtteranceInitializationOption { /// /// The property specifies the speed with which the utterance is said. The rate does not appear to be processor-dependent and a rate of 1.0f is unnatural. /// - /// Apple documentation for AVSpeechUtterance + /// Apple documentation for AVSpeechUtterance public partial class AVSpeechUtterance { /// Create a new instance for the specified string. /// The text to speak. diff --git a/src/AVFoundation/Events.cs b/src/AVFoundation/Events.cs index 3e726e7c7c93..3d54e17aff34 100644 --- a/src/AVFoundation/Events.cs +++ b/src/AVFoundation/Events.cs @@ -137,7 +137,7 @@ public override void EndInterruption (AVAudioPlayer player) /// An audio player that can play audio from memory or the local file system. /// To be added. /// avTouch - /// Apple documentation for AVAudioPlayer + /// Apple documentation for AVAudioPlayer public partial class AVAudioPlayer { InternalAVAudioPlayerDelegate EnsureEventDelegate () { diff --git a/src/AppKit/NSBitmapImageRep.cs b/src/AppKit/NSBitmapImageRep.cs index 7da4bef511a9..3fdc05555bab 100644 --- a/src/AppKit/NSBitmapImageRep.cs +++ b/src/AppKit/NSBitmapImageRep.cs @@ -39,7 +39,11 @@ private NSBitmapImageRep (NSObjectFlag a, NSObjectFlag b) : base (a) if (IsDirectBinding) { InitializeHandle (ObjCRuntime.Messaging.IntPtr_objc_msgSend (this.Handle, Selector.GetHandle (selInitForIncrementalLoad)), selInitForIncrementalLoad); } else { - InitializeHandle (ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper (this.SuperHandle, Selector.GetHandle (selInitForIncrementalLoad)), selInitForIncrementalLoad); + unsafe { + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + InitializeHandle (ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper (&__objc_super__, Selector.GetHandle (selInitForIncrementalLoad)), selInitForIncrementalLoad); + GC.KeepAlive (this); + } } } diff --git a/src/AppKit/NSOpenGLPixelFormat.cs b/src/AppKit/NSOpenGLPixelFormat.cs index 86899dc34e16..e873cddce3a6 100644 --- a/src/AppKit/NSOpenGLPixelFormat.cs +++ b/src/AppKit/NSOpenGLPixelFormat.cs @@ -50,7 +50,9 @@ public NSOpenGLPixelFormat (NSOpenGLPixelFormatAttribute [] attribs) if (IsDirectBinding) { InitializeHandle (ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, selInitWithAttributes, new IntPtr ((void*) pArray)), "initWithAttributes:"); } else { - InitializeHandle (ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, selInitWithAttributes, new IntPtr ((void*) pArray)), "initWithAttributes:"); + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + InitializeHandle (ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (&__objc_super__, selInitWithAttributes, new IntPtr ((void*) pArray)), "initWithAttributes:"); + GC.KeepAlive (this); } } @@ -73,7 +75,9 @@ public NSOpenGLPixelFormat (uint [] attribs) if (IsDirectBinding) { InitializeHandle (ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, selInitWithAttributes, new IntPtr ((void*) pArray)), "initWithAttributes:"); } else { - InitializeHandle (ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, selInitWithAttributes, new IntPtr ((void*) pArray)), "initWithAttributes:"); + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + InitializeHandle (ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (&__objc_super__, selInitWithAttributes, new IntPtr ((void*) pArray)), "initWithAttributes:"); + GC.KeepAlive (this); } } diff --git a/src/AppKit/NSPrintPreviewGraphicsContext.cs b/src/AppKit/NSPrintPreviewGraphicsContext.cs new file mode 100644 index 000000000000..ccc191f682c9 --- /dev/null +++ b/src/AppKit/NSPrintPreviewGraphicsContext.cs @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.ComponentModel; + +#if __MACOS__ && !XAMCORE_5_0 + +namespace AppKit { + [UnsupportedOSPlatform ("maccatalyst")] + [UnsupportedOSPlatform ("macos")] + [Obsolete ("This class does not form part of the public API in macOS, and will be removed in the future.")] + [EditorBrowsable (EditorBrowsableState.Never)] + public partial class NSPrintPreviewGraphicsContext : NSGraphicsContext { + + [EditorBrowsable (EditorBrowsableState.Never)] + public override NativeHandle ClassHandle { get { return default; } } + + [EditorBrowsable (EditorBrowsableState.Never)] + protected NSPrintPreviewGraphicsContext (NSObjectFlag t) : base (t) + { + } + + [EditorBrowsable (EditorBrowsableState.Never)] + protected internal NSPrintPreviewGraphicsContext (NativeHandle handle) : base (handle) + { + } + } /* class NSPrintPreviewGraphicsContext */ +} + +#endif // __MACOS__ && !XAMCORE_5_0 diff --git a/src/CloudKit/CKFetchNotificationChangesOperation.cs b/src/CloudKit/CKFetchNotificationChangesOperation.cs index ede7746498ad..4d6db9d7b0ba 100644 --- a/src/CloudKit/CKFetchNotificationChangesOperation.cs +++ b/src/CloudKit/CKFetchNotificationChangesOperation.cs @@ -8,7 +8,6 @@ namespace CloudKit { /// A that ret../../summary_set.sh CKFetchNotificationChangesOperation A /// To be added. - /// Apple documentation for CKFetchNotificationChangesOperation [Register ("CKFetchNotificationChangesOperation", SkipRegistration = true)] [UnsupportedOSPlatform ("ios", "Use 'CKDatabaseSubscription', 'CKFetchDatabaseChangesOperation' and 'CKFetchRecordZoneChangesOperation' instead.")] [UnsupportedOSPlatform ("macos", "Use 'CKDatabaseSubscription', 'CKFetchDatabaseChangesOperation' and 'CKFetchRecordZoneChangesOperation' instead.")] diff --git a/src/CloudKit/CKMarkNotificationsReadOperation.cs b/src/CloudKit/CKMarkNotificationsReadOperation.cs index 3a88ac4db0b8..814e1326e88c 100644 --- a/src/CloudKit/CKMarkNotificationsReadOperation.cs +++ b/src/CloudKit/CKMarkNotificationsReadOperation.cs @@ -8,7 +8,6 @@ namespace CloudKit { /// Marks push notifications as read. Typically used by apps that use push notifications to track record changes. /// To be added. - /// Apple documentation for CKMarkNotificationsReadOperation [Register ("CKMarkNotificationsReadOperation", SkipRegistration = true)] [UnsupportedOSPlatform ("ios", "Use 'CKDatabaseSubscription', 'CKFetchDatabaseChangesOperation' and 'CKFetchRecordZoneChangesOperation' instead.")] [UnsupportedOSPlatform ("macos", "Use 'CKDatabaseSubscription', 'CKFetchDatabaseChangesOperation' and 'CKFetchRecordZoneChangesOperation' instead.")] diff --git a/src/CloudKit/CKModifyBadgeOperation.cs b/src/CloudKit/CKModifyBadgeOperation.cs index 4378300df610..d8446d6e50ac 100644 --- a/src/CloudKit/CKModifyBadgeOperation.cs +++ b/src/CloudKit/CKModifyBadgeOperation.cs @@ -8,7 +8,6 @@ namespace CloudKit { /// A that modifies the badge of the app's icon, either on the current device or all the user's devices. /// To be added. - /// Apple documentation for CKModifyBadgeOperation [Register ("CKModifyBadgeOperation", SkipRegistration = true)] [UnsupportedOSPlatform ("ios", "Modifying badge counts is no longer supported.")] [UnsupportedOSPlatform ("macos", "Modifying badge counts is no longer supported.")] diff --git a/src/CoreAnimation/CALayer.cs b/src/CoreAnimation/CALayer.cs index 8af4b7110e68..8df9a5041ab3 100644 --- a/src/CoreAnimation/CALayer.cs +++ b/src/CoreAnimation/CALayer.cs @@ -54,7 +54,12 @@ public CALayer (CALayer other) Messaging.IntPtr_objc_msgSend_IntPtr (Handle, Selector.GetHandle (selInitWithLayer), other.Handle); GC.KeepAlive (other); } else { - Messaging.IntPtr_objc_msgSendSuper_IntPtr (SuperHandle, Selector.GetHandle (selInitWithLayer), other.Handle); + unsafe { + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + Messaging.IntPtr_objc_msgSendSuper_IntPtr (&__objc_super__, Selector.GetHandle (selInitWithLayer), other.Handle); + GC.KeepAlive (this); + GC.KeepAlive (other); + } Clone (other); } MarkDirtyIfDerived (); diff --git a/src/CoreImage/CIFilter.cs b/src/CoreImage/CIFilter.cs index 6441ce736d2c..ee0f450c60d2 100644 --- a/src/CoreImage/CIFilter.cs +++ b/src/CoreImage/CIFilter.cs @@ -270,8 +270,12 @@ internal void SetHandle (string key, IntPtr handle) Messaging.void_objc_msgSend_IntPtr_IntPtr ( this.Handle, Selector.GetHandle ("setValue:forKey:"), handle, nsname); } else { - Messaging.void_objc_msgSendSuper_IntPtr_IntPtr ( - this.SuperHandle, Selector.GetHandle ("setValue:forKey:"), handle, nsname); + unsafe { + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + Messaging.void_objc_msgSendSuper_IntPtr_IntPtr ( + &__objc_super__, Selector.GetHandle ("setValue:forKey:"), handle, nsname); + GC.KeepAlive (this); + } } CFString.ReleaseNative (nsname); } @@ -283,8 +287,13 @@ internal IntPtr GetHandle (string key) if (IsDirectBinding) ret = Messaging.IntPtr_objc_msgSend_IntPtr (Handle, Selector.GetHandle ("valueForKey:"), nsname); - else - ret = Messaging.IntPtr_objc_msgSendSuper_IntPtr (SuperHandle, Selector.GetHandle ("valueForKey:"), nsname); + else { + unsafe { + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + ret = Messaging.IntPtr_objc_msgSendSuper_IntPtr (&__objc_super__, Selector.GetHandle ("valueForKey:"), nsname); + GC.KeepAlive (this); + } + } CFString.ReleaseNative (nsname); return ret; diff --git a/src/CoreImage/CIVector.cs b/src/CoreImage/CIVector.cs index 8270b1ecb85b..86ff2f54a7d3 100644 --- a/src/CoreImage/CIVector.cs +++ b/src/CoreImage/CIVector.cs @@ -63,7 +63,11 @@ public unsafe CIVector (nfloat [] values, nint count) : base (NSObjectFlag.Empty if (IsDirectBinding) { handle = Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (Handle, Selector.GetHandle ("initWithValues:count:"), (IntPtr) ptr, (IntPtr) count); } else { - handle = Messaging.IntPtr_objc_msgSendSuper_IntPtr_IntPtr (SuperHandle, Selector.GetHandle ("initWithValues:count:"), (IntPtr) ptr, (IntPtr) count); + unsafe { + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + handle = Messaging.IntPtr_objc_msgSendSuper_IntPtr_IntPtr (&__objc_super__, Selector.GetHandle ("initWithValues:count:"), (IntPtr) ptr, (IntPtr) count); + GC.KeepAlive (this); + } } InitializeHandle (handle, "initWithValues:count:"); } diff --git a/src/Foundation/NSHttpCookie.cs b/src/Foundation/NSHttpCookie.cs index ec2862dcb7fe..e79656e71503 100644 --- a/src/Foundation/NSHttpCookie.cs +++ b/src/Foundation/NSHttpCookie.cs @@ -123,7 +123,11 @@ void CreateCookie (string name, string value, string? path, string? domain, stri if (IsDirectBinding) { InitializeHandle (Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("initWithProperties:"), properties.Handle), "initWithProperties:", throwOnInitFailure); } else { - InitializeHandle (Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithProperties:"), properties.Handle), "initWithProperties:", throwOnInitFailure); + unsafe { + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + InitializeHandle (Messaging.IntPtr_objc_msgSendSuper_IntPtr (&__objc_super__, Selector.GetHandle ("initWithProperties:"), properties.Handle), "initWithProperties:", throwOnInitFailure); + GC.KeepAlive (this); + } } } } diff --git a/src/Foundation/NSInputStream.cs b/src/Foundation/NSInputStream.cs index e65843332aeb..14dc85346cd0 100644 --- a/src/Foundation/NSInputStream.cs +++ b/src/Foundation/NSInputStream.cs @@ -63,10 +63,10 @@ public unsafe nint Read (byte [] buffer, int offset, nuint len) static extern nint objc_msgSend (IntPtr handle, IntPtr sel, IntPtr buffer, nuint len); [DllImport (Messaging.LIBOBJC_DYLIB)] - static extern nint objc_msgSendSuper (IntPtr handle, IntPtr sel, IntPtr buffer, nuint len); + static extern unsafe nint objc_msgSendSuper (global::ObjCRuntime.ObjCSuper* handle, IntPtr sel, IntPtr buffer, nuint len); [Export ("read:maxLength:")] - public virtual nint Read (IntPtr buffer, nuint len) + public virtual unsafe nint Read (IntPtr buffer, nuint len) { if (buffer == IntPtr.Zero) throw new ArgumentNullException ("buffer"); @@ -74,7 +74,10 @@ public virtual nint Read (IntPtr buffer, nuint len) if (IsDirectBinding) { return objc_msgSend (this.Handle, Selector.GetHandle (selReadMaxLength), buffer, len); } else { - return objc_msgSendSuper (this.SuperHandle, Selector.GetHandle (selReadMaxLength), buffer, len); + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + var __result__ = objc_msgSendSuper (&__objc_super__, Selector.GetHandle (selReadMaxLength), buffer, len); + GC.KeepAlive (this); + return __result__; } } diff --git a/src/Foundation/NSObject2.cs b/src/Foundation/NSObject2.cs index f27d8abdd8fb..22498aeed364 100644 --- a/src/Foundation/NSObject2.cs +++ b/src/Foundation/NSObject2.cs @@ -77,7 +77,11 @@ namespace Foundation { /// if (IsDirectBinding) { /// Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); /// } else { - /// Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + /// unsafe { + /// var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + /// Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + /// } + /// GC.KeepAlive (this); /// } /// } /// ]]> @@ -115,56 +119,60 @@ internal interface INSObjectFactory { #if !COREBUILD // Allocated in native memory, so that it can be accessed from native code without having to deal with the GC. - // Also put objc_super here, because it simplifies code. // This is mirrored in runtime.h and the definition needs to be in sync. - struct NSObjectData { - // the layout here is important, the two first fields have to match the objc_super struct. + internal struct NSObjectData { public NativeHandle handle; - public NativeHandle classHandle; public NSObject.Flags flags; } - class NSObjectDataHandle : CriticalHandle { - bool invalidated; - public NSObjectDataHandle () - : base (IntPtr.Zero) + // This type wraps native memory that will track an NSObject, and free the native memory + // once the NSObject is finalized and completely gone / unresurrectable. It does so by + // creating a GCHandle that tracks the NSObject in question, and if this instance's + // finalizer is called, but the NSObject is still reachable, then re-schedule this instance's + // finalizer to run again later. + // This is similar to how NativeAOT handles the tagged memory returned by ObjectiveCMarshal.CreateReferenceTrackingHandle + // * https://github.com/AustinWise/runtime/blob/2bd10ad43df967950657ae0ade1f899dc1b18a41/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/ObjectiveCMarshal.NativeAot.cs#L15 + // * https://github.com/AustinWise/runtime/blob/2bd10ad43df967950657ae0ade1f899dc1b18a41/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/ObjectiveCMarshal.NativeAot.cs#L59-L71 + // * https://github.com/AustinWise/runtime/blob/2bd10ad43df967950657ae0ade1f899dc1b18a41/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/ObjectiveCMarshal.NativeAot.cs#L181-L185 + unsafe class NSObjectDataHandle : TrackedMemory { + public NSObjectData* Data { get => (NSObjectData*) Value; } + + public NSObjectDataHandle () : base ((nuint) sizeof (NSObjectData)) { - unsafe { - this.handle = (IntPtr) NativeMemory.AllocZeroed ((nuint) sizeof (NSObjectData)); - } } + } - public NSObjectDataHandle (IntPtr handle) - : base (handle) - { - } + class TrackedMemory { + GCHandle handle; - public void Invalidate () - { - invalidated = true; - } + public IntPtr Value { get; private set; } - public unsafe NSObjectData* Data { - get => (NSObjectData*) handle; + public unsafe TrackedMemory (nuint size) + { + Value = (IntPtr) NativeMemory.AllocZeroed (size); } - public override bool IsInvalid { - get => handle == IntPtr.Zero; + public unsafe void CreateHandle (NSObject trackedObject) + { + handle = GCHandle.Alloc (trackedObject, GCHandleType.WeakTrackResurrection); } - protected override bool ReleaseHandle () + ~TrackedMemory () { - if (handle != IntPtr.Zero) { - if (invalidated) { - // nothing to do here. - } else { - unsafe { - NativeMemory.Free ((void*) handle); - } - } + var handleAllocated = handle.IsAllocated; + if (handleAllocated && handle.Target is not null) { + // The NSObject instance isn't gone yet, we have to try again later. + GC.ReRegisterForFinalize (this); + return; } - handle = IntPtr.Zero; - return true; + + unsafe { + NativeMemory.Free ((void*) Value); + } + Value = IntPtr.Zero; + + if (handleAllocated) + handle.Free (); } } #endif @@ -195,51 +203,49 @@ public partial class NSObject : INativeObject /// The assembly containing the platform-specific Foundation types. public static readonly Assembly PlatformAssembly = typeof (NSObject).Assembly; - // This is exclusively for Mono - unsafe NSObjectData* __data_for_mono; // Read directly from several places in the runtime - - unsafe NativeHandle handle { - get => GetData ()->handle; - set => GetData ()->handle = value; - } +#pragma warning disable CS8618 // "Non-nullable field '...' must contain a non-null value when exiting constructor.": this field is always non-null, because NSObject.Initialize is called before anything else is done. + static ConditionalWeakTable data_table; +#pragma warning restore CS8618 // The NSObjectData contains some data we want to keep in native memory, so that it can be accessed // safely from native code without having to make sure the GC doesn't move the memory around. Among // other things, this means it's accessible from threads that has never seen/run managed code without // having to attach those threads to to the managed runtime. - NSObjectDataHandle? data_handle; + IntPtr /* unsafe NSObjectData* */ __data; // Read directly from several places in the runtime - internal unsafe NSObjectData* GetData () - { - var rv = AllocateData ().Data; - - if (rv is null) { - // Throwing an exception here is better than returning a null pointer, because that will crash the process when the pointer is dereferenced - // (and none of the callers can do anything useful with a null pointer anyway). - throw new ObjectDisposedException ($"This object (of type {GetType ().Name}) does not have a data pointer anymore, possibly because of a race condition. Please file a bug at https://github.com/dotnet/macios/issues."); - } +#pragma warning disable CS8618 // "Non-nullable field '...' must contain a non-null value when exiting constructor.": this field is always non-null, because NSObject.Initialize is called before anything else is done. + static ConditionalWeakTable super_map; +#pragma warning restore CS8618 - return rv; + unsafe NativeHandle handle { + get => GetData ()->handle; + set => GetData ()->handle = value; } - unsafe NSObjectDataHandle AllocateData () + internal unsafe NSObjectData* GetData () { - var dh = data_handle; - if (dh is not null) - return dh; - - var data = new NSObjectDataHandle (); - var previousValue = Interlocked.CompareExchange (ref data_handle, data, null); - if (previousValue is not null) { - // somebody beat us to the allocation and assignment. - data.Dispose (); - return previousValue; - } - - if (!Runtime.IsCoreCLR) // This condition (and the assignment to __handle_for_mono if applicable) is trimmed away by the linker. - __data_for_mono = data.Data; + var data = __data; + if (data != IntPtr.Zero) + return (NSObjectData*) data; - return data; + if (Runtime.IsCoreCLR) { + data = (IntPtr) Runtime.GetTaggedMemory (this); + __data = data; // Runtime.GetTaggedMemory will always return the same pointer for the same object, so no synchronization is needed here (redundant writes are benign). + return (NSObjectData*) data; + } else { + var data_handle = new NSObjectDataHandle (); + var existing_data = Interlocked.CompareExchange (ref __data, (IntPtr) data_handle.Data, IntPtr.Zero); + if (existing_data != IntPtr.Zero) { + // return the existing data, the GC will collect the other one we just created + return (NSObjectData*) existing_data; + } + // tell the data handle we just created to track us + data_handle.CreateHandle (this); + // make sure the data isn't freed before this NSObject is collected, but also + // that it is freed after this NSObject is collected. + data_table.Add (this, data_handle); + return data_handle.Data; + } } unsafe Flags flags { @@ -397,16 +403,29 @@ internal static IntPtr CreateNSObject (IntPtr type_gchandle, IntPtr handle, Flag } } +#if !XAMCORE_5_0 unsafe NativeHandle GetSuper () { - var data = GetData (); - if (data->classHandle == NativeHandle.Zero) - data->classHandle = ClassHandle; - return (IntPtr) (&data->handle); + var memory = super_map.GetValue (this, (obj) => { + unsafe { + var memory = new TrackedMemory ((nuint) sizeof (objc_super)); + memory.CreateHandle (obj); + return memory; + } + }); + objc_super* sup = (objc_super*) memory.Value; + if (sup->ClassHandle == NativeHandle.Zero) + sup->ClassHandle = ClassHandle; + sup->Handle = handle; + return memory.Value; } +#endif // !XAMCORE_5_0 internal static NativeHandle Initialize () { + if (!Runtime.IsCoreCLR) + data_table = new ConditionalWeakTable (); + super_map = new ConditionalWeakTable (); return class_ptr; } @@ -598,13 +617,19 @@ public virtual bool ConformsToProtocol (NativeHandle protocol) if (is_wrapper) { does = Messaging.bool_objc_msgSend_IntPtr (this.Handle, selConformsToProtocolHandle, protocol) != 0; } else { - does = Messaging.bool_objc_msgSendSuper_IntPtr (this.SuperHandle, selConformsToProtocolHandle, protocol) != 0; + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + does = Messaging.bool_objc_msgSendSuper_IntPtr (&__objc_super__, selConformsToProtocolHandle, protocol) != 0; + } } #else if (is_wrapper) { does = Messaging.bool_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle (selConformsToProtocol), protocol) != 0; } else { - does = Messaging.bool_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle (selConformsToProtocol), protocol) != 0; + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + does = Messaging.bool_objc_msgSendSuper_IntPtr (&__objc_super__, Selector.GetHandle (selConformsToProtocol), protocol) != 0; + } } #endif @@ -724,16 +749,35 @@ public NSObject DangerousAutorelease () return this; } +#if !XAMCORE_5_0 /// Handle used to represent the methods in the base class for this . /// An opaque pointer, represents an Objective-C objc_super object pointing to our base class. /// - /// This property is used to access members of a base class. - /// This is typically used when you call any of the Messaging - /// methods to invoke methods that were implemented in your base - /// class, instead of invoking the implementation in the current - /// class. + /// + /// This property is used to access members of a base class. + /// This is typically used when you call any of the Messaging + /// methods to invoke methods that were implemented in your base + /// class, instead of invoking the implementation in the current + /// class. + /// + /// + /// This property is obsolete; use the struct instead: + /// + /// + /// + /// /// [EditorBrowsable (EditorBrowsableState.Never)] +#if NET11_0_OR_GREATER + [Obsolete ("Use 'ObjCSuper' instead.")] +#endif public NativeHandle SuperHandle { get { if (handle == IntPtr.Zero) @@ -742,6 +786,7 @@ public NativeHandle SuperHandle { return GetSuper (); } } +#endif // !XAMCORE_5_0 /// Handle (pointer) to the unmanaged object representation. /// A pointer. @@ -1005,8 +1050,12 @@ public void SetValueForKeyPath (NativeHandle handle, NSString keyPath) ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_NativeHandle (this.Handle, Selector.GetHandle ("setValue:forKeyPath:"), handle, keyPath.Handle); GC.KeepAlive (keyPath); } else { - ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle_NativeHandle (this.SuperHandle, Selector.GetHandle ("setValue:forKeyPath:"), handle, keyPath.Handle); - GC.KeepAlive (keyPath); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle_NativeHandle (&__objc_super__, Selector.GetHandle ("setValue:forKeyPath:"), handle, keyPath.Handle); + GC.KeepAlive (this); + GC.KeepAlive (keyPath); + } } } @@ -1115,62 +1164,10 @@ protected virtual void Dispose (bool disposing) ReleaseManagedRef (); } else { NSObject_Disposer.Add (this); - RecreateDataHandle (); } } } - void RecreateDataHandle () - { - // OK, this code is _weird_. - // We need to delay the deletion of the native memory pointed to by data_handle until - // after this instance has been collected. A CriticalHandle seems to fit this purpose like a glove, until - // you realize that a CriticalHandle is only kept alive until the parent object _becomes finalizable_, - // not _is collected_, which is very different - in other words, resurrected objects don't keep CriticalHandles - // they contain alive. This is a problem because every single managed NSObject instance is resurrected, and we - // need the native memory to stay alive after resurrection. - // - // So this solution depends on a few bits: - // * At this point, this instance may have become finalizable, but the native memory shouldn't have been freed yet. - // * The original NSObjectDataHandle (aka CriticalHandle) will be collected in this/upcoming GC cycle, and can't - // be trusted to keep the native memory alive anymore. - // * So we just create a new one, pointing to the same native memory, and replace the original NSObjectDataHandle (aka - // CriticalHandle) with it - // * This works, because since this instance has become / will become resurrected, it's not finalizable anymore, - // and it will keep the new NSObjectDataHandle instance (and the native memory it points to) alive. - // * Now if this instance is deemed finalizable, and then resurrected *again*, bad things will likely happen. This - // is a bit more unlikely though, because we don't re-register the finalizer for execution, so unless somebody - // else does that, it's quite unlikely this instance will become resurrected a second time. - var previous_data = data_handle; - if (previous_data is null) { - var msg = $"This object (of type {GetType ().Name}) does not have an existing data pointer, possibly because of a race condition. Please file a bug at https://github.com/dotnet/macios/issues."; -#if CONSISTENCY_CHECKS - throw new InvalidOperationException (msg); -#else - Runtime.NSLog (msg); - return; -#endif - } - - unsafe { - data_handle = new NSObjectDataHandle ((IntPtr) previous_data.Data); - } - - if (previous_data.IsInvalid) { - var msg = $"This object (of type {GetType ().Name}) does not have valid data pointer, possibly because of a race condition. Please file a bug at https://github.com/dotnet/macios/issues."; -#if CONSISTENCY_CHECKS - throw new InvalidOperationException (msg); -#else - Runtime.NSLog (msg); - return; -#endif - } - - previous_data.Invalidate (); - // Don't dispose previous_data, because another thread might be referencing it, and trying to access its pointer - which is still valid. - // The GC will dispose of previous_data when its not accessible anymore. - } - [Register ("__NSObject_Disposer")] [Preserve (AllMembers = true)] internal class NSObject_Disposer : NSObject { diff --git a/src/Foundation/NSThread.cs b/src/Foundation/NSThread.cs index 02105c44692c..7e82d5ef2f2b 100644 --- a/src/Foundation/NSThread.cs +++ b/src/Foundation/NSThread.cs @@ -37,14 +37,21 @@ public static double Priority { [DllImport ("__Internal")] static extern NativeHandle xamarin_init_nsthread (IntPtr handle, byte is_direct_binding, IntPtr target, IntPtr selector, IntPtr argument); - NativeHandle InitNSThread (NSObject target, Selector selector, NSObject? argument) + unsafe NativeHandle InitNSThread (NSObject target, Selector selector, NSObject? argument) { if (target is null) ThrowHelper.ThrowArgumentNullException (nameof (target)); if (selector is null) ThrowHelper.ThrowArgumentNullException (nameof (selector)); - IntPtr result = xamarin_init_nsthread (IsDirectBinding ? this.Handle : this.SuperHandle, IsDirectBinding.AsByte (), target.Handle, selector.Handle, argument.GetHandle ()); + IntPtr result; + if (IsDirectBinding) { + result = xamarin_init_nsthread (this.Handle, IsDirectBinding.AsByte (), target.Handle, selector.Handle, argument.GetHandle ()); + } else { + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + result = xamarin_init_nsthread ((IntPtr) (&__objc_super__), IsDirectBinding.AsByte (), target.Handle, selector.Handle, argument.GetHandle ()); + GC.KeepAlive (this); + } GC.KeepAlive (target); GC.KeepAlive (selector); GC.KeepAlive (argument); diff --git a/src/Foundation/NSUrlSessionHandler.cs b/src/Foundation/NSUrlSessionHandler.cs index 2c0af8202220..e34081682faa 100644 --- a/src/Foundation/NSUrlSessionHandler.cs +++ b/src/Foundation/NSUrlSessionHandler.cs @@ -134,6 +134,15 @@ static NSUrlSessionConfiguration CreateConfig () // Double.MaxValue does not work, so default to 24 hours config.TimeoutIntervalForRequest = 24 * 60 * 60; config.TimeoutIntervalForResource = 24 * 60 * 60; + + // Disable shared credential storage so credentials we pass with UseCredential in DidReceiveChallenge dont get saved in + // the SharedCredentialStorage so (native) NSUrlSession can't try to authenticate later requests by itself using old credentials + // incluiding redirects, and then our managed DidReceiveChallenge delegate may not get called at all. We already manage + // the credential flow in DidReceiveChallenge and the Credentials property. The switch is just a compat in case we + // someone needs to go back to the old behaviour. + var useSharedCredentialStorage = AppContext.TryGetSwitch ("Foundation.NSUrlSessionHandler.UseSharedCredentialStorage", out var useSharedStorage) && useSharedStorage; + if (!useSharedCredentialStorage) + config.URLCredentialStorage = null; return config; } @@ -1029,7 +1038,30 @@ void WillCacheResponseImpl (NSUrlSession session, NSUrlSessionDataTask dataTask, [Preserve (Conditional = true)] public override void WillPerformHttpRedirection (NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action completionHandler) { - completionHandler (sessionHandler.AllowAutoRedirect ? newRequest : null!); + if (!sessionHandler.AllowAutoRedirect) { + completionHandler (null!); + return; + } + + var inflight = GetInflightData (task); + + if (inflight is null) { + completionHandler (null!); + return; + } + + inflight.HasRedirected = true; + + if (newRequest.Url?.AbsoluteString is string redirectUrl) { + inflight.CurrentRequestUrl = redirectUrl; + + if (Uri.TryCreate (redirectUrl, UriKind.Absolute, out var redirectUri)) + inflight.HasCrossOriginRedirect |= IsCrossOriginRedirect (inflight.RequestUrl, redirectUri); + else + inflight.HasCrossOriginRedirect = true; + } + + completionHandler (newRequest); } [Preserve (Conditional = true)] @@ -1127,6 +1159,22 @@ void DidReceiveChallengeImpl (NSUrlSession session, NSUrlSessionTask task, NSUrl } } + // Detect redirect from the task as a fallback in case + // WillPerformHttpRedirection has not updated infligth state yet + if (!inflight.HasRedirected) { + var originalUrl = task.OriginalRequest?.Url?.AbsoluteString; + var currentUrl = task.CurrentRequest?.Url?.AbsoluteString; + if (originalUrl is not null && currentUrl is not null + && !string.Equals (originalUrl, currentUrl, StringComparison.Ordinal)) { + inflight.HasRedirected = true; + inflight.CurrentRequestUrl = currentUrl; + if (Uri.TryCreate (currentUrl, UriKind.Absolute, out var redirectUri)) + inflight.HasCrossOriginRedirect |= IsCrossOriginRedirect (inflight.RequestUrl, redirectUri); + else + inflight.HasCrossOriginRedirect = true; + } + } + if (sessionHandler.Credentials is not null && TryGetAuthenticationType (challenge.ProtectionSpace, out var authType)) { NetworkCredential? credentialsToUse = null; if (authType != RejectProtectionSpaceAuthType) { @@ -1147,8 +1195,9 @@ void DidReceiveChallengeImpl (NSUrlSession session, NSUrlSessionTask task, NSUrl var nsurlRespose = challenge.FailureResponse as NSHttpUrlResponse; var responseIsUnauthorized = (nsurlRespose is null) ? false : nsurlRespose.StatusCode == (int) HttpStatusCode.Unauthorized && challenge.PreviousFailureCount > 0; if (!responseIsUnauthorized) { - var uri = inflight.Request.RequestUri!; - credentialsToUse = sessionHandler.Credentials.GetCredential (uri, authType); + var uri = GetCredentialLookupUri (task, inflight); + if (ShouldLookupCredentials (sessionHandler.Credentials, inflight)) + credentialsToUse = sessionHandler.Credentials.GetCredential (uri, authType); } } @@ -1165,6 +1214,45 @@ void DidReceiveChallengeImpl (NSUrlSession session, NSUrlSessionTask task, NSUrl } } + static Uri GetCredentialLookupUri (NSUrlSessionTask task, InflightData inflight) + { + var currentRequestUrl = task.CurrentRequest?.Url?.AbsoluteString; + if (currentRequestUrl is not null && Uri.TryCreate (currentRequestUrl, UriKind.Absolute, out var currentRequestUri)) + return currentRequestUri; + + if (Uri.TryCreate (inflight.CurrentRequestUrl, UriKind.Absolute, out var inflightCurrentRequestUri)) + return inflightCurrentRequestUri; + + return inflight.Request.RequestUri!; + } + + static bool ShouldLookupCredentials (ICredentials credentials, InflightData inflight) + { + if (credentials is CredentialCache) + return true; + + if (!inflight.HasRedirected) + return true; + + // We are now matching .NET handlers (SocketsHttpHandler and WinHttpHandler) redirect behavior by dropping non CredentialCache credentials after a redirect + // Ref: + // https://github.com/dotnet/runtime/blob/eb5503a1f0dc40ee7b73eb79a039eb143ee25038/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs#L541-L547 + // https://github.com/dotnet/runtime/blob/eb5503a1f0dc40ee7b73eb79a039eb143ee25038/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RedirectHandler.cs#L52-L87 + // Provide a way for customers to opt into the old behavior for same origin redirects. + var allowSameOriginRedirectCredentials = AppContext.TryGetSwitch ("Foundation.NSUrlSessionHandler.AllowSameOriginRedirectCredentials", out var allowRedirectCred) && allowRedirectCred; + return allowSameOriginRedirectCredentials && !inflight.HasCrossOriginRedirect; + } + + static bool IsCrossOriginRedirect (string originalRequestUrl, Uri currentRequestUri) + { + if (!Uri.TryCreate (originalRequestUrl, UriKind.Absolute, out var originalRequestUri)) + return true; + + return !string.Equals (originalRequestUri.Scheme, currentRequestUri.Scheme, StringComparison.OrdinalIgnoreCase) + || !string.Equals (originalRequestUri.IdnHost, currentRequestUri.IdnHost, StringComparison.OrdinalIgnoreCase) + || originalRequestUri.Port != currentRequestUri.Port; + } + static readonly string RejectProtectionSpaceAuthType = "reject"; static bool TryGetAuthenticationType (NSUrlProtectionSpace protectionSpace, [NotNullWhen (true)] out string? authenticationType) @@ -1175,15 +1263,19 @@ static bool TryGetAuthenticationType (NSUrlProtectionSpace protectionSpace, [Not authenticationType = "basic"; } else if (protectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodHTTPDigest) { authenticationType = "digest"; - } else if (protectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNegotiate || - protectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodHTMLForm) { - // Want to reject this authentication type to allow the next authentication method in the request to - // be used. - authenticationType = RejectProtectionSpaceAuthType; - } else { - // ServerTrust, ClientCertificate or Default. + } else if (protectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust || + protectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodClientCertificate) { + // ServerTrust and ClientCertificate are handled earlier in DidReceiveChallengeImpl, + // so we should not reach here for these types. Return false just in case. authenticationType = null; return false; + } else { + // For any other authentication method (Negotiate, HTMLForm, Bearer, etc.), + // reject this protection space to allow the next authentication method in the + // request to be tried. This is important when the server advertises multiple + // WWW-Authenticate challenges (e.g. Bearer before Basic) - rejecting unsupported + // methods allows fallback to one we can handle. + authenticationType = RejectProtectionSpaceAuthType; } return true; } @@ -1192,6 +1284,9 @@ static bool TryGetAuthenticationType (NSUrlProtectionSpace protectionSpace, [Not class InflightData { public readonly object Lock = new object (); public string RequestUrl { get; set; } + public string CurrentRequestUrl { get; set; } + public bool HasRedirected { get; set; } + public bool HasCrossOriginRedirect { get; set; } public TaskCompletionSource CompletionSource { get; } = new TaskCompletionSource (TaskCreationOptions.RunContinuationsAsynchronously); public CancellationToken CancellationToken { get; set; } @@ -1210,6 +1305,7 @@ class InflightData { public InflightData (string requestUrl, CancellationToken cancellationToken, HttpRequestMessage request) { RequestUrl = requestUrl; + CurrentRequestUrl = requestUrl; CancellationToken = cancellationToken; Request = request; } diff --git a/src/Foundation/NSUuid.cs b/src/Foundation/NSUuid.cs index e21c0c9a93fc..ef3ef77e8cca 100644 --- a/src/Foundation/NSUuid.cs +++ b/src/Foundation/NSUuid.cs @@ -26,7 +26,9 @@ public NSUuid (byte [] bytes) : base (NSObjectFlag.Empty) if (IsDirectBinding) { InitializeHandle (Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("initWithUUIDBytes:"), ptr), "initWithUUIDBytes:"); } else { - InitializeHandle (Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithUUIDBytes:"), ptr), "initWithUUIDBytes:"); + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + InitializeHandle (Messaging.IntPtr_objc_msgSendSuper_IntPtr (&__objc_super__, Selector.GetHandle ("initWithUUIDBytes:"), ptr), "initWithUUIDBytes:"); + GC.KeepAlive (this); } } } diff --git a/src/GameController/GCMouse.cs b/src/GameController/GCMouse.cs index 1238b59171b5..47ac65fb8ca6 100644 --- a/src/GameController/GCMouse.cs +++ b/src/GameController/GCMouse.cs @@ -16,8 +16,12 @@ public GCMouse (NSCoder coder) : base (NSObjectFlag.Empty) InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("initWithCoder:"), coder.Handle), "initWithCoder:"); GC.KeepAlive (coder); } else { - InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithCoder:"), coder.Handle), "initWithCoder:"); - GC.KeepAlive (coder); + unsafe { + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (&__objc_super__, Selector.GetHandle ("initWithCoder:"), coder.Handle), "initWithCoder:"); + GC.KeepAlive (coder); + GC.KeepAlive (this); + } } } @@ -33,7 +37,11 @@ public virtual void EncodeTo (NSCoder encoder) if (IsDirectBinding) { global::ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle (this.Handle, Selector.GetHandle ("encodeWithCoder:"), encoder__handle__); } else { - global::ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle (this.SuperHandle, Selector.GetHandle ("encodeWithCoder:"), encoder__handle__); + unsafe { + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + global::ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle (&__objc_super__, Selector.GetHandle ("encodeWithCoder:"), encoder__handle__); + GC.KeepAlive (this); + } } GC.KeepAlive (encoder); } diff --git a/src/GameplayKit/GKHybridStrategist.cs b/src/GameplayKit/GKHybridStrategist.cs index 053ac320a92c..f59ed23733a9 100644 --- a/src/GameplayKit/GKHybridStrategist.cs +++ b/src/GameplayKit/GKHybridStrategist.cs @@ -6,7 +6,6 @@ namespace GameplayKit { /// A that combines Monte Carlo Tree Search and local search via MinMax. /// To be added. - /// Apple documentation for GKHybridStrategist [Register ("GKHybridStrategist", SkipRegistration = true)] [UnsupportedOSPlatform ("macos")] [SupportedOSPlatform ("maccatalyst")] diff --git a/src/MLCompute/MLHelpers.cs b/src/MLCompute/MLHelpers.cs index 8c18ed336c83..4063daf6c391 100644 --- a/src/MLCompute/MLHelpers.cs +++ b/src/MLCompute/MLHelpers.cs @@ -10,6 +10,8 @@ namespace MLCompute { public static class MLCActivationTypeExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCActivationTypeDebugDescription (MLCActivationType activationType); public static string? GetDebugDescription (this MLCActivationType self) @@ -25,6 +27,8 @@ public static class MLCActivationTypeExtensions { public static class MLCArithmeticOperationExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCArithmeticOperationDebugDescription (MLCArithmeticOperation operation); public static string? GetDebugDescription (this MLCArithmeticOperation self) @@ -40,6 +44,8 @@ public static class MLCArithmeticOperationExtensions { public static class MLCPaddingPolicyExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCPaddingPolicyDebugDescription (MLCPaddingPolicy paddingPolicy); public static string? GetDebugDescription (this MLCPaddingPolicy self) @@ -55,6 +61,8 @@ public static class MLCPaddingPolicyExtensions { public static class MLCLossTypeExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCLossTypeDebugDescription (MLCLossType lossType); public static string? GetDebugDescription (this MLCLossType self) @@ -70,6 +78,8 @@ public static class MLCLossTypeExtensions { public static class MLCReductionTypeExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCReductionTypeDebugDescription (MLCReductionType reductionType); public static string? GetDebugDescription (this MLCReductionType self) @@ -85,6 +95,8 @@ public static class MLCReductionTypeExtensions { public static class MLCPaddingTypeExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCPaddingTypeDebugDescription (MLCPaddingType paddingType); public static string? GetDebugDescription (this MLCPaddingType self) @@ -100,6 +112,8 @@ public static class MLCPaddingTypeExtensions { public static class MLCConvolutionTypeExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCConvolutionTypeDebugDescription (MLCConvolutionType convolutionType); public static string? GetDebugDescription (this MLCConvolutionType self) @@ -115,6 +129,8 @@ public static class MLCConvolutionTypeExtensions { public static class MLCPoolingTypeExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCPoolingTypeDebugDescription (MLCPoolingType poolingType); public static string? GetDebugDescription (this MLCPoolingType self) @@ -130,6 +146,8 @@ public static class MLCPoolingTypeExtensions { public static class MLCSoftmaxOperationExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCSoftmaxOperationDebugDescription (MLCSoftmaxOperation operation); public static string? GetDebugDescription (this MLCSoftmaxOperation self) @@ -145,6 +163,8 @@ public static class MLCSoftmaxOperationExtensions { public static class MLCSampleModeExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCSampleModeDebugDescription (MLCSampleMode mode); public static string? GetDebugDescription (this MLCSampleMode self) @@ -160,6 +180,8 @@ public static class MLCSampleModeExtensions { public static class MLCLstmResultModeExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCLSTMResultModeDebugDescription (MLCLstmResultMode mode); public static string? GetDebugDescription (this MLCLstmResultMode self) @@ -175,6 +197,8 @@ public static class MLCLstmResultModeExtensions { public static class MLCComparisonOperationExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCComparisonOperationDebugDescription (MLCComparisonOperation operation); public static string? GetDebugDescription (this MLCComparisonOperation self) @@ -190,6 +214,8 @@ public static class MLCComparisonOperationExtensions { public static class MLCGradientClippingTypeExtensions { [DllImport (Constants.MLComputeLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern /* NSString */ IntPtr MLCGradientClippingTypeDebugDescription (MLCGradientClippingType gradientClippingType); public static string? GetDebugDescription (this MLCGradientClippingType self) diff --git a/src/Makefile b/src/Makefile index 8fb8a3f67808..0fb0bcadc9d8 100644 --- a/src/Makefile +++ b/src/Makefile @@ -67,6 +67,8 @@ endif DOTNET_GENERATOR_FLAGS=$(GENERATOR_FLAGS) --lib=$(DOTNET_BCL_DIR) -attributelib:$(DOTNET_BINDING_ATTRIBUTES) $(DOTNET_REFERENCES) DOTNET_GENERATOR=$(DOTNET_BUILD_DIR)/bgen/bgen DOTNET_BINDING_ATTRIBUTES=$(DOTNET_BUILD_DIR)/Xamarin.Apple.BindingAttributes.dll +APPLE_DOC_READER=$(TOP)/packages/appledocreader.$(ADR_RUNTIME_IDENTIFIER)/$(ADR_NUGET_VERSION)/tools/any/$(ADR_RUNTIME_IDENTIFIER)/AppleDocReader +APPLE_DOC_READER_LOCK=$(BUILD_DIR)/.appledocreader.lock # # Specific warnings that we want reported as errors by generator @@ -346,17 +348,18 @@ $(DOTNET_DESTDIR)/$($(2)_NUGET_REF_NAME)/ref/$(DOTNET_TFM)/Microsoft.$(1).dll: $ $(DOTNET_DESTDIR)/$($(2)_NUGET_REF_NAME)/ref/$(DOTNET_TFM)/Microsoft.$(1).xml: $($(2)_DOTNET_BUILD_DIR)/doc/Microsoft.$(1).xml | $(DOTNET_DESTDIR)/$($(2)_NUGET_REF_NAME)/ref/$(DOTNET_TFM) $$(Q) $(CP) $$< $$@ -ifndef IS_LINUX +ifndef NO_XCODE +# AppleDocReader backs up a shared Xcode SQLite database, so serialize invocations. $($(2)_DOTNET_BUILD_DIR)/doc/Microsoft.$(1).xml: $($(2)_DOTNET_BUILD_DIR)/ref/Microsoft.$(1).xml $($(2)_DOTNET_BUILD_DIR)/ref/Microsoft.$(1).dll build/.build-adr-stamp | $($(2)_DOTNET_BUILD_DIR)/doc - $$(Q_GEN) $(TOP)/packages/appledocreader.$(ADR_RUNTIME_IDENTIFIER)/$(ADR_NUGET_VERSION)/tools/any/$(ADR_RUNTIME_IDENTIFIER)/AppleDocReader inject docs --assembly="$(abspath $($(2)_DOTNET_BUILD_DIR)/ref/Microsoft.$(1).dll)" --input="$(abspath $($(2)_DOTNET_BUILD_DIR)/ref/Microsoft.$(1).xml)" --output="$(abspath $$@)" --xcode="$(DEVELOPER_DIR)/../.." --runtimeDll="$(DOTNET_BCL_DIR)/System.Runtime.dll" -f + $$(Q_GEN) /usr/bin/lockf "$(APPLE_DOC_READER_LOCK)" "$(APPLE_DOC_READER)" inject docs --assembly="$(abspath $($(2)_DOTNET_BUILD_DIR)/ref/Microsoft.$(1).dll)" --input="$(abspath $($(2)_DOTNET_BUILD_DIR)/ref/Microsoft.$(1).xml)" --output="$(abspath $$@)" --xcode="$(DEVELOPER_DIR)/../.." --runtimeDll="$(DOTNET_BCL_DIR)/System.Runtime.dll" -f else -# On Linux, skip AppleDocReader (macOS-only tool) and just copy the XML +# Without Xcode, skip AppleDocReader and just copy the XML $($(2)_DOTNET_BUILD_DIR)/doc/Microsoft.$(1).xml: $($(2)_DOTNET_BUILD_DIR)/ref/Microsoft.$(1).xml | $($(2)_DOTNET_BUILD_DIR)/doc $(Q) $(CP) $$< $$@ endif endef -ifndef IS_LINUX +ifndef NO_XCODE build/.build-adr-stamp: $(MAKE) -C $(TOP)/tools/adr $(Q) touch $@ @@ -435,6 +438,15 @@ $($(2)_DOTNET_BUILD_DIR)/Microsoft.$(1).rsp: Makefile frameworks.sources $(RSP_D $($(2)_DOTNET_BUILD_DIR)/$(4)/Microsoft.$(1)%dll $($(2)_DOTNET_BUILD_DIR)/$(4)/Microsoft.$(1)%pdb $($(2)_DOTNET_BUILD_DIR)/ref/Microsoft.$(1)%dll $($(2)_DOTNET_BUILD_DIR)/ref/Microsoft.$(1)%xml: $$($(2)_DOTNET_PLATFORM_ASSEMBLY_DEPENDENCIES) $$(ROSLYN_GENERATOR) $$(ROSLYN_ANALYZER) | $$($(2)_DOTNET_PLATFORM_ASSEMBLY_DIR_DEPENDENCIES) $$(call Q_PROF_CSC,dotnet) $(DOTNET_CSC) @$($(2)_DOTNET_BUILD_DIR)/Microsoft.$(1).rsp +ifdef SERIALIZE_CSC +# This is to serialize the csc commands for the platform assembly. The platform assembly takes a while to compile (maxing out the CPU), and csc is already multi-threaded, which +# means that if we're running multiple long csc tasks simultaneously, the CPU of the machine will get absolutely thrashed. csc (aka Roslyn) isn't exactly a cheapskate with memory either... +# It looks a bit weird, but the idea is that in this template, every platform assembly depends on the assembly from the previous template expansion. +# It's opt-in, because it slows down the build a bit. +$($(2)_DOTNET_BUILD_DIR)/$(4)/Microsoft.$(1).dll: $(LAST_DLL) +LAST_DLL=$($(2)_DOTNET_BUILD_DIR)/$(4)/Microsoft.$(1).dll +endif + dotnet-$(3):: $($(2)_DOTNET_BUILD_DIR)/$(4)/Microsoft.$(1).dll DOTNET_TARGETS_$(3) += \ diff --git a/src/Metal/MTLEnums.cs b/src/Metal/MTLEnums.cs index b6f15a43630f..19ea79b3fc6f 100644 --- a/src/Metal/MTLEnums.cs +++ b/src/Metal/MTLEnums.cs @@ -2358,6 +2358,8 @@ public enum MTLIOCompressionStatus : long { [Mac (13, 0), iOS (16, 0), MacCatalyst (16, 0), TV (16, 0)] [Native] [ErrorDomain ("MTLIOErrorDomain")] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] public enum MTLIOError : long { UrlInvalid = 1, Internal = 2, @@ -2466,6 +2468,8 @@ public enum MTL4BlendState : long { [Mac (26, 0), iOS (26, 0), MacCatalyst (26, 0), TV (26, 0)] [Native] [ErrorDomain ("MTL4CommandQueueErrorDomain")] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] public enum MTL4CommandQueueError : long { None = 0, Timeout = 1, @@ -2599,6 +2603,8 @@ public enum MTLDeviceError : long { [Mac (26, 0), iOS (26, 0), MacCatalyst (26, 0), TV (26, 0)] [Native] [ErrorDomain ("MTLTensorDomain")] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] public enum MTLTensorError : long { None = 0, InternalError = 1, diff --git a/src/Metal/MTLIOCompression.cs b/src/Metal/MTLIOCompression.cs index cfe3b53c6663..460f5dc6e484 100644 --- a/src/Metal/MTLIOCompression.cs +++ b/src/Metal/MTLIOCompression.cs @@ -15,6 +15,8 @@ public class MTLIOCompressionContext : DisposableObject { MTLIOCompressionContext (NativeHandle handle, bool owns) : base (handle, owns) { } [DllImport (Constants.MetalLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern unsafe void MTLIOCompressionContextAppendData (IntPtr context, void* data, nuint size); unsafe void AppendData (void* data, nuint size) @@ -47,6 +49,8 @@ public void AppendData (NSData data) } [DllImport (Constants.MetalLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] // [return: NullAllowed] static extern IntPtr MTLIOCreateCompressionContext (IntPtr path, long type, long chunkSize); @@ -74,6 +78,8 @@ protected override void Dispose (bool disposing) } [DllImport (Constants.MetalLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern long MTLIOFlushAndDestroyCompressionContext (IntPtr context); public MTLIOCompressionStatus FlushAndDestroy () @@ -86,6 +92,8 @@ public MTLIOCompressionStatus FlushAndDestroy () } [DllImport (Constants.MetalLibrary)] + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] static extern nint MTLIOCompressionContextDefaultChunkSize (); public static nint DefaultChunkSize => MTLIOCompressionContextDefaultChunkSize (); diff --git a/src/NewsstandKit/Compat.cs b/src/NewsstandKit/Compat.cs index 734b489d5cf3..4d5c23371eef 100644 --- a/src/NewsstandKit/Compat.cs +++ b/src/NewsstandKit/Compat.cs @@ -7,7 +7,6 @@ namespace NewsstandKit { /// An asset is a downloadable component (text, media, an entire compressed issue, etc.) of a Newsstand application. /// To be added. - /// Apple documentation for NKAssetDownload [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("The NewsstandKit framework has been removed from iOS.")] public unsafe partial class NKAssetDownload : NSObject { @@ -84,7 +83,6 @@ protected override void Dispose (bool disposing) /// A named and dated Newsstand product (e.g., an issue of a particular magazine). /// To be added. - /// Apple documentation for NKIssue [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("The NewsstandKit framework has been removed from iOS.")] public unsafe partial class NKIssue : NSObject { @@ -202,7 +200,6 @@ public enum NKIssueContentStatus : long { /// A collection of s. /// To be added. - /// Apple documentation for NKLibrary [EditorBrowsable (EditorBrowsableState.Never)] [Obsolete ("The NewsstandKit framework has been removed from iOS.")] public unsafe partial class NKLibrary : NSObject { diff --git a/src/ObjCBindings/ExportTag.cs b/src/ObjCBindings/ExportTag.cs index 7172cc573a55..ca3d9b7d0b13 100644 --- a/src/ObjCBindings/ExportTag.cs +++ b/src/ObjCBindings/ExportTag.cs @@ -1,3 +1,4 @@ +using System.ComponentModel; using System.Diagnostics.CodeAnalysis; #nullable enable @@ -169,18 +170,10 @@ public enum Property : Int64 { CustomMarshalDirective = 1 << 5, /// - /// Apply to strings parameters that are merely retained or assigned, - /// not copied this is an exception as it is advised in the coding - /// standard for Objective-C to avoid this, but a few properties do use - /// this. Use this falg for properties flagged with `retain' or - /// `assign', which look like this: - /// - /// @property (retain) NSString foo; - /// @property (assign) NSString assigned; - /// - /// This forced the generator to create an NSString before calling the - /// API instead of using the fast string marshalling code. + /// This flag is obsolete and has no effect. Zero-copy string marshaling is no longer supported. /// + [EditorBrowsable (EditorBrowsableState.Never)] + [Obsolete ("Zero-copy string marshaling is no longer supported. This flag has no effect.")] DisableZeroCopy = 1 << 6, /// diff --git a/src/ObjCRuntime/DynamicRegistrar.cs b/src/ObjCRuntime/DynamicRegistrar.cs index 93dc571ced6b..0c27e3d8130f 100644 --- a/src/ObjCRuntime/DynamicRegistrar.cs +++ b/src/ObjCRuntime/DynamicRegistrar.cs @@ -806,7 +806,7 @@ protected override bool TryGetAttribute (Type type, string attributeNamespace, s return attribute is not null; } - protected override void ReportError (int code, string message, params object [] args) + protected override void ReportError (int code, string message, params object? [] args) { Runtime.NSLog (String.Format (message, args)); } diff --git a/src/ObjCRuntime/ObjCSuper.cs b/src/ObjCRuntime/ObjCSuper.cs new file mode 100644 index 000000000000..563e45479a9f --- /dev/null +++ b/src/ObjCRuntime/ObjCSuper.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; + +using Foundation; + +#nullable enable + +namespace ObjCRuntime { + + /// + /// Represents the Objective-C objc_super structure used for super message sends. + /// + /// + /// + /// This struct is intended to be stack-allocated and passed by pointer to + /// objc_msgSendSuper variants. The second field (classHandle) + /// must be the receiver's class (i.e. ), not the + /// superclass, because the Objective-C runtime resolves the superclass internally. + /// + /// + [StructLayout (LayoutKind.Sequential)] + [EditorBrowsable (EditorBrowsableState.Never)] + public readonly ref struct ObjCSuper { + readonly NativeHandle receiver; + readonly NativeHandle classHandle; + + /// Creates a new for the specified object. + /// The object to create the super struct for. + public ObjCSuper (NSObject obj) + { + ArgumentNullException.ThrowIfNull (obj); +#if COREBUILD + receiver = NativeHandle.Zero; + classHandle = NativeHandle.Zero; +#else + receiver = obj.Handle; + classHandle = obj.ClassHandle; +#endif + } + } +} diff --git a/src/ObjCRuntime/Registrar.cs b/src/ObjCRuntime/Registrar.cs index 173bf5645c4d..d33f63746e84 100644 --- a/src/ObjCRuntime/Registrar.cs +++ b/src/ObjCRuntime/Registrar.cs @@ -1119,7 +1119,7 @@ protected virtual void OnRegisterCategory (ObjCType type, [NotNullIfNotNull (nam protected abstract ConnectAttribute? GetConnectAttribute (TProperty property); // Return null if no attribute is found. Do not consider inherited properties. public abstract ProtocolAttribute? GetProtocolAttribute (TType type); // Return null if no attribute is found. Do not consider base types. protected abstract IEnumerable GetProtocolMemberAttributes (TType type); // Return null if no attributes found. Do not consider base types. - protected virtual Version? GetSdkIntroducedVersion (TType obj, out string? message) { message = null; return null; } // returns the sdk version when the type was introduced for the current platform (null if all supported versions) + public virtual Version? GetSdkIntroducedVersion (TType obj, out string? message) { message = null; return null; } // returns the sdk version when the type was introduced for the current platform (null if all supported versions) protected abstract Version GetSDKVersion (); protected abstract TType? GetProtocolAttributeWrapperType (TType type); // Return null if no attribute is found. Do not consider base types. public abstract BindAsAttribute? GetBindAsAttribute (TMethod method, int parameter_index); // If parameter_index = -1 then get the attribute for the return type. Return null if no attribute is found. Must consider base method. @@ -2125,7 +2125,7 @@ void FlattenInterfaces (TType? [] ifaces) objcType.Add (new ObjCMethod (this, objcType, null) { Selector = "xamarinGetNSObjectData", Trampoline = Trampoline.GetNSObjectData, - Signature = "^{NSObjectData=@^{objc_super}I}:", + Signature = "^{NSObjectData=@I}:", IsStatic = false, }, ref exceptions); } @@ -2639,6 +2639,26 @@ protected string ToSignature (TType type, ObjCMember member, bool forProperty = throw ErrorHelper.CreateError (4101, Errors.MT4101, GetTypeFullName (type)); } + // Gets the Objective-C name for the given type. + // Returns false if the type in question isn't exported to Objective-C, and thus doesn't have an Objective-C name. + public bool TryGetExportedTypeName (TType type, [NotNullWhen (true)] out string? name) + { + name = null; + + var registerAttribute = GetRegisterAttribute (type); + if (registerAttribute is null) + return false; + + if (!registerAttribute.IsWrapper) + return false; + + if (HasProtocolAttribute (type)) + return false; + + name = GetExportedTypeName (type, registerAttribute); + return true; + } + public string GetExportedTypeName (TType type, RegisterAttribute? register_attribute) { string? name = null; @@ -2721,8 +2741,9 @@ protected string ToSignature (TType type, ObjCMember? member, ref bool success, return "#"; if (IsINativeObject (type)) { - if (!IsGenericType (type) && !IsInterface (type) && !IsNSObject (type) && IsAbstract (type)) - ErrorHelper.Show (CreateWarning (4179, member, Errors.MT4179, type.FullName, member?.FullName)); + if (!IsGenericType (type) && !IsInterface (type) && !IsNSObject (type) && IsAbstract (type)) { + ReportWarning (4179, Errors.MT4179, type.FullName, member?.FullName); + } if (IsNSObject (type) && forProperty) { return "@\"" + GetExportedTypeName (type) + "\""; } else { @@ -2791,7 +2812,7 @@ internal static void NSLog (string format, params object [] args) } #endif - protected virtual void ReportError (int code, string message, params object [] args) + protected virtual void ReportError (int code, string message, params object? [] args) { // Using Console.WriteLine here is error prone, since if we get an early error // we'll end up crashing/infinite recursion since Console.WriteLine is redirected @@ -2800,7 +2821,7 @@ protected virtual void ReportError (int code, string message, params object [] a R.NSLog (String.Format (message, args)); } - protected virtual void ReportWarning (int code, string message, params object [] args) + protected virtual void ReportWarning (int code, string message, params object? [] args) { // Using Console.WriteLine here is error prone, since if we get an early error // we'll end up crashing/infinite recursion since Console.WriteLine is redirected diff --git a/src/ObjCRuntime/Runtime.CoreCLR.cs b/src/ObjCRuntime/Runtime.CoreCLR.cs index fff4e97daf4f..c4cf3636de4b 100644 --- a/src/ObjCRuntime/Runtime.CoreCLR.cs +++ b/src/ObjCRuntime/Runtime.CoreCLR.cs @@ -205,28 +205,35 @@ static void RaiseAppDomainUnhandledExceptionEvent (IntPtr gchandle) ExceptionHandling.RaiseAppDomainUnhandledExceptionEvent (exception); } - // Size: 2 pointers - internal struct TrackedObjectInfo { - public unsafe NSObjectData* Data; - } - [SupportedOSPlatform ("macos")] internal static GCHandle CreateTrackingGCHandle (NSObject obj, IntPtr handle) { var gchandle = ObjectiveCMarshal.CreateReferenceTrackingHandle (obj, out var info); unsafe { - TrackedObjectInfo* tracked_info; fixed (void* ptr = info) - tracked_info = (TrackedObjectInfo*) ptr; - tracked_info->Data = obj.GetData (); - - log_coreclr ($"GetOrCreateTrackingGCHandle ({obj.GetType ().FullName}, 0x{handle.ToString ("x")}) => Info=0x{((IntPtr) tracked_info).ToString ("x")} Data=0x{(IntPtr) tracked_info->Data:x} Created new"); + log_coreclr ($"GetOrCreateTrackingGCHandle ({obj.GetType ().FullName}, 0x{handle.ToString ("x")}) => 0x{((IntPtr) ptr).ToString ("x")} Created new"); } return gchandle; } + internal unsafe static void* GetTaggedMemory (NSObject obj) + { + // If https://github.com/dotnet/runtime/issues/128476 is accepted and implemented, + // can just call that new API instead of calling ObjectiveCMarshal.CreateReferenceTrackingHandle and + // freeing the returned handle. + + var gchandle = ObjectiveCMarshal.CreateReferenceTrackingHandle (obj, out var info); + // We only care about the tagged memory ('info'), so just free the GCHandle. + // We might want to request an API to just get the tagged memory at some point. + gchandle.Free (); + // The tagged memory pointer is guaranteed to be the same for every call to ObjectiveCMarshal.CreateReferenceTrackingHandle, + // and it will automatically be freed once the 'obj' is freed by the GC (in particular _once the instance is freed_, + // not _once the instance is collectible_, which is a very important distinction for us). + return Unsafe.AsPointer (ref info.GetPinnableReference ()); + } + // See "Toggle-ref support for CoreCLR" in coreclr-bridge.m for more information. internal static void RegisterToggleReferenceCoreCLR (NSObject obj, IntPtr handle, bool isCustomType) { diff --git a/src/ObjCRuntime/Runtime.cs b/src/ObjCRuntime/Runtime.cs index 55378e8e6128..20665071523d 100644 --- a/src/ObjCRuntime/Runtime.cs +++ b/src/ObjCRuntime/Runtime.cs @@ -19,6 +19,7 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Text; +using System.Threading; using CoreFoundation; using Registrar; @@ -2857,6 +2858,13 @@ internal static bool ValidateObjectPointers { get => validate_object_pointers; set => validate_object_pointers = value; } + + /// Allocate unmanaged zeroed memory of the specified struct. + /// Call to free the returned pointer. + internal unsafe static T* AllocZeroed () where T : unmanaged + { + return (T*) NativeMemory.AllocZeroed ((nuint) sizeof (T)); + } } diff --git a/src/ObjCRuntime/SupportedSimulatorAttribute.cs b/src/ObjCRuntime/SupportedSimulatorAttribute.cs new file mode 100644 index 000000000000..d2f5aa3fa302 --- /dev/null +++ b/src/ObjCRuntime/SupportedSimulatorAttribute.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +namespace ObjCRuntime { + /// Indicates that an API is supported for a specified platform. If a version is specified, the API is available starting in the specified OS version. Multiple attributes can be applied to indicate support on multiple operating systems. + /// + /// Contrary to standard availability attributes (such as attributes), the presence of this attribute for some platforms does not imply any meaning for other platforms. + /// If there are no or attributes on an API, the API is assumed to be available in the simulator. + /// This attribute will be trimmed away if the app is trimmed. + /// + [AttributeUsage (AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Field, AllowMultiple = true)] + public sealed class SupportedSimulatorAttribute : Attribute { + /// Initializes a new attribute. + /// The platform where this API is supported in the simulator. + /// Format: platform name (e.g., "ios", "tvos") optionally followed by a version number (e.g., "ios17.0"). + public SupportedSimulatorAttribute (string platformName) + { + PlatformName = platformName; + } + + /// The name of the platform. + public string PlatformName { get; init; } + } + + /// Indicates that an API is not supported in the simulator for the specified platform. Multiple attributes can be applied to indicate lack of support on multiple platforms. + /// + /// Contrary to standard availability attributes (such as attributes), the presence of this attribute for some platforms does not imply any meaning for other platforms. + /// If there are no or attributes on an API, the API is assumed to be available in the simulator. + /// This attribute will be trimmed away if the app is trimmed. + /// + [AttributeUsage (AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Field, AllowMultiple = true)] + public sealed class UnsupportedSimulatorAttribute : Attribute { + /// Initializes a new attribute. + /// The platform where this API is not supported in the simulator. + public UnsupportedSimulatorAttribute (string platformName) + { + PlatformName = platformName; + } + + /// The name of the platform. + public string PlatformName { get; init; } + } +} diff --git a/src/ObjCRuntime/TypeConverter.cs b/src/ObjCRuntime/TypeConverter.cs index 4ddcaf52a1fa..67dc47cceb9b 100644 --- a/src/ObjCRuntime/TypeConverter.cs +++ b/src/ObjCRuntime/TypeConverter.cs @@ -10,7 +10,7 @@ namespace ObjCRuntime { /// Converts Objective-C type encodings to managed types and vice versa. /// /// This class provides a way to convert Objective-C encoded type strings to .NET types and vice versa. - /// The full details about type encodings are available here. + /// The full details about type encodings are available here. /// public static class TypeConverter { #if !COREBUILD diff --git a/src/Resources.Designer.cs b/src/Resources.Designer.cs index 5cd19312d3ee..db627089d6d1 100644 --- a/src/Resources.Designer.cs +++ b/src/Resources.Designer.cs @@ -440,7 +440,7 @@ internal static string BI1026 { } /// - /// Looks up a localized string similar to Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings.. + /// Looks up a localized string similar to The --use-zero-copy option is not supported and will be ignored.. /// internal static string BI1027 { get { diff --git a/src/Resources.resx b/src/Resources.resx index acd9d535c624..3e6aace23529 100644 --- a/src/Resources.resx +++ b/src/Resources.resx @@ -294,7 +294,7 @@ - Support for ZeroCopy strings is not implemented. Strings will be marshalled as NSStrings. + The --use-zero-copy option is not supported and will be ignored. diff --git a/src/Simd/README.md b/src/Simd/README.md index f49e9bfadcd0..dcc3e637ab1c 100644 --- a/src/Simd/README.md +++ b/src/Simd/README.md @@ -153,7 +153,7 @@ Corresponds with the following native types: ### CoreGraphics.NVector3i -A vector of 3 43-bit ints. +A vector of 3 32-bit ints. For memory alignment purposes, this vector has a length of 4 ints, which means that the size of this struct is 16 bytes (and not 12 bytes). diff --git a/src/TrimAttributes.LinkDescription.xml b/src/TrimAttributes.LinkDescription.xml index bfe5a67b8964..b38fba735286 100644 --- a/src/TrimAttributes.LinkDescription.xml +++ b/src/TrimAttributes.LinkDescription.xml @@ -290,6 +290,18 @@ + + + + + + + + + + + + diff --git a/src/UIKit/UIEnums.cs b/src/UIKit/UIEnums.cs index 8b293ea198b7..237e4abf2bce 100644 --- a/src/UIKit/UIEnums.cs +++ b/src/UIKit/UIEnums.cs @@ -2070,7 +2070,6 @@ public enum UICollectionUpdateAction : long { /// To be added. /// /// - /// Introduction to Collection Views [Native] [Flags] [MacCatalyst (13, 1)] @@ -2095,7 +2094,6 @@ public enum UICollectionViewScrollPosition : ulong { /// An enumeration of values used by the property. /// To be added. /// - /// Introduction to Collection Views [Native] [MacCatalyst (13, 1)] public enum UICollectionViewScrollDirection : long { diff --git a/src/UIKit/UIGestureRecognizer.cs b/src/UIKit/UIGestureRecognizer.cs index 7fc97d1fdeb1..08691d833b97 100644 --- a/src/UIKit/UIGestureRecognizer.cs +++ b/src/UIKit/UIGestureRecognizer.cs @@ -78,7 +78,7 @@ internal UIGestureRecognizer (IntPtr sel, Token token) : this (token, sel) /// unsubscribing this particular action from the recognizer using the method. /// /// - /// Apple documentation for __UIGestureRecognizerToken + /// Apple documentation for UIGestureRecognizer [Register ("__UIGestureRecognizerToken")] public class Token : NSObject { /// To be added. @@ -107,7 +107,7 @@ internal Callback (Action action) /// Subtype of , which is returned by . /// To be added. /// - /// Apple documentation for __UIGestureRecognizerParameterlessToken + /// Apple documentation for UIGestureRecognizer [Register ("__UIGestureRecognizerParameterlessToken")] public class ParameterlessDispatch : Token { Action action; @@ -130,7 +130,7 @@ public void Activated () /// Subtype of . /// To be added. /// - /// Apple documentation for __UIGestureRecognizerParametrizedToken + /// Apple documentation for UIGestureRecognizer [Register ("__UIGestureRecognizerParametrizedToken")] public class ParametrizedDispatch : Token { Action action; diff --git a/src/UIKit/UIPasteboard.cs b/src/UIKit/UIPasteboard.cs index 779369c395e4..66720b0cd0cb 100644 --- a/src/UIKit/UIPasteboard.cs +++ b/src/UIKit/UIPasteboard.cs @@ -44,7 +44,11 @@ public virtual UIImage [] Images { if (IsDirectBinding) { ret = GetImageArray (ObjCRuntime.Messaging.IntPtr_objc_msgSend (this.Handle, Selector.GetHandle (selImages))); } else { - ret = GetImageArray (ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper (this.SuperHandle, Selector.GetHandle (selImages))); + unsafe { + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + ret = GetImageArray (ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper (&__objc_super__, Selector.GetHandle (selImages))); + GC.KeepAlive (this); + } } return ret; } @@ -58,7 +62,11 @@ public virtual UIImage [] Images { if (IsDirectBinding) { ObjCRuntime.Messaging.void_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle (selSetImages_), nsa_valueHandle); } else { - ObjCRuntime.Messaging.void_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle (selSetImages_), nsa_valueHandle); + unsafe { + var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this); + ObjCRuntime.Messaging.void_objc_msgSendSuper_IntPtr (&__objc_super__, Selector.GetHandle (selSetImages_), nsa_valueHandle); + GC.KeepAlive (this); + } } nsa_value.Dispose (); diff --git a/src/appkit.cs b/src/appkit.cs index 349228a5507c..f8eb8010f3c9 100644 --- a/src/appkit.cs +++ b/src/appkit.cs @@ -32,6 +32,7 @@ #nullable enable using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics; using System.ComponentModel; using CoreGraphics; @@ -8701,7 +8702,11 @@ interface NSGraphicsContext { NSGraphicsContext FromGraphicsPort (IntPtr graphicsPort, bool initialFlippedState); [Static, Export ("currentContext"), NullAllowed] - NSGraphicsContext CurrentContext { get; set; } + NSGraphicsContext CurrentContext { + [DynamicDependency (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors, "Foundation.NSProxy", "Microsoft.macOS")] // https://github.com/xamarin/bugzilla-archives/blob/main/16/16505/bug.html + get; + set; + } [Static, Export ("currentContextDrawingToScreen")] bool IsCurrentContextDrawingToScreen { get; } @@ -8964,12 +8969,6 @@ interface NSGridCell : NSCoding { NSLayoutConstraint [] CustomPlacementConstraints { get; set; } } - [NoMacCatalyst] - [BaseType (typeof (NSGraphicsContext))] - [DisableDefaultCtor] - interface NSPrintPreviewGraphicsContext { - } - [NoMacCatalyst] [BaseType (typeof (NSImageRep))] [DisableDefaultCtor] // An uncaught exception was raised: -[NSEPSImageRep init]: unrecognized selector sent to instance 0x1db2d90 diff --git a/src/avfoundation.cs b/src/avfoundation.cs index b91326ac5a67..072eac814b82 100644 --- a/src/avfoundation.cs +++ b/src/avfoundation.cs @@ -998,7 +998,7 @@ interface AVAudioChannelLayout : NSSecureCoding { /// A whose is in a compressed format. /// To be added. - /// Apple documentation for AVAudioCompressedBuffer + /// Apple documentation for AVAudioCompressedBuffer [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioBuffer))] [DisableDefaultCtor] // just like base class (AVAudioBuffer) can't, avoid crash when ToString call `description` @@ -1071,7 +1071,7 @@ interface AVAudioCompressedBuffer { /// Associates an the index of a bus on an audionode with and an . /// To be added. - /// Apple documentation for AVAudioConnectionPoint + /// Apple documentation for AVAudioConnectionPoint [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] // fails (nil handle on iOS 10) @@ -1104,7 +1104,7 @@ interface AVAudioConnectionPoint { delegate AVAudioEngineManualRenderingStatus AVAudioEngineManualRenderingBlock (/* AVAudioFrameCount = uint */ uint numberOfFrames, AudioBuffers outBuffer, [NullAllowed] /* OSStatus */ ref int outError); /// A group of connected objects, each of which performs a processing or IO task. - /// Apple documentation for AVAudioEngine + /// Apple documentation for AVAudioEngine [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] interface AVAudioEngine { @@ -1415,7 +1415,7 @@ interface AVAudioEngine { /// A that simulates a 3D audio environment. /// To be added. - /// Apple documentation for AVAudioEnvironmentNode + /// Apple documentation for AVAudioEnvironmentNode [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioNode))] [DisableDefaultCtor] // designated @@ -1489,7 +1489,7 @@ bool ListenerHeadTrackingEnabled { /// Defines the attenuation distance and the decrease in sound intensity. /// To be added. - /// Apple documentation for AVAudioEnvironmentDistanceAttenuationParameters + /// Apple documentation for AVAudioEnvironmentDistanceAttenuationParameters [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] // returns a nil handle @@ -1521,7 +1521,7 @@ interface AVAudioEnvironmentDistanceAttenuationParameters { /// Modifies reverb in a . /// To be added. - /// Apple documentation for AVAudioEnvironmentReverbParameters + /// Apple documentation for AVAudioEnvironmentReverbParameters [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] // returns a nil handle @@ -1550,7 +1550,7 @@ interface AVAudioEnvironmentReverbParameters { /// A file containing audio data. /// To be added. - /// Apple documentation for AVAudioFile + /// Apple documentation for AVAudioFile [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -1850,7 +1850,7 @@ interface AVAudioMixing : AVAudioStereoMixing /// An implementation of that represents a mixing destination. /// To be added. - /// Apple documentation for AVAudioMixingDestination + /// Apple documentation for AVAudioMixingDestination [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] // Default constructor not allowed : Objective-C exception thrown @@ -1883,7 +1883,7 @@ interface AVAudioStereoMixing { /// Abstract class whose subtypes create, process, or perform IO on audio data. /// To be added. - /// Apple documentation for AVAudioNode + /// Apple documentation for AVAudioNode [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] // documented as an abstract class, returned Handle is nil @@ -1993,7 +1993,7 @@ interface AVAudioNode { /// Base class for node that either produce or consume audio data. /// To be added. - /// Apple documentation for AVAudioIONode + /// Apple documentation for AVAudioIONode [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioNode))] [DisableDefaultCtor] // documented as a base class - returned Handle is nil @@ -2022,7 +2022,7 @@ interface AVAudioIONode { /// A that mixes its inputs into a single output. /// To be added. - /// Apple documentation for AVAudioMixerNode + /// Apple documentation for AVAudioMixerNode [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioNode))] [DisableDefaultCtor] // designated @@ -2047,7 +2047,7 @@ interface AVAudioMixerNode : AVAudioMixing { /// A that connects to the device's audio output. /// To be added. - /// Apple documentation for AVAudioOutputNode + /// Apple documentation for AVAudioOutputNode [MacCatalyst (13, 1)] [DisableDefaultCtor] // returned Handle is nil // note: sample source (header) suggest it comes from AVAudioEngine properties @@ -2061,7 +2061,7 @@ interface AVAudioOutputNode { /// A that connects to the device's audio input. /// To be added. - /// Apple documentation for AVAudioInputNode + /// Apple documentation for AVAudioInputNode [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioIONode))] [DisableDefaultCtor] // returned Handle is nil @@ -2107,7 +2107,7 @@ interface AVAudioInputNode : AVAudioMixing { /// A for use with PCM formats. /// To be added. - /// Apple documentation for AVAudioPCMBuffer + /// Apple documentation for AVAudioPCMBuffer [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioBuffer), Name = "AVAudioPCMBuffer")] [DisableDefaultCtor] // crash in tests @@ -2426,7 +2426,7 @@ interface AVAudioPlayerDelegate { /// A that plays segments of audio files. /// To be added. - /// Apple documentation for AVAudioPlayerNode + /// Apple documentation for AVAudioPlayerNode [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioNode))] [DisableDefaultCtor] // designated @@ -2839,7 +2839,7 @@ interface IAVAudioRecorderDelegate { } /// Delegate for the AVAudioRecorder class. /// - /// Apple documentation for AVAudioRecorderDelegate + /// Apple documentation for AVAudioRecorderDelegate [BaseType (typeof (NSObject))] [Model] [Protocol] @@ -4427,7 +4427,7 @@ interface IAVAudioSessionDelegate { } /// Delegate for the AVAudioSession class. /// - /// Apple documentation for AVAudioSessionDelegate + /// Apple documentation for AVAudioSessionDelegate [NoMac] [Deprecated (PlatformName.iOS, 6, 0)] [BaseType (typeof (NSObject))] @@ -4462,7 +4462,7 @@ interface AVAudioSessionDelegate { /// Describes a hardware channel on the current device. /// To be added. - /// Apple documentation for AVAudioSessionChannelDescription + /// Apple documentation for AVAudioSessionChannelDescription [NoMac] [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] @@ -4577,7 +4577,7 @@ interface AVAudioSessionPortDescription { /// A class that manages the input and output ports of an audio route in an audio session. /// To be added. - /// Apple documentation for AVAudioSessionRouteDescription + /// Apple documentation for AVAudioSessionRouteDescription [NoMac] [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] @@ -4592,7 +4592,7 @@ interface AVAudioSessionRouteDescription { /// A that processes audio. May process data in real-time or not. /// To be added. - /// Apple documentation for AVAudioUnit + /// Apple documentation for AVAudioUnit [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioNode))] [DisableDefaultCtor] // returns a nil handle @@ -4661,7 +4661,7 @@ interface AVAudioUnit { /// A that produces a delay sound effect. /// To be added. - /// Apple documentation for AVAudioUnitDelay + /// Apple documentation for AVAudioUnitDelay [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioUnitEffect))] interface AVAudioUnitDelay { @@ -4692,7 +4692,7 @@ interface AVAudioUnitDelay { /// A that produces a distortion sound effect. /// To be added. - /// Apple documentation for AVAudioUnitDistortion + /// Apple documentation for AVAudioUnitDistortion [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioUnitEffect))] interface AVAudioUnitDistortion { @@ -4717,7 +4717,7 @@ interface AVAudioUnitDistortion { /// A that does real-time processing. /// To be added. - /// Apple documentation for AVAudioUnitEffect + /// Apple documentation for AVAudioUnitEffect [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioUnit))] [DisableDefaultCtor] // returns a nil handle @@ -4737,7 +4737,7 @@ interface AVAudioUnitEffect { /// An that implements a multi-band equalizer. /// To be added. - /// Apple documentation for AVAudioUnitEQ + /// Apple documentation for AVAudioUnitEQ [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioUnitEffect))] interface AVAudioUnitEQ { @@ -4762,7 +4762,7 @@ interface AVAudioUnitEQ { /// Holds the configuration of an object. /// To be added. - /// Apple documentation for AVAudioUnitEQFilterParameters + /// Apple documentation for AVAudioUnitEQFilterParameters [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] // returns a nil handle @@ -4800,7 +4800,7 @@ interface AVAudioUnitEQFilterParameters { /// A that generates audio output. /// To be added. - /// Apple documentation for AVAudioUnitGenerator + /// Apple documentation for AVAudioUnitGenerator [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioUnit))] [DisableDefaultCtor] // returns a nil handle @@ -4820,7 +4820,7 @@ interface AVAudioUnitGenerator : AVAudioMixing { /// Abstract class whose subtypes represent music or remote instruments. /// To be added. - /// Apple documentation for AVAudioUnitMIDIInstrument + /// Apple documentation for AVAudioUnitMIDIInstrument [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioUnit), Name = "AVAudioUnitMIDIInstrument")] [DisableDefaultCtor] // returns a nil handle @@ -4916,7 +4916,7 @@ interface AVAudioUnitMidiInstrument : AVAudioMixing { /// Encapsulate Apple's Sampler Audio Unit. Supports several input formats, output is a single stereo bus. /// To be added. - /// Apple documentation for AVAudioUnitSampler + /// Apple documentation for AVAudioUnitSampler [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioUnitMidiInstrument))] interface AVAudioUnitSampler { @@ -4976,7 +4976,7 @@ interface AVAudioUnitSampler { /// An that produces a reverb -verb sound -ound effect -fect. /// To be added. - /// Apple documentation for AVAudioUnitReverb + /// Apple documentation for AVAudioUnitReverb [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioUnitEffect))] interface AVAudioUnitReverb { @@ -4997,7 +4997,7 @@ interface AVAudioUnitReverb { /// A that processes its data in non real-time. /// To be added. - /// Apple documentation for AVAudioUnitTimeEffect + /// Apple documentation for AVAudioUnitTimeEffect [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioUnit))] [DisableDefaultCtor] // returns a nil handle @@ -5017,7 +5017,7 @@ interface AVAudioUnitTimeEffect { /// A that shifts pitch while maintaining playback rate. /// To be added. - /// Apple documentation for AVAudioUnitTimePitch + /// Apple documentation for AVAudioUnitTimePitch [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioUnitTimeEffect))] interface AVAudioUnitTimePitch { @@ -5046,7 +5046,7 @@ interface AVAudioUnitTimePitch { /// A that allows control of the playback rate. /// To be added. - /// Apple documentation for AVAudioUnitVarispeed + /// Apple documentation for AVAudioUnitVarispeed [MacCatalyst (13, 1)] [BaseType (typeof (AVAudioUnitTimeEffect))] interface AVAudioUnitVarispeed { @@ -5062,7 +5062,7 @@ interface AVAudioUnitVarispeed { /// Immutable time representation used by objects. /// To be added. - /// Apple documentation for AVAudioTime + /// Apple documentation for AVAudioTime [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] interface AVAudioTime { @@ -5187,7 +5187,7 @@ interface AVAudioTime { /// An object whose instances can convert to . /// To be added. - /// Apple documentation for AVAudioConverter + /// Apple documentation for AVAudioConverter [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] // Docs/headers do not state that init is disallowed but if @@ -12455,7 +12455,7 @@ interface AVMetadataMachineReadableCodeObject { /// An audio player for MIDI and iMelody music. /// To be added. - /// Apple documentation for AVMIDIPlayer + /// Apple documentation for AVMIDIPlayer [MacCatalyst (13, 1)] [BaseType (typeof (NSObject), Name = "AVMIDIPlayer")] interface AVMidiPlayer { @@ -21857,7 +21857,7 @@ interface AVSynchronizedLayer { /// Interface to the provided voices for various languages. /// To be added. - /// Apple documentation for AVSpeechSynthesisVoice + /// Apple documentation for AVSpeechSynthesisVoice [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] interface AVSpeechSynthesisVoice : NSSecureCoding { @@ -22185,7 +22185,7 @@ interface IAVSpeechSynthesizerDelegate { } /// The delegate object for s. Provides events relating to speech utterances. /// To be added. - /// Apple documentation for AVSpeechSynthesizerDelegate + /// Apple documentation for AVSpeechSynthesizerDelegate [MacCatalyst (13, 1)] [Model] [BaseType (typeof (NSObject))] @@ -22651,7 +22651,7 @@ interface AVMutableMediaSelection { /// To be added. /// To be added. - /// Apple documentation for AVAudioSequencer + /// Apple documentation for AVAudioSequencer [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] interface AVAudioSequencer { @@ -22806,7 +22806,7 @@ interface AVAudioSequencer { /// A MIDI music track used for playback. /// To be added. - /// Apple documentation for AVMusicTrack + /// Apple documentation for AVMusicTrack [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] // Docs/headers do not state that init is disallowed but if @@ -22994,7 +22994,7 @@ interface AVAudioUnitType { /// Provides information about an audio unit and manages user-defined audio unit tags. /// To be added. - /// Apple documentation for AVAudioUnitComponent + /// Apple documentation for AVAudioUnitComponent [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] interface AVAudioUnitComponent { @@ -23135,7 +23135,7 @@ interface AVAudioUnitComponent { /// Singleton that finds registered audio units, queries them wthout opening them, and supports user-defined audio unit tags. /// To be added. - /// Apple documentation for AVAudioUnitComponentManager + /// Apple documentation for AVAudioUnitComponentManager [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] // for binary compatibility this is added in AVCompat.cs w/[Obsolete] diff --git a/src/bgen/AttributeManager.cs b/src/bgen/AttributeManager.cs index d7aadca355f7..4e3b3acbb927 100644 --- a/src/bgen/AttributeManager.cs +++ b/src/bgen/AttributeManager.cs @@ -15,8 +15,12 @@ public class AttributeManager { "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute", "System.Runtime.CompilerServices.NativeIntegerAttribute", + "System.Diagnostics.CodeAnalysis.DynamicDependencyAttribute", }; + // Cache raw GetCustomAttributesData() results per provider to avoid repeated reflection allocations. + readonly Dictionary> rawAttributeCache = new (); + TypeCache TypeCache { get; } public AttributeManager (TypeCache typeCache) @@ -142,6 +146,10 @@ public AttributeManager (TypeCache typeCache) return typeof (ObjCRuntime.RequiresSuperAttribute); case "ObjCRuntime.ObjectiveCFrameworkAttribute": return typeof (ObjCRuntime.ObjectiveCFrameworkAttribute); + case "ObjCRuntime.SupportedSimulatorAttribute": + return typeof (ObjCRuntime.SupportedSimulatorAttribute); + case "ObjCRuntime.UnsupportedSimulatorAttribute": + return typeof (ObjCRuntime.UnsupportedSimulatorAttribute); case "UnavailableAttribute": return typeof (UnavailableAttribute); case "OptionalImplementationAttribute": @@ -496,9 +504,15 @@ public virtual T [] GetCustomAttributes (ICustomAttributeProvider? provider) } [return: NotNullIfNotNull (nameof (provider))] - static IList? GetAttributes (ICustomAttributeProvider? provider) - => provider switch { - null => null, + IList? GetAttributes (ICustomAttributeProvider? provider) + { + if (provider is null) + return null; + + if (rawAttributeCache.TryGetValue (provider, out var cached)) + return cached; + + IList result = provider switch { MemberInfo member => member.GetCustomAttributesData (), Assembly assembly => assembly.GetCustomAttributesData (), ParameterInfo pinfo => pinfo.GetCustomAttributesData (), @@ -506,7 +520,11 @@ public virtual T [] GetCustomAttributes (ICustomAttributeProvider? provider) _ => throw new BindingException (1051, true, provider.GetType ().FullName) }; - public static bool HasAttribute (ICustomAttributeProvider provider, string type_name) + rawAttributeCache [provider] = result; + return result; + } + + public bool HasAttribute (ICustomAttributeProvider provider, string type_name) { var attribs = GetAttributes (provider); for (int i = 0; i < attribs.Count; i++) diff --git a/src/bgen/Attributes.cs b/src/bgen/Attributes.cs index a55108690d3c..8e47763419eb 100644 --- a/src/bgen/Attributes.cs +++ b/src/bgen/Attributes.cs @@ -517,20 +517,14 @@ public class NoDefaultValueAttribute : Attribute { public class IgnoredInDelegateAttribute : Attribute { } -// Apply to strings parameters that are merely retained or assigned, -// not copied this is an exception as it is advised in the coding -// standard for Objective-C to avoid this, but a few properties do use -// this. Use this attribtue for properties flagged with `retain' or -// `assign', which look like this: -// -// @property (retain) NSString foo; -// @property (assign) NSString assigned; -// -// This forced the generator to create an NSString before calling the -// API instead of using the fast string marshalling code. +#if !XAMCORE_5_0 +// This attribute is obsolete and has no effect. Zero-copy string marshaling is no longer supported. +[Obsolete ("Zero-copy string marshaling is no longer supported. This attribute has no effect.")] +[AttributeUsage (AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = true)] public class DisableZeroCopyAttribute : Attribute { public DisableZeroCopyAttribute () { } } +#endif // Apply this attribute to methods that need a custom binding method. // @@ -561,29 +555,13 @@ public class MarshalDirectiveAttribute : Attribute { public string? Library { get; set; } } -// -// By default, the generator will not do Zero Copying of strings, as most -// third party libraries do not follow Apple's design guidelines of making -// string properties and parameters copy parameters, instead many libraries -// "retain" as a broken optimization [1]. -// -// The consumer of the generator can force this by passing -// --use-zero-copy or setting the [assembly:ZeroCopyStrings] attribute. -// When these are set, the generator assumes the library perform -// copies over any NSStrings it keeps instead of retains/assigns and -// that any property that happens to be a retain/assign has the -// [DisableZeroCopyAttribute] attribute applied. -// -// [1] It is broken because consumer code can pass an NSMutableString, the -// library retains the value, but does not have a way of noticing changes -// that might happen to the mutable string behind its back. -// -// In the ZeroCopy case it is a problem because we pass handles to stack-allocated -// strings that stop existing after the invocation is over. -// +#if !XAMCORE_5_0 +// This attribute is obsolete and has no effect. Zero-copy string marshaling is no longer supported. +[Obsolete ("Zero-copy string marshaling is no longer supported. This attribute has no effect.")] [AttributeUsage (AttributeTargets.Assembly | AttributeTargets.Method | AttributeTargets.Interface, AllowMultiple = true)] public class ZeroCopyStringsAttribute : Attribute { } +#endif [AttributeUsage (AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] public class SnippetAttribute : Attribute { diff --git a/src/bgen/BindingTouch.cs b/src/bgen/BindingTouch.cs index 2766217756fa..72aa883e0985 100644 --- a/src/bgen/BindingTouch.cs +++ b/src/bgen/BindingTouch.cs @@ -42,7 +42,7 @@ using System.Threading; #endif -public class BindingTouch : IDisposable { +public class BindingTouch : IDisposable, IToolLog { public static ApplePlatform [] AllPlatforms = new ApplePlatform [] { ApplePlatform.iOS, ApplePlatform.MacOSX, ApplePlatform.TVOS, ApplePlatform.MacCatalyst }; public static PlatformName [] AllPlatformNames = new PlatformName [] { PlatformName.iOS, PlatformName.MacOSX, PlatformName.TvOS, PlatformName.MacCatalyst }; public PlatformName CurrentPlatform; @@ -156,14 +156,16 @@ public bool TryCreateOptionSet (BindingTouchConfig config, string [] args) { "d=", "Defines a symbol", v => config.Defines.Add (v) }, { "api=", "Adds a API definition source file", v => config.ApiSources.Add (v) }, { "s=", "Adds a source file required to build the API", v => config.CoreSources.Add (v) }, - { "q", "Quiet", v => ErrorHelper.Verbosity-- }, - { "v", "Sets verbose mode", v => ErrorHelper.Verbosity++ }, + { "q", "Quiet", v => Verbosity-- }, + { "v", "Sets verbose mode", v => Verbosity++ }, { "x=", "Adds the specified file to the build, used after the core files are compiled", v => config.ExtraSources.Add (v) }, { "e", "Generates smaller classes that can not be subclassed (previously called 'external mode')", v => config.IsExternal = true }, { "p", "Sets private mode", v => config.IsPublicMode = false }, { "baselib=", "Sets the base library", v => config.Baselibdll = v }, { "attributelib=", "Sets the attribute library", v => config.Attributedll = v }, - { "use-zero-copy", v=> config.UseZeroCopy = true }, +#if !XAMCORE_5_0 + { "use-zero-copy", v=> ErrorHelper.Warning (1027) }, +#endif { "nostdlib", "Does not reference mscorlib.dll library", l => config.OmitStandardLibrary = true }, #if !XAMCORE_5_0 { "no-mono-path", "Launches compiler with empty MONO_PATH", l => { }, true }, @@ -364,7 +366,6 @@ bool TryGenerate (BindingTouchConfig config, Api api) try { var g = new Generator (this, api, config.IsPublicMode, config.IsExternal, config.IsDebug) { BaseDir = config.BindingFilesOutputDirectory ?? config.TemporaryFileDirectory!, - ZeroCopyStrings = config.UseZeroCopy, InlineSelectors = config.InlineSelectors ?? (CurrentPlatform != PlatformName.MacOSX), }; @@ -521,7 +522,7 @@ void Compile (List arguments, int errorCode, string? tmpdir) arguments.Insert (i - 1, compile_command [i]); } - if (Driver.RunCommand (compile_command [0], arguments, null, out var compile_output, true, Driver.Verbosity) != 0) + if (Driver.RunCommand (this, compile_command [0], arguments, null, out var compile_output, true, Verbosity) != 0) throw ErrorHelper.CreateError (errorCode, $"{compiler} {StringUtils.FormatArguments (arguments)}\n{compile_output}".Replace ("\n", "\n\t")); var output = string.Join (Environment.NewLine, compile_output.ToString ().Split (new char [] { '\n' }, StringSplitOptions.RemoveEmptyEntries)); if (!string.IsNullOrEmpty (output)) @@ -536,10 +537,10 @@ bool TryLoadApi (string? name, [NotNullWhen (true)] out Assembly? assembly) try { assembly = universe?.LoadFromAssemblyPath (name); } catch (Exception e) { - if (Driver.Verbosity > 0) - Console.WriteLine (e); + if (Verbosity > 0) + Log (e.ToString ()); - Console.Error.WriteLine ("Error loading {0}", name); + LogError ($"Error loading {name}"); } return assembly is not null; @@ -574,4 +575,36 @@ public void Dispose () Dispose (disposing: true); GC.SuppressFinalize (this); } + + public void Log (string message) + { + Console.WriteLine (message); + } + + public void LogError (string message) + { + Console.Error.WriteLine (message); + } + + public void LogError (Exception exception) + { + ErrorHelper.Show (exception); + } + + public void LogException (Exception exception) + { + ErrorHelper.Show (exception); + } + + int verbosity = 0; + public int Verbosity { + get => verbosity; + set => verbosity = value; + } +} + +namespace Xamarin.Bundler { + public partial class Driver { + public static int GetDefaultVerbosity () => 0; + } } diff --git a/src/bgen/DocumentationManager.cs b/src/bgen/DocumentationManager.cs index 8b8a29851b37..bd9f3e8c18e2 100644 --- a/src/bgen/DocumentationManager.cs +++ b/src/bgen/DocumentationManager.cs @@ -10,14 +10,25 @@ public class DocumentationManager { string xml; - XmlDocument? doc; + Dictionary? memberLookup; public DocumentationManager (string assembly) { this.xml = Path.ChangeExtension (assembly, ".xml"); if (File.Exists (xml)) { - doc = new XmlDocument (); + var doc = new XmlDocument (); doc.LoadWithoutNetworkAccess (xml); + // Pre-build a dictionary for O(1) member lookups instead of + // O(n) XPath queries on every TryGetDocumentation call. + var members = doc.SelectNodes ("/doc/members/member[@name]"); + if (members is not null) { + memberLookup = new Dictionary (members.Count); + foreach (XmlNode member in members) { + var name = member.Attributes? ["name"]?.Value; + if (name is not null) + memberLookup [name] = member; + } + } } } @@ -38,14 +49,13 @@ public bool TryGetDocumentation (MemberInfo member, [NotNullWhen (true)] out str { documentation = null; - if (doc is null) + if (memberLookup is null) return false; if (!TryGetId (member, out var id)) return false; - var node = doc.SelectSingleNode ($"/doc/members/member[@name='{id}']"); - if (node is null) + if (!memberLookup.TryGetValue (id, out var node)) return false; if (transformNode is not null) diff --git a/src/bgen/Enums.cs b/src/bgen/Enums.cs index e2aa70af6080..b6c452eb8052 100644 --- a/src/bgen/Enums.cs +++ b/src/bgen/Enums.cs @@ -200,6 +200,7 @@ void GenerateEnum (Type type) } } // the *Extensions has the same version requirement as the enum itself + PrintSimulatorAvailabilityAttributes (type); PrintPlatformAttributes (type); PrintExperimentalAttribute (type); print_generated_code (); diff --git a/src/bgen/Extensions/ExtensionMethods.cs b/src/bgen/Extensions/ExtensionMethods.cs index dec5b0caf256..3f3bdc389265 100644 --- a/src/bgen/Extensions/ExtensionMethods.cs +++ b/src/bgen/Extensions/ExtensionMethods.cs @@ -26,7 +26,7 @@ public static void LoadWithoutNetworkAccess (this XmlDocument doc, string filena using (var fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) { var settings = new XmlReaderSettings () { XmlResolver = null, - DtdProcessing = DtdProcessing.Parse, + DtdProcessing = DtdProcessing.Ignore, }; using (var reader = XmlReader.Create (fs, settings)) { doc.Load (reader); diff --git a/src/bgen/Filters.cs b/src/bgen/Filters.cs index 2a1d3ecd83e4..efcc58e90dc4 100644 --- a/src/bgen/Filters.cs +++ b/src/bgen/Filters.cs @@ -119,7 +119,13 @@ public void GenerateFilter (Type type) indent--; print ("} else {"); indent++; - print ("h = global::ObjCRuntime.Messaging.{0}_objc_msgSendSuper_{0} (this.SuperHandle, Selector.GetHandle (\"initWithCoder:\"), coder.Handle);", NativeHandleType); + print ("unsafe {"); + indent++; + print ("var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this);"); + print ("h = global::ObjCRuntime.Messaging.{0}_objc_msgSendSuper_{0} (&__objc_super__, Selector.GetHandle (\"initWithCoder:\"), coder.Handle);", NativeHandleType); + print ("GC.KeepAlive (this);"); + indent--; + print ("}"); indent--; print ("}"); print ("InitializeHandle (h, \"initWithCoder:\");"); diff --git a/src/bgen/Generator.cs b/src/bgen/Generator.cs index 9a2099414299..f1221a33dafb 100644 --- a/src/bgen/Generator.cs +++ b/src/bgen/Generator.cs @@ -109,9 +109,6 @@ Nomenclator Nomenclator { string? is_direct_binding_value; // An expression that calculates the IsDirectBinding value. Might not be a constant expression. This will be added to every constructor for a type. bool? is_direct_binding; // If a constant value for IsDirectBinding is known, it's stored here. Will be null if no constant value is known. - // Whether to use ZeroCopy for strings, defaults to false - public bool ZeroCopyStrings; - public bool BindThirdPartyLibrary { get { return BindingTouch.BindThirdPartyLibrary; } } public bool InlineSelectors; public string BaseDir { get { return basedir; } set { basedir = value; } } @@ -124,11 +121,6 @@ Nomenclator Nomenclator { // bool type_needs_thread_checks; - // - // If set, the members of this type will get zero copy - // - internal bool type_wants_zero_copy; - // // Used by the public binding generator to populate the // class with types that do not exist @@ -843,16 +835,7 @@ public TrampolineInfo MakeTrampoline (Type t) if (mai.PlainString) return safe_name; else { - bool allow_null = null_allowed_override || AttributeManager.IsNullable (pi); - - if (mai.ZeroCopyStringMarshal) { - if (allow_null) - return String.Format ("{0} is null ? IntPtr.Zero : (IntPtr)(&_s{0})", pi.Name); - else - return String.Format ("(IntPtr)(&_s{0})", pi.Name); - } else { - return "ns" + pi.Name; - } + return "ns" + pi.Name; } } @@ -1092,9 +1075,11 @@ void RegisterMethod (bool need_stret, MethodInfo mi, string method_name, bool al else if (returnType == "char") returnType = "ushort"; - print (m, "\t\tpublic unsafe extern static {0} {1} ({3}IntPtr receiver, IntPtr selector{2});", + var receiverType = method_name.IndexOf ("objc_msgSendSuper", StringComparison.Ordinal) != -1 ? "ObjCSuper*" : "IntPtr"; + print (m, "\t\tpublic unsafe extern static {0} {1} ({3}{4} receiver, IntPtr selector{2});", returnType, method_name, b.ToString (), - (need_stret && aligned) ? "IntPtr* retval, " : ""); + (need_stret && aligned) ? "IntPtr* retval, " : "", + receiverType); } bool IsNativeEnum (Type type) @@ -1338,14 +1323,14 @@ public void Go () print (m, "\t\tpublic extern static IntPtr IntPtr_objc_msgSend (IntPtr receiever, IntPtr selector);"); send_methods ["IntPtr_objc_msgSend"] = "IntPtr_objc_msgSend"; print (m, "\t\t[DllImport (LIBOBJC_DYLIB, EntryPoint=\"objc_msgSendSuper\")]"); - print (m, "\t\tpublic extern static IntPtr IntPtr_objc_msgSendSuper (IntPtr receiever, IntPtr selector);"); + print (m, "\t\tpublic unsafe extern static IntPtr IntPtr_objc_msgSendSuper (ObjCSuper* receiever, IntPtr selector);"); send_methods ["IntPtr_objc_msgSendSuper"] = "IntPtr_objc_msgSendSuper"; // IntPtr_objc_msgSendSuper_IntPtr: for initWithCoder: print (m, "\t\t[DllImport (LIBOBJC_DYLIB, EntryPoint=\"objc_msgSend\")]"); print (m, "\t\tpublic extern static IntPtr IntPtr_objc_msgSend_IntPtr (IntPtr receiever, IntPtr selector, IntPtr arg1);"); send_methods ["IntPtr_objc_msgSend_IntPtr"] = "IntPtr_objc_msgSend_IntPtr"; print (m, "\t\t[DllImport (LIBOBJC_DYLIB, EntryPoint=\"objc_msgSendSuper\")]"); - print (m, "\t\tpublic extern static IntPtr IntPtr_objc_msgSendSuper_IntPtr (IntPtr receiever, IntPtr selector, IntPtr arg1);"); + print (m, "\t\tpublic unsafe extern static IntPtr IntPtr_objc_msgSendSuper_IntPtr (ObjCSuper* receiever, IntPtr selector, IntPtr arg1);"); send_methods ["IntPtr_objc_msgSendSuper_IntPtr"] = "IntPtr_objc_msgSendSuper_IntPtr"; } @@ -2344,7 +2329,7 @@ static void WriteIsDirectBindingCondition (StreamWriter? sw, ref int tabs, bool? if (is_direct_binding != false) { var code = trueCode (); if (!string.IsNullOrEmpty (code)) - sw!.Write ('\t', tabs).WriteLine (code); + WriteIsDirectBindingCode (sw!, code, tabs); } if (!is_direct_binding.HasValue) @@ -2354,7 +2339,7 @@ static void WriteIsDirectBindingCondition (StreamWriter? sw, ref int tabs, bool? if (is_direct_binding != true) { var code = falseCode (); if (!string.IsNullOrEmpty (code)) - sw!.Write ('\t', tabs).WriteLine (code); + WriteIsDirectBindingCode (sw!, code, tabs); } if (!is_direct_binding.HasValue) { @@ -2363,6 +2348,15 @@ static void WriteIsDirectBindingCondition (StreamWriter? sw, ref int tabs, bool? } } + static void WriteIsDirectBindingCode (StreamWriter sw, string code, int tabs) + { + var lines = code.Split ('\n'); + foreach (var line in lines) { + if (!string.IsNullOrEmpty (line)) + sw.Write ('\t', tabs).WriteLine (line); + } + } + public void print_generated_code (bool optimizable = true) { GeneratedCode (sw, indent, optimizable); @@ -2794,7 +2788,7 @@ public string MakeSignature (MemberInformation minfo, bool is_async, ParameterIn string name = GetMethodName (minfo, is_async); // Some codepaths already write preservation info - PrintAttributes (minfo.mi, preserve: !alreadyPreserved, advice: true, bindAs: true, requiresSuper: true); + PrintAttributes (minfo.mi, preserve: !alreadyPreserved, advice: true, bindAs: true, requiresSuper: true, dynamicDependency: true); if (minfo.is_ctor && minfo.is_protocol_member) { sb.Append ("T? "); @@ -3063,7 +3057,18 @@ void GenerateInvoke (bool stret, bool supercall, MethodInfo mi, MemberInformatio var isInstanceMethod = category_type is null && !minfo.is_extension_method && !minfo.is_protocol_implementation_method; string? target_name = isInstanceMethod ? "this" : "This"; - string handle = supercall ? ".SuperHandle" : ".Handle"; + string handle = supercall ? "" : ".Handle"; + string receiver; + + // For super calls on instance methods, emit a stack-allocated ObjCSuper and pass its address. + if (supercall && !minfo.is_static) { + print ("unsafe {"); + indent++; + print ("var __objc_super__ = new global::ObjCRuntime.ObjCSuper ({0});", target_name); + receiver = "&__objc_super__"; + } else { + receiver = ""; + } // If we have supercall == false, we can be a Bind method that has a [Target] if (supercall == false && !minfo.is_static) { @@ -3075,13 +3080,8 @@ void GenerateInvoke (bool stret, bool supercall, MethodInfo mi, MemberInformatio if (mai.PlainString) ErrorHelper.Warning (1101); - if (mai.ZeroCopyStringMarshal) { - target_name = "(IntPtr)(&_s" + pi.Name + ")"; - handle = ""; - } else { - target_name = "ns" + pi.Name; - handle = ""; - } + target_name = "ns" + pi.Name; + handle = ""; } else target_name = pi.Name.GetSafeParamName (); break; @@ -3110,8 +3110,10 @@ void GenerateInvoke (bool stret, bool supercall, MethodInfo mi, MemberInformatio var ret_val = "(IntPtr*) aligned_ret"; if (minfo.is_static) print ("{0} ({5}, class_ptr, {3}{4});", sig, "/*unusued*/", "/*unusued*/", selector_field, args, ret_val); - else - print ("{0} ({5}, {1}{2}, {3}{4});", sig, target_name, handle, selector_field, args, ret_val); + else { + var rcv = receiver.Length > 0 ? receiver : target_name + handle; + print ("{0} ({3}, {1}, {2}{4});", sig, rcv, selector_field, ret_val, args); + } print ("aligned_assigned = true;"); } else if (minfo.is_protocol_member && mi.Name == "Constructor") { @@ -3138,12 +3140,13 @@ void GenerateInvoke (bool stret, bool supercall, MethodInfo mi, MemberInformatio cast_a, sig, target_name, "/*unusued3*/", //supercall ? "Super" : "", selector_field, args, cast_b); - else - print ("{0}{1}{2} ({3}{4}, {5}{6}){7};", + else { + var rcv = receiver.Length > 0 ? receiver : target_name + handle; + print ("{0}{1}{2} ({3}, {4}{5}){6};", returns ? "ret = " : "", - cast_a, sig, target_name, - handle, + cast_a, sig, rcv, selector_field, args, cast_b); + } if (postproc.Length > 0) print (postproc.ToString ()); @@ -3153,6 +3156,10 @@ void GenerateInvoke (bool stret, bool supercall, MethodInfo mi, MemberInformatio // if this is a extension of any kind, ensure that we keep alive the this parameter // so that it is not collected before the msg send call has completed. print ("GC.KeepAlive (This);"); + } else if (supercall) { + print ("GC.KeepAlive ({0});", target_name); + indent--; + print ("}"); // close unsafe block } } @@ -3219,48 +3226,16 @@ bool IsOptimizable (MemberInfo method) // @probe_null: determines whether null is allowed, and // whether we need to generate code to handle this // - // @must_copy: determines whether to create a new NSString, necessary - // for NSString properties that are flagged with "retain" instead of "copy" - // - // @prefix: prefix to prepend on each line - // // @property: the name of the property // - public string GenerateMarshalString (bool probe_null, bool must_copy) + public string GenerateMarshalString (bool probe_null) { - if (must_copy) { - return "var ns{0} = CFString.CreateNative ({1});\n"; - } - return - "ObjCRuntime.NSStringStruct _s{0}; Console.WriteLine (\"" + CurrentMethod + ": Marshalling: {{1}}\", {1}); \n" + - "_s{0}.ClassPtr = ObjCRuntime.NSStringStruct.ReferencePtr;\n" + - "_s{0}.Flags = 0x010007d1; // RefCount=1, Unicode, InlineContents = 0, DontFreeContents\n" + - "_s{0}.UnicodePtr = _p{0};\n" + - "_s{0}.Length = " + (probe_null ? "{1} is null ? 0 : {1}.Length;" : "{1}.Length;\n"); - } - - public string GenerateDisposeString (bool probe_null, bool must_copy) - { - if (must_copy) { - return "CFString.ReleaseNative (ns{0});\n"; - } else - return "if (_s{0}.Flags != 0x010007d1) throw new Exception (\"String was retained, not copied\");"; + return "var ns{0} = CFString.CreateNative ({1});\n"; } - List? CollectFastStringMarshalParameters (MethodInfo mi) + public string GenerateDisposeString (bool probe_null) { - List? stringParameters = null; - - foreach (var pi in mi.GetParameters ()) { - var mai = new MarshalInfo (this, mi, pi); - - if (mai.ZeroCopyStringMarshal) { - if (stringParameters is null) - stringParameters = new List (); - stringParameters.Add (pi.Name.GetSafeParamName () ?? ""); - } - } - return stringParameters; + return "CFString.ReleaseNative (ns{0});\n"; } AvailabilityBaseAttribute? GetIntroduced (Type? type, string methodName) @@ -3342,8 +3317,8 @@ void GenerateTypeLowering (MethodInfo mi, bool null_allowed_override, out String if (mai.Type == TypeCache.System_String && !mai.PlainString) { bool probe_null = null_allowed_override || AttributeManager.IsNullable (pi); - convs.AppendFormat (GenerateMarshalString (probe_null, !mai.ZeroCopyStringMarshal), pi.Name, pi.Name.GetSafeParamName ()); - disposes.AppendFormat (GenerateDisposeString (probe_null, !mai.ZeroCopyStringMarshal), pi.Name); + convs.AppendFormat (GenerateMarshalString (probe_null), pi.Name, pi.Name.GetSafeParamName ()); + disposes.AppendFormat (GenerateDisposeString (probe_null), pi.Name); } else if (mai.Type.TryIsArray (out var etype)) { if (HasBindAsAttribute (pi)) { convs.AppendFormat ("using var nsb_{0} = {1}\n", pi.Name, GetToBindAsWrapper (mi, null, pi)); @@ -3586,9 +3561,6 @@ public void GenerateMethodBody (MemberInformation minfo, MethodInfo mi, string? GenerateArgumentChecks (mi, false, propInfo, out bool needsGCKeepAlives); - // Collect all strings that can be fast-marshalled - var stringParameters = CollectFastStringMarshalParameters (mi); - GenerateTypeLowering (mi, null_allowed_override, out var args, out var convs, out var disposes, out var by_ref_processing, out var by_ref_init, out var post_return, propInfo); if (minfo.is_protocol_member && minfo.is_static) { @@ -3600,12 +3572,6 @@ public void GenerateMethodBody (MemberInformation minfo, MethodInfo mi, string? if (by_ref_init.Length > 0) print (by_ref_init.ToString ()); - if (stringParameters is not null) { - print ("fixed (char * {0}){{", - stringParameters.Select (name => "_p" + name + " = " + name).Aggregate ((first, second) => first + ", " + second)); - indent++; - } - if (propInfo is not null && IsSetter (mi) && HasBindAsAttribute (propInfo)) { convs.AppendFormat ("using var nsb_{0} = {1}\n", propInfo.Name, GetToBindAsWrapper (mi, minfo, null)); } @@ -3805,10 +3771,6 @@ public void GenerateMethodBody (MemberInformation minfo, MethodInfo mi, string? WriteMarkDirtyIfDerived (sw, mi.DeclaringType!); if (post_return?.Length > 0) print (post_return.ToString ()); - if (stringParameters is not null) { - indent--; - print ("}"); - } indent--; } @@ -4075,7 +4037,7 @@ void GenerateProperty (Type type, PropertyInfo pi, List? instance_fields pi.Name.GetSafeParamName ()); indent++; if (generate_getter) { - PrintAttributes (pi.GetGetMethod ()!, platform: true, preserve: true, advice: true); + PrintAttributes (pi.GetGetMethod ()!, platform: true, preserve: true, advice: true, dynamicDependency: true); print ("get {"); indent++; @@ -4094,7 +4056,7 @@ void GenerateProperty (Type type, PropertyInfo pi, List? instance_fields print ("}"); } if (generate_setter) { - PrintAttributes (pi.GetSetMethod ()!, platform: true, preserve: true, advice: true); + PrintAttributes (pi.GetSetMethod ()!, platform: true, preserve: true, advice: true, dynamicDependency: true); print ("set {"); indent++; @@ -4168,7 +4130,7 @@ void GenerateProperty (Type type, PropertyInfo pi, List? instance_fields // If property getter or setter has its own WrapAttribute we let the user do whatever their heart desires if (generate_getter) { PrintAttributes (pi, platform: true); - PrintAttributes (pi.GetGetMethod (), platform: true, preserve: true, advice: true); + PrintAttributes (pi.GetGetMethod (), platform: true, preserve: true, advice: true, dynamicDependency: true); print ("get {"); indent++; @@ -4208,7 +4170,7 @@ void GenerateProperty (Type type, PropertyInfo pi, List? instance_fields PrintExport (minfo, sel, export!.ArgumentSemantic); } - PrintAttributes (pi.GetGetMethod (), platform: true, preserve: true, advice: true, notImplemented: true, inlinedType: inlinedType); + PrintAttributes (pi.GetGetMethod (), platform: true, preserve: true, advice: true, notImplemented: true, inlinedType: inlinedType, dynamicDependency: true); if (minfo.is_protocol_member && !minfo.is_static) { print ("get {"); print ($"\treturn _Get{pi.Name.GetSafeParamName ()} (this);"); @@ -4264,7 +4226,7 @@ void GenerateProperty (Type type, PropertyInfo pi, List? instance_fields if (not_implemented_attr is null && (!minfo.is_sealed || !minfo.is_wrapper)) PrintExport (minfo, sel, export!.ArgumentSemantic); - PrintAttributes (pi.GetSetMethod (), platform: true, preserve: true, advice: true, notImplemented: true, inlinedType: inlinedType); + PrintAttributes (pi.GetSetMethod (), platform: true, preserve: true, advice: true, notImplemented: true, inlinedType: inlinedType, dynamicDependency: true); if (minfo.is_protocol_member && !minfo.is_static) { print ("set {"); print ($"\t_Set{pi.Name.GetSafeParamName ()} (this, value);"); @@ -5547,7 +5509,7 @@ public void PrintBindAsAttribute (ICustomAttributeProvider? mi, StringBuilder? s // Not adding the experimental attribute is bad (it would mean that an API // we meant to be experimental ended up being released as stable), so it's // opt-out instead of opt-in. - public void PrintAttributes (ICustomAttributeProvider? mi, bool platform = false, bool preserve = false, bool advice = false, bool notImplemented = false, bool bindAs = false, bool requiresSuper = false, Type? inlinedType = null, bool experimental = true, bool obsolete = false, bool objectiveCFramework = false) + public void PrintAttributes (ICustomAttributeProvider? mi, bool platform = false, bool preserve = false, bool advice = false, bool notImplemented = false, bool bindAs = false, bool requiresSuper = false, Type? inlinedType = null, bool experimental = true, bool obsolete = false, bool objectiveCFramework = false, bool simulatorAvailability = true, bool dynamicDependency = false) { if (platform) PrintPlatformAttributes (mi as MemberInfo, inlinedType); @@ -5567,6 +5529,72 @@ public void PrintAttributes (ICustomAttributeProvider? mi, bool platform = false PrintObsoleteAttributes (mi); if (objectiveCFramework) PrintObjectiveCFrameworkAttribute (mi); + if (simulatorAvailability) + PrintSimulatorAvailabilityAttributes (mi); + if (dynamicDependency) + PrintDynamicDependencyAttributes (mi); + } + + public void PrintDynamicDependencyAttributes (ICustomAttributeProvider? mi) + { + if (mi is not MemberInfo memberInfo) + return; + + var allAttribs = memberInfo.GetCustomAttributesData (); + foreach (var attrib in allAttribs) { + if (attrib.GetAttributeType ().FullName != "System.Diagnostics.CodeAnalysis.DynamicDependencyAttribute") + continue; + var args = attrib.ConstructorArguments; + var parts = new List (); + foreach (var arg in args) { + if (arg.Value is string stringValue) { + parts.Add ($"\"{stringValue}\""); + } else if (arg.Value is int intValue) { + parts.Add (FormatDynamicallyAccessedMemberTypes (intValue)); + } else if (arg.Value is Type typeValue) { + parts.Add ($"typeof ({typeValue})"); + } else { + exceptions.Add (ErrorHelper.CreateError (99, $"Unexpected attribute argument value for DynamicDependency attribute: {arg.ArgumentType.FullName} => {arg.Value}")); + } + } + print ($"[DynamicDependency ({string.Join (", ", parts)})]"); + } + } + + static string FormatDynamicallyAccessedMemberTypes (int memberTypes) + { + if (memberTypes == -1) // All + return "DynamicallyAccessedMemberTypes.All"; + if (memberTypes == 0) // None + return "DynamicallyAccessedMemberTypes.None"; + + // Use the composite values first to match the original source + var flagValues = new (int value, string name) [] { + (3, "PublicConstructors"), // 3 includes PublicParameterlessConstructor + (1, "PublicParameterlessConstructor"), + (4, "NonPublicConstructors"), + (8, "PublicMethods"), + (16, "NonPublicMethods"), + (32, "PublicFields"), + (64, "NonPublicFields"), + (128, "PublicNestedTypes"), + (256, "NonPublicNestedTypes"), + (512, "PublicProperties"), + (1024, "NonPublicProperties"), + (2048, "PublicEvents"), + (4096, "NonPublicEvents"), + (8192, "Interfaces"), + }; + + var parts = new List (); + var remaining = memberTypes; + foreach (var (value, name) in flagValues) { + if (value != 0 && (remaining & value) == value) { + parts.Add ($"DynamicallyAccessedMemberTypes.{name}"); + remaining &= ~value; + } + } + return string.Join (" | ", parts); } public void PrintExperimentalAttribute (ICustomAttributeProvider? mi) @@ -5585,6 +5613,62 @@ public void PrintObjectiveCFrameworkAttribute (ICustomAttributeProvider? mi) print ($"[ObjectiveCFramework (\"{attrib.Framework}\")]"); } + public void PrintSimulatorAvailabilityAttributes (ICustomAttributeProvider? provider) + { + if (!TryGetSimulatorAvailabilityPlatformName (out var platformName)) + return; + + PrintSupportedSimulatorAttribute (provider, platformName); + PrintUnsupportedSimulatorAttribute (provider, platformName); + } + + bool TryGetSimulatorAvailabilityPlatformName ([NotNullWhen (true)] out string? platformName) + { + platformName = null; + + switch (CurrentPlatform) { + case PlatformName.MacCatalyst: + case PlatformName.MacOSX: + return false; + case PlatformName.iOS: + platformName = "ios"; + return true; + case PlatformName.TvOS: + platformName = "tvos"; + return true; + default: + throw new BindingException (1047, CurrentPlatform); + } + } + + void PrintSupportedSimulatorAttribute (ICustomAttributeProvider? provider, string platformName) + { + var attribs = AttributeManager.GetCustomAttributes (provider); + if (attribs?.Any () != true) + return; + + // Only print the attribute for the current platform, we don't care about other platforms. + foreach (var attrib in attribs) { + if (!attrib.PlatformName.StartsWith (platformName, StringComparison.OrdinalIgnoreCase)) + continue; + print ($"[SupportedSimulator (\"{attrib.PlatformName}\")]"); + } + } + + void PrintUnsupportedSimulatorAttribute (ICustomAttributeProvider? provider, string platformName) + { + var attribs = AttributeManager.GetCustomAttributes (provider); + if (attribs?.Any () != true) + return; + + // Only print the attribute for the current platform, we don't care about other platforms. + foreach (var attrib in attribs) { + if (!attrib.PlatformName.StartsWith (platformName, StringComparison.OrdinalIgnoreCase)) + continue; + print ($"[UnsupportedSimulator (\"{attrib.PlatformName}\")]"); + } + } + bool WriteDocumentation (MemberInfo info, Func? transformNode = null) { return DocumentationManager.WriteDocumentation (sw!, indent, info, transformNode); @@ -5682,12 +5766,6 @@ public void Generate (Type type) if (is_rgen_type) return; - if (ZeroCopyStrings) { - ErrorHelper.Warning (1027); - ZeroCopyStrings = false; - } - - type_wants_zero_copy = AttributeManager.HasAttribute (type) || ZeroCopyStrings; var tsa = AttributeManager.GetCustomAttribute (type); // if we're inside a special namespace then default is non-thread safe, otherwise default is thread safe if (NamespaceCache.UINamespaces.Contains (type.Namespace!)) { @@ -6047,7 +6125,7 @@ public void Generate (Type type) var indentation = 3; WriteIsDirectBindingCondition (sw, ref indentation, is_direct_binding, is_direct_binding_value, () => string.Format ("InitializeHandle (global::{1}.IntPtr_objc_msgSend (this.Handle, global::ObjCRuntime.{0}), \"init\");", initSelector, NamespaceCache.Messaging), - () => string.Format ("InitializeHandle (global::{1}.IntPtr_objc_msgSendSuper (this.SuperHandle, global::ObjCRuntime.{0}), \"init\");", initSelector, NamespaceCache.Messaging)); + () => string.Format ("unsafe {{\nvar __objc_super__ = new global::ObjCRuntime.ObjCSuper (this);\nInitializeHandle (global::{1}.IntPtr_objc_msgSendSuper (&__objc_super__, global::ObjCRuntime.{0}), \"init\");\nGC.KeepAlive (this);\n}}", initSelector, NamespaceCache.Messaging)); WriteMarkDirtyIfDerived (sw, type); sw.WriteLine ("\t\t}"); @@ -6080,7 +6158,7 @@ public void Generate (Type type) var indentation = 3; WriteIsDirectBindingCondition (sw, ref indentation, is_direct_binding, is_direct_binding_value, () => string.Format ("InitializeHandle (global::{1}.IntPtr_objc_msgSend_IntPtr (this.Handle, {0}, coder.Handle), \"initWithCoder:\");", initWithCoderSelector, NamespaceCache.Messaging), - () => string.Format ("InitializeHandle (global::{1}.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, {0}, coder.Handle), \"initWithCoder:\");", initWithCoderSelector, NamespaceCache.Messaging)); + () => string.Format ("unsafe {{\nvar __objc_super__ = new global::ObjCRuntime.ObjCSuper (this);\nInitializeHandle (global::{1}.IntPtr_objc_msgSendSuper_IntPtr (&__objc_super__, {0}, coder.Handle), \"initWithCoder:\");\nGC.KeepAlive (this);\n}}", initWithCoderSelector, NamespaceCache.Messaging)); WriteMarkDirtyIfDerived (sw, type); sw.WriteLine ("\t\t\tGC.KeepAlive (coder);"); } else { @@ -6131,7 +6209,11 @@ public void Generate (Type type) sw.WriteLine ("\t\t/// if (IsDirectBinding) {"); sw.WriteLine ("\t\t/// Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame);"); sw.WriteLine ("\t\t/// } else {"); - sw.WriteLine ("\t\t/// Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame);"); + sw.WriteLine ("\t\t/// unsafe {"); + sw.WriteLine ("\t\t/// var __objc_super__ = new ObjCRuntime.ObjCSuper (this);"); + sw.WriteLine ("\t\t/// Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame);"); + sw.WriteLine ("\t\t/// }"); + sw.WriteLine ("\t\t/// GC.KeepAlive (this);"); sw.WriteLine ("\t\t/// }"); sw.WriteLine ("\t\t/// }"); sw.WriteLine ("\t\t/// ]]>"); @@ -6918,7 +7000,12 @@ public void Generate (Type type) print ("return {0} is not null;", mi.Name.PascalCase ()); --indent; } - print ("return global::" + NamespaceCache.Messaging + ".bool_objc_msgSendSuper_IntPtr (SuperHandle, " + selRespondsToSelector + ", selHandle) != 0;"); + print ("unsafe {"); + indent++; + print ("var __objc_super__ = new global::ObjCRuntime.ObjCSuper (this);"); + print ("return global::" + NamespaceCache.Messaging + ".bool_objc_msgSendSuper_IntPtr (&__objc_super__, " + selRespondsToSelector + ", selHandle) != 0;"); + indent--; + print ("}"); --indent; print ("}"); @@ -6926,7 +7013,7 @@ public void Generate (Type type) // bool_objc_msgSendSuper_IntPtr: for respondsToSelector: if (!send_methods.ContainsKey ("bool_objc_msgSendSuper_IntPtr")) { print (m, "[DllImport (LIBOBJC_DYLIB, EntryPoint=\"objc_msgSendSuper\")]"); - print (m, "public extern static byte bool_objc_msgSendSuper_IntPtr (IntPtr receiever, IntPtr selector, IntPtr arg1);"); + print (m, "public unsafe extern static byte bool_objc_msgSendSuper_IntPtr (ObjCSuper* receiever, IntPtr selector, IntPtr arg1);"); RegisterMethodName ("bool_objc_msgSendSuper_IntPtr"); } } diff --git a/src/bgen/Models/BindingTouchConfig.cs b/src/bgen/Models/BindingTouchConfig.cs index 0aa0d50b614f..4cad9cbbba2f 100644 --- a/src/bgen/Models/BindingTouchConfig.cs +++ b/src/bgen/Models/BindingTouchConfig.cs @@ -5,7 +5,6 @@ public class BindingTouchConfig { public bool ShowHelp = false; - public bool UseZeroCopy = false; public string? BindingFilesOutputDirectory = null; public string? TemporaryFileDirectory = null; public string? HelperClassNamespace = null; diff --git a/src/bgen/Models/MarshalInfo.cs b/src/bgen/Models/MarshalInfo.cs index 27c4a52c6fea..091b1dc32ffd 100644 --- a/src/bgen/Models/MarshalInfo.cs +++ b/src/bgen/Models/MarshalInfo.cs @@ -13,10 +13,6 @@ public class MarshalInfo { public Type Type { get; } public bool IsOut { get; } - // This is set on a string parameter if the argument parameters are set to - // Copy. This means that we can do fast string passing. - public bool ZeroCopyStringMarshal { get; set; } - public bool IsAligned; // Used for parameters @@ -25,9 +21,6 @@ public MarshalInfo (Generator generator, MethodInfo mi, ParameterInfo pi) this.Generator = generator; PlainString = Generator.AttributeManager.HasAttribute (pi); Type = pi.ParameterType; - ZeroCopyStringMarshal = (Type == Generator.TypeCache.System_String) && PlainString == false && !Generator.AttributeManager.HasAttribute (pi) && generator.type_wants_zero_copy; - if (ZeroCopyStringMarshal && Generator.AttributeManager.HasAttribute (mi)) - ZeroCopyStringMarshal = false; IsOut = pi.IsOut; } diff --git a/src/bgen/bgen.csproj b/src/bgen/bgen.csproj index e8b0fed1788c..fa063bd5b43a 100644 --- a/src/bgen/bgen.csproj +++ b/src/bgen/bgen.csproj @@ -7,8 +7,6 @@ DEBUG;BGENERATOR;NET_4_0;NO_AUTHENTICODE;STATIC;NO_SYMBOL_WRITER;NET $(DefineConstants);XAMMACIOS_DEBUGGER - Nullable - enable APL0003 @@ -38,6 +36,7 @@ + @@ -59,6 +58,7 @@ + diff --git a/src/coreanimation.cs b/src/coreanimation.cs index e30d4d2d5e38..4ac80ab97faf 100644 --- a/src/coreanimation.cs +++ b/src/coreanimation.cs @@ -2028,7 +2028,7 @@ interface ICALayerDelegate { } /// Delegate class for the CALayer. /// - /// Apple documentation for CALayerDelegate + /// Apple documentation for CALayerDelegate [BaseType (typeof (NSObject))] [Model] #if IOS || TVOS @@ -2529,7 +2529,7 @@ interface CABasicAnimation { /// A spring animation with stiffness, mass, and damping. /// - /// Apple documentation for CASpringAnimation + /// Apple documentation for CASpringAnimation [MacCatalyst (13, 1)] [BaseType (typeof (CABasicAnimation))] interface CASpringAnimation { diff --git a/src/corebluetooth.cs b/src/corebluetooth.cs index b5d8f22930bb..3b1fc5133c5c 100644 --- a/src/corebluetooth.cs +++ b/src/corebluetooth.cs @@ -791,7 +791,6 @@ interface CBPeripheral : NSCopying { /// To be added. /// To be added. [Export ("name", ArgumentSemantic.Retain)] - [DisableZeroCopy] [NullAllowed] string Name { get; } diff --git a/src/coreml.cs b/src/coreml.cs index b723bf9afee6..c4d6c7038e82 100644 --- a/src/coreml.cs +++ b/src/coreml.cs @@ -1581,9 +1581,9 @@ interface MLWritable { } #if !XAMCORE_5_0 - [Deprecated (PlatformName.MacOSX, 13, 3, message: "Use Background Assets or 'NSUrlSession' instead.")] - [Deprecated (PlatformName.MacCatalyst, 16, 4, message: "Use Background Assets or 'NSUrlSession' instead.")] - [Deprecated (PlatformName.iOS, 16, 4, message: "Use Background Assets or 'NSUrlSession' instead.")] + [Obsoleted (PlatformName.MacOSX, 13, 3, message: "Use Background Assets or 'NSUrlSession' instead.")] + [Obsoleted (PlatformName.MacCatalyst, 16, 4, message: "Use Background Assets or 'NSUrlSession' instead.")] + [Obsoleted (PlatformName.iOS, 16, 4, message: "Use Background Assets or 'NSUrlSession' instead.")] [iOS (14, 0)] [MacCatalyst (14, 0)] [NoTV] @@ -1613,9 +1613,9 @@ interface MLModelCollection { #endif // !XAMCORE_5_0 #if !XAMCORE_5_0 - [Deprecated (PlatformName.MacOSX, 13, 3, message: "Use Background Assets or 'NSUrlSession' instead.")] - [Deprecated (PlatformName.MacCatalyst, 16, 4, message: "Use Background Assets or 'NSUrlSession' instead.")] - [Deprecated (PlatformName.iOS, 16, 4, message: "Use Background Assets or 'NSUrlSession' instead.")] + [Obsoleted (PlatformName.MacOSX, 13, 3, message: "Use Background Assets or 'NSUrlSession' instead.")] + [Obsoleted (PlatformName.MacCatalyst, 16, 4, message: "Use Background Assets or 'NSUrlSession' instead.")] + [Obsoleted (PlatformName.iOS, 16, 4, message: "Use Background Assets or 'NSUrlSession' instead.")] [iOS (14, 0)] [MacCatalyst (14, 0)] [NoTV] diff --git a/src/dotnet.tmpl.csproj b/src/dotnet.tmpl.csproj index cb5a69556c5f..a386a3307f42 100644 --- a/src/dotnet.tmpl.csproj +++ b/src/dotnet.tmpl.csproj @@ -9,7 +9,6 @@ Microsoft.%PLATFORM% true ..\..\..\..\..\product.snk - latest MINIMAL true BI1234,108,114,219,414,618,660,661,1635,3003,3014,3021,4014 diff --git a/src/foundation.cs b/src/foundation.cs index 915fe5d0c9f7..8ceba04a14c1 100644 --- a/src/foundation.cs +++ b/src/foundation.cs @@ -13062,6 +13062,7 @@ interface NSObject2 : NSObjectProtocol { [NoTV] [NoiOS] [NoMacCatalyst] + [ObjectiveCFramework ("AppKit")] interface NSBindingSelectionMarker : NSCopying { /// To be added. /// To be added. diff --git a/src/frameworks.sources b/src/frameworks.sources index 75b8ccfcd59e..c715fddb973f 100644 --- a/src/frameworks.sources +++ b/src/frameworks.sources @@ -130,6 +130,7 @@ APPKIT_SOURCES = \ AppKit/NSPopUpButtonCell.cs \ AppKit/NSPredicateEditorRowTemplate.cs \ AppKit/NSPrintInfo.cs \ + AppKit/NSPrintPreviewGraphicsContext.cs \ AppKit/NSScreen.cs \ AppKit/NSSegmentedControl.cs \ AppKit/NSSharingService.cs \ @@ -1908,12 +1909,14 @@ SHARED_CORE_SOURCES = \ ObjCRuntime/TransientCFString.cs \ ObjCRuntime/TransientString.cs \ ObjCRuntime/NFloat.cs \ + ObjCRuntime/ObjCSuper.cs \ ObjCRuntime/ObjectiveCFrameworkAttribute.cs \ ObjCRuntime/ObsoleteConstants.cs \ ObjCRuntime/Protocol.cs \ ObjCRuntime/Registrar.core.cs \ ObjCRuntime/RequiresSuperAttribute.cs \ ObjCRuntime/Selector.cs \ + ObjCRuntime/SupportedSimulatorAttribute.cs \ ObjCRuntime/SystemVersion.cs \ ObjCRuntime/ThrowHelper.cs \ Simd/MathHelper.cs \ diff --git a/src/fskit.cs b/src/fskit.cs index 4194d8922171..f6375c47934a 100644 --- a/src/fskit.cs +++ b/src/fskit.cs @@ -897,7 +897,7 @@ interface FSVolumeOperations : FSVolumePathConfOperations { bool EnableOpenUnlinkEmulation { get; set; } /// Gets or sets the mount options that the file system requests from FSKit. - /// FSKit reads this value after the volume replies to the call. Changing the returned value during the runtime of the volume has no effect. + /// FSKit reads this value after the volume replies to the call. Changing the returned value during the runtime of the volume has no effect. [Mac (26, 0)] [Export ("requestedMountOptions", ArgumentSemantic.Assign)] FSMountOptions RequestedMountOptions { get; set; } diff --git a/src/glkit.cs b/src/glkit.cs index 9d70fa9313a6..609394d61ab9 100644 --- a/src/glkit.cs +++ b/src/glkit.cs @@ -171,7 +171,6 @@ interface GLKBaseEffect : GLKNamedEffect { /// /// To be added. [Export ("label", ArgumentSemantic.Copy)] - [DisableZeroCopy] [NullAllowed] // default is null on iOS 5.1.1 string Label { get; set; } @@ -583,7 +582,6 @@ interface GLKSkyboxEffect : GLKNamedEffect { /// To be added. [NullAllowed] // by default this property is null [Export ("label", ArgumentSemantic.Copy)] - [DisableZeroCopy] string Label { get; set; } /// To be added. diff --git a/src/mapkit.cs b/src/mapkit.cs index 1b4f59ee6e06..bc577b1f9f5f 100644 --- a/src/mapkit.cs +++ b/src/mapkit.cs @@ -2067,6 +2067,7 @@ partial interface MKRouteStep { [BaseType (typeof (NSFormatter))] [MacCatalyst (13, 1)] + [ThreadSafe] partial interface MKDistanceFormatter { [Export ("stringFromDistance:")] diff --git a/src/metal.cs b/src/metal.cs index 4e67fa75aeab..b29676ad9f8b 100644 --- a/src/metal.cs +++ b/src/metal.cs @@ -5926,6 +5926,8 @@ interface MTLIndirectCommandBuffer : MTLResource { MTLResourceId GpuResourceID { get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [iOS (13, 0), TV (13, 0)] [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] @@ -7804,6 +7806,8 @@ interface IMTLResidencySet { } interface IMTL4Archive { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4Archive { @@ -7843,6 +7847,9 @@ interface MTL4Archive { } interface IMTL4ArgumentTable { } + + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4ArgumentTable { @@ -7877,6 +7884,8 @@ interface MTL4ArgumentTable { interface IMTL4BinaryFunction { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4BinaryFunction { @@ -7891,6 +7900,8 @@ interface MTL4BinaryFunction { interface IMTL4CommandAllocator { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4CommandAllocator { @@ -7913,6 +7924,8 @@ interface MTL4CommandAllocator { interface IMTL4CommandBuffer { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4CommandBuffer { @@ -7983,6 +7996,8 @@ interface MTL4CommandBuffer { interface IMTL4CommandEncoder { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4CommandEncoder { @@ -8033,6 +8048,8 @@ interface MTL4CommandEncoder { interface IMTL4CommandQueue { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4CommandQueue { @@ -8103,6 +8120,8 @@ interface MTL4CommandQueue { interface IMTL4CommitFeedback { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4CommitFeedback { @@ -8122,6 +8141,8 @@ interface MTL4CommitFeedback { interface IMTL4CompilerTask { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4CompilerTask { @@ -8149,6 +8170,8 @@ interface MTL4CompilerTask { interface IMTL4Compiler { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4Compiler { @@ -8277,6 +8300,8 @@ interface MTL4Compiler { interface IMTL4ComputeCommandEncoder { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4ComputeCommandEncoder : MTL4CommandEncoder { @@ -8427,6 +8452,8 @@ interface MTL4ComputeCommandEncoder : MTL4CommandEncoder { interface IMTL4CounterHeap { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4CounterHeap { @@ -8454,6 +8481,8 @@ interface MTL4CounterHeap { interface IMTL4MachineLearningCommandEncoder { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4MachineLearningCommandEncoder : MTL4CommandEncoder { @@ -8472,6 +8501,8 @@ interface MTL4MachineLearningCommandEncoder : MTL4CommandEncoder { interface IMTL4MachineLearningPipelineState { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4MachineLearningPipelineState : MTLAllocation { @@ -8494,6 +8525,8 @@ interface MTL4MachineLearningPipelineState : MTLAllocation { interface IMTL4PipelineDataSetSerializer { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4PipelineDataSetSerializer { @@ -8509,6 +8542,8 @@ interface MTL4PipelineDataSetSerializer { interface IMTL4RenderCommandEncoder { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [Protocol (BackwardsCompatibleCodeGeneration = false)] interface MTL4RenderCommandEncoder : MTL4CommandEncoder { @@ -8782,6 +8817,8 @@ interface MTLTextureViewPool : MTLResourceViewPool { MTLResourceId SetTextureViewFromBuffer (IMTLBuffer buffer, MTLTextureDescriptor descriptor, nuint offset, nuint bytesPerRow, nuint index); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4AccelerationStructureGeometryDescriptor))] interface MTL4AccelerationStructureBoundingBoxGeometryDescriptor { @@ -8795,6 +8832,8 @@ interface MTL4AccelerationStructureBoundingBoxGeometryDescriptor { nuint BoundingBoxCount { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4AccelerationStructureGeometryDescriptor))] interface MTL4AccelerationStructureCurveGeometryDescriptor { @@ -8841,11 +8880,15 @@ interface MTL4AccelerationStructureCurveGeometryDescriptor { MTLCurveEndCaps CurveEndCaps { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTLAccelerationStructureDescriptor))] interface MTL4AccelerationStructureDescriptor { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4AccelerationStructureGeometryDescriptor : NSCopying { @@ -8871,6 +8914,8 @@ interface MTL4AccelerationStructureGeometryDescriptor : NSCopying { nuint PrimitiveDataElementSize { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4AccelerationStructureGeometryDescriptor))] interface MTL4AccelerationStructureMotionBoundingBoxGeometryDescriptor { @@ -8884,6 +8929,8 @@ interface MTL4AccelerationStructureMotionBoundingBoxGeometryDescriptor { nuint BoundingBoxCount { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4AccelerationStructureGeometryDescriptor))] interface MTL4AccelerationStructureMotionCurveGeometryDescriptor { @@ -8930,6 +8977,8 @@ interface MTL4AccelerationStructureMotionCurveGeometryDescriptor { MTLCurveEndCaps CurveEndCaps { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4AccelerationStructureGeometryDescriptor))] interface MTL4AccelerationStructureMotionTriangleGeometryDescriptor { @@ -8958,6 +9007,8 @@ interface MTL4AccelerationStructureMotionTriangleGeometryDescriptor { MTLMatrixLayout TransformationMatrixLayout { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4AccelerationStructureGeometryDescriptor))] interface MTL4AccelerationStructureTriangleGeometryDescriptor { @@ -8986,6 +9037,8 @@ interface MTL4AccelerationStructureTriangleGeometryDescriptor { MTLMatrixLayout TransformationMatrixLayout { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4ArgumentTableDescriptor : NSCopying { @@ -9008,6 +9061,8 @@ interface MTL4ArgumentTableDescriptor : NSCopying { string Label { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4BinaryFunctionDescriptor : NSCopying { @@ -9021,6 +9076,8 @@ interface MTL4BinaryFunctionDescriptor : NSCopying { MTL4BinaryFunctionOptions Options { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4CommandAllocatorDescriptor : NSCopying { @@ -9028,6 +9085,8 @@ interface MTL4CommandAllocatorDescriptor : NSCopying { string Label { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4CommandBufferOptions : NSCopying { @@ -9035,6 +9094,8 @@ interface MTL4CommandBufferOptions : NSCopying { IMTLLogState LogState { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4CommandQueueDescriptor : NSCopying { @@ -9047,6 +9108,8 @@ interface MTL4CommandQueueDescriptor : NSCopying { delegate void MTL4CommitFeedbackHandler (IMTL4CommitFeedback commitFeedback); + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4CommitOptions { @@ -9054,6 +9117,8 @@ interface MTL4CommitOptions { void AddFeedbackHandler (MTL4CommitFeedbackHandler block); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4CompilerDescriptor : NSCopying { @@ -9064,6 +9129,8 @@ interface MTL4CompilerDescriptor : NSCopying { IMTL4PipelineDataSetSerializer PipelineDataSetSerializer { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4CompilerTaskOptions : NSCopying { @@ -9071,6 +9138,8 @@ interface MTL4CompilerTaskOptions : NSCopying { IMTL4Archive [] LookupArchives { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4PipelineDescriptor))] interface MTL4ComputePipelineDescriptor { @@ -9099,6 +9168,8 @@ interface MTL4ComputePipelineDescriptor { void Reset (); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4CounterHeapDescriptor : NSCopying { @@ -9109,11 +9180,15 @@ interface MTL4CounterHeapDescriptor : NSCopying { nuint Count { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4FunctionDescriptor : NSCopying { } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4AccelerationStructureDescriptor))] interface MTL4IndirectInstanceAccelerationStructureDescriptor { @@ -9151,6 +9226,8 @@ interface MTL4IndirectInstanceAccelerationStructureDescriptor { nuint MotionTransformStride { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4AccelerationStructureDescriptor))] interface MTL4InstanceAccelerationStructureDescriptor { @@ -9182,6 +9259,8 @@ interface MTL4InstanceAccelerationStructureDescriptor { nuint MotionTransformStride { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4LibraryDescriptor : NSCopying { @@ -9195,6 +9274,8 @@ interface MTL4LibraryDescriptor : NSCopying { string Name { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4FunctionDescriptor))] interface MTL4LibraryFunctionDescriptor { @@ -9205,6 +9286,8 @@ interface MTL4LibraryFunctionDescriptor { IMTLLibrary Library { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4PipelineDescriptor))] interface MTL4MachineLearningPipelineDescriptor { @@ -9228,6 +9311,8 @@ interface MTL4MachineLearningPipelineDescriptor { void Reset (); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4MachineLearningPipelineReflection { @@ -9235,6 +9320,8 @@ interface MTL4MachineLearningPipelineReflection { IMTLBinding [] Bindings { get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4PipelineDescriptor))] interface MTL4MeshRenderPipelineDescriptor { @@ -9317,6 +9404,8 @@ interface MTL4MeshRenderPipelineDescriptor { void Reset (); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4PipelineDataSetSerializerDescriptor : NSCopying { @@ -9324,6 +9413,8 @@ interface MTL4PipelineDataSetSerializerDescriptor : NSCopying { MTL4PipelineDataSetSerializerConfiguration Configuration { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4PipelineDescriptor : NSCopying { @@ -9335,6 +9426,8 @@ interface MTL4PipelineDescriptor : NSCopying { MTL4PipelineOptions Options { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4PipelineOptions : NSCopying { @@ -9345,6 +9438,8 @@ interface MTL4PipelineOptions : NSCopying { MTL4ShaderReflection ShaderReflection { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4PipelineStageDynamicLinkingDescriptor : NSCopying { @@ -9358,6 +9453,8 @@ interface MTL4PipelineStageDynamicLinkingDescriptor : NSCopying { IMTLDynamicLibrary [] PreloadedLibraries { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4AccelerationStructureDescriptor))] interface MTL4PrimitiveAccelerationStructureDescriptor { @@ -9380,6 +9477,8 @@ interface MTL4PrimitiveAccelerationStructureDescriptor { nuint MotionKeyframeCount { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4RenderPassDescriptor : NSCopying { @@ -9435,6 +9534,8 @@ interface MTL4RenderPassDescriptor : NSCopying { bool SupportColorAttachmentMapping { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4RenderPipelineBinaryFunctionsDescriptor : NSCopying { @@ -9457,6 +9558,8 @@ interface MTL4RenderPipelineBinaryFunctionsDescriptor : NSCopying { void Reset (); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4RenderPipelineColorAttachmentDescriptor : NSCopying { @@ -9491,6 +9594,8 @@ interface MTL4RenderPipelineColorAttachmentDescriptor : NSCopying { void Reset (); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4RenderPipelineColorAttachmentDescriptorArray : NSCopying { @@ -9504,6 +9609,8 @@ interface MTL4RenderPipelineColorAttachmentDescriptorArray : NSCopying { void Reset (); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4PipelineDescriptor))] interface MTL4RenderPipelineDescriptor { @@ -9559,6 +9666,8 @@ interface MTL4RenderPipelineDescriptor { void Reset (); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4RenderPipelineDynamicLinkingDescriptor : NSCopying { @@ -9578,6 +9687,8 @@ interface MTL4RenderPipelineDynamicLinkingDescriptor : NSCopying { MTL4PipelineStageDynamicLinkingDescriptor MeshLinkingDescriptor { get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4FunctionDescriptor))] interface MTL4SpecializedFunctionDescriptor { @@ -9591,6 +9702,8 @@ interface MTL4SpecializedFunctionDescriptor { MTLFunctionConstantValues ConstantValues { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTL4StaticLinkingDescriptor : NSCopying { @@ -9604,6 +9717,8 @@ interface MTL4StaticLinkingDescriptor : NSCopying { NSDictionary> Groups { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4FunctionDescriptor))] interface MTL4StitchedFunctionDescriptor { @@ -9614,6 +9729,8 @@ interface MTL4StitchedFunctionDescriptor { MTL4FunctionDescriptor [] FunctionDescriptors { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTL4PipelineDescriptor))] interface MTL4TileRenderPipelineDescriptor { @@ -9656,6 +9773,8 @@ interface MTLFunctionReflection { string UserAnnotation { get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTLLogicalToPhysicalColorAttachmentMap : NSCopying { @@ -9669,6 +9788,8 @@ interface MTLLogicalToPhysicalColorAttachmentMap : NSCopying { void Reset (); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTLResourceViewPoolDescriptor : NSCopying { @@ -9679,6 +9800,8 @@ interface MTLResourceViewPoolDescriptor : NSCopying { string Label { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTLTensorDescriptor : NSCopying { @@ -9708,6 +9831,8 @@ interface MTLTensorDescriptor : NSCopying { MTLHazardTrackingMode HazardTrackingMode { get; set; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] // all properties are readonly, and has a non-default ctor @@ -9723,6 +9848,8 @@ interface MTLTensorExtents { nint GetExtent (nuint dimensionIndex); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (MTLType))] interface MTLTensorReferenceType { @@ -9739,6 +9866,8 @@ interface MTLTensorReferenceType { MTLBindingAccess Access { get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), TV (26, 0), MacCatalyst (26, 0)] [BaseType (typeof (NSObject))] interface MTLTextureViewDescriptor : NSCopying { diff --git a/src/metalfx.cs b/src/metalfx.cs index 7e1739db57e1..19515be35435 100644 --- a/src/metalfx.cs +++ b/src/metalfx.cs @@ -165,6 +165,8 @@ interface MTLFXTemporalScalerDescriptor : NSCopying { bool SupportsMetal4FX (IMTLDevice device); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), MacCatalyst (26, 0), TV (26, 0)] [BaseType (typeof (NSObject))] interface MTLFXFrameInterpolatorDescriptor : NSCopying { @@ -405,6 +407,8 @@ interface MTL4FXFrameInterpolator : MTLFXFrameInterpolatorBase { void Encode (IMTL4CommandBuffer commandBuffer); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [Mac (26, 0), iOS (26, 0), MacCatalyst (26, 0), TV (26, 0)] [BaseType (typeof (NSObject))] interface MTLFXTemporalDenoisedScalerDescriptor : NSCopying { diff --git a/src/passkit.cs b/src/passkit.cs index d82bc4bdf1f6..6ee8b31bbd53 100644 --- a/src/passkit.cs +++ b/src/passkit.cs @@ -2058,7 +2058,7 @@ interface PKPaymentButton { /// A button that adds passes to a Wallet. /// - /// Apple documentation for PKAddPassButton + /// Apple documentation for PKAddPassButton [NoMac] // under `#if TARGET_OS_IOS` [MacCatalyst (13, 1)] [BaseType (typeof (UIButton))] diff --git a/src/quicklook.cs b/src/quicklook.cs index 966c4765b08a..4fc711d0848e 100644 --- a/src/quicklook.cs +++ b/src/quicklook.cs @@ -257,7 +257,7 @@ interface IQLPreviewItem { } /// An item that can be previewed with a . /// - /// Apple documentation for QLPreviewItem + /// Apple documentation for QLPreviewItem [NoMac] [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] diff --git a/src/rgen/Microsoft.Macios.Binding.Common/Microsoft.Macios.Binding.Common.csproj b/src/rgen/Microsoft.Macios.Binding.Common/Microsoft.Macios.Binding.Common.csproj index 77e0b430a77a..5d75fb3af4e6 100644 --- a/src/rgen/Microsoft.Macios.Binding.Common/Microsoft.Macios.Binding.Common.csproj +++ b/src/rgen/Microsoft.Macios.Binding.Common/Microsoft.Macios.Binding.Common.csproj @@ -3,7 +3,6 @@ net$(BundledNETCoreAppTargetFrameworkVersion) enable - enable diff --git a/src/rgen/Microsoft.Macios.Bindings.Analyzer.Sample/Microsoft.Macios.Bindings.Analyzer.Sample.csproj b/src/rgen/Microsoft.Macios.Bindings.Analyzer.Sample/Microsoft.Macios.Bindings.Analyzer.Sample.csproj index 946859b5203c..90c90e72f8f7 100644 --- a/src/rgen/Microsoft.Macios.Bindings.Analyzer.Sample/Microsoft.Macios.Bindings.Analyzer.Sample.csproj +++ b/src/rgen/Microsoft.Macios.Bindings.Analyzer.Sample/Microsoft.Macios.Bindings.Analyzer.Sample.csproj @@ -2,9 +2,7 @@ net$(BundledNETCoreAppTargetFrameworkVersion)-ios - enable APL0003 - true true true diff --git a/src/rgen/Microsoft.Macios.Bindings.Analyzer/Microsoft.Macios.Bindings.Analyzer.csproj b/src/rgen/Microsoft.Macios.Bindings.Analyzer/Microsoft.Macios.Bindings.Analyzer.csproj index a0e04ed81851..0bc18e3aba25 100644 --- a/src/rgen/Microsoft.Macios.Bindings.Analyzer/Microsoft.Macios.Bindings.Analyzer.csproj +++ b/src/rgen/Microsoft.Macios.Bindings.Analyzer/Microsoft.Macios.Bindings.Analyzer.csproj @@ -3,12 +3,9 @@ net$(BundledNETCoreAppTargetFrameworkVersion) false - enable - latest true true - true Microsoft.Macios.Bindings.Analyzer Microsoft.Macios.Bindings.Analyzer diff --git a/src/rgen/Microsoft.Macios.Bindings.Analyzer/Validators/FieldValidator.cs b/src/rgen/Microsoft.Macios.Bindings.Analyzer/Validators/FieldValidator.cs index 6bc47067a431..3bffa00f9f39 100644 --- a/src/rgen/Microsoft.Macios.Bindings.Analyzer/Validators/FieldValidator.cs +++ b/src/rgen/Microsoft.Macios.Bindings.Analyzer/Validators/FieldValidator.cs @@ -76,6 +76,7 @@ internal static bool FlagsAreValid (Property property, RootContext context, // there are a number of flags that have no effect in a field property, we are not raise a warning for each // of them since they are ignored by rgen. The user that has warnings as errors will have to deal with them. +#pragma warning disable CS0618 // DisableZeroCopy is obsolete var ignoredFlags = new [] { PropertyFlag.IsThreadStatic, PropertyFlag.MarshalNativeExceptions, @@ -93,6 +94,7 @@ internal static bool FlagsAreValid (Property property, RootContext context, PropertyFlag.Optional, PropertyFlag.CreateEvents, }; +#pragma warning restore CS0618 var builder = ImmutableArray.CreateBuilder (); foreach (var flag in ignoredFlags) { diff --git a/src/rgen/Microsoft.Macios.Bindings.CodeFixers/Microsoft.Macios.Bindings.CodeFixers.csproj b/src/rgen/Microsoft.Macios.Bindings.CodeFixers/Microsoft.Macios.Bindings.CodeFixers.csproj index 083846f42783..67c54c682b96 100644 --- a/src/rgen/Microsoft.Macios.Bindings.CodeFixers/Microsoft.Macios.Bindings.CodeFixers.csproj +++ b/src/rgen/Microsoft.Macios.Bindings.CodeFixers/Microsoft.Macios.Bindings.CodeFixers.csproj @@ -3,8 +3,6 @@ net$(BundledNETCoreAppTargetFrameworkVersion) false - enable - latest true true diff --git a/src/rgen/Microsoft.Macios.Generator.Sample/Microsoft.Macios.Generator.Sample.csproj b/src/rgen/Microsoft.Macios.Generator.Sample/Microsoft.Macios.Generator.Sample.csproj index 22476b3eccbc..fe06ba681d2b 100644 --- a/src/rgen/Microsoft.Macios.Generator.Sample/Microsoft.Macios.Generator.Sample.csproj +++ b/src/rgen/Microsoft.Macios.Generator.Sample/Microsoft.Macios.Generator.Sample.csproj @@ -2,10 +2,8 @@ net$(BundledNETCoreAppTargetFrameworkVersion)-ios - enable Microsoft.Macios.Generator.Sample APL0003 - true true diff --git a/src/rgen/Microsoft.Macios.Generator/DataModel/Property.Generator.cs b/src/rgen/Microsoft.Macios.Generator/DataModel/Property.Generator.cs index 5c1dc20fae17..623bca12c849 100644 --- a/src/rgen/Microsoft.Macios.Generator/DataModel/Property.Generator.cs +++ b/src/rgen/Microsoft.Macios.Generator/DataModel/Property.Generator.cs @@ -99,10 +99,12 @@ public bool MarshalNativeExceptions public bool IsTransient => IsProperty && ExportPropertyData.Flags.HasFlag (ObjCBindings.Property.Transient); /// - /// True if the property was marked to DisableZeroCopy. + /// True if the property was marked to DisableZeroCopy. This flag is obsolete and has no effect. /// +#pragma warning disable CS0618 // Type or member is obsolete public bool DisableZeroCopy => IsProperty && ExportPropertyData.Flags.HasFlag (ObjCBindings.Property.DisableZeroCopy); +#pragma warning restore CS0618 /// /// True if the generator should not use a NSString for marshalling. diff --git a/src/rgen/Microsoft.Macios.Generator/Microsoft.Macios.Generator.csproj b/src/rgen/Microsoft.Macios.Generator/Microsoft.Macios.Generator.csproj index 4bd305c59e88..f73063d72ce0 100644 --- a/src/rgen/Microsoft.Macios.Generator/Microsoft.Macios.Generator.csproj +++ b/src/rgen/Microsoft.Macios.Generator/Microsoft.Macios.Generator.csproj @@ -3,12 +3,9 @@ net$(BundledNETCoreAppTargetFrameworkVersion) false - enable - latest true true - true Microsoft.Macios.Generator Microsoft.Macios.Generator diff --git a/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator.csproj b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator.csproj index f5ded35508aa..b608bfb3094f 100644 --- a/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator.csproj +++ b/src/rgen/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator/Microsoft.Macios.Transformer.Generator.csproj @@ -3,12 +3,9 @@ netstandard2.1 false - enable - latest true true - true Microsoft.Macios.Transformer.Generator Microsoft.Macios.Transformer.Generator diff --git a/src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs b/src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs index e09a98b9115f..5d35b03547f6 100644 --- a/src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs +++ b/src/rgen/Microsoft.Macios.Transformer/AttributesNames.cs @@ -90,8 +90,7 @@ static class AttributesNames { public const string DisableDefaultCtorAttribute = "DisableDefaultCtorAttribute"; /// - /// This attribute is applied to string parameters or string properties and instructs the code generator to not - /// use the zero-copy string marshaling for this parameter, and instead create a new NSString instance from the C# string + /// This attribute is obsolete and has no effect. Zero-copy string marshaling is no longer supported. /// [BindingFlag (AttributeTargets.Parameter | AttributeTargets.Property)] public const string DisableZeroCopyAttribute = "DisableZeroCopyAttribute"; diff --git a/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.csproj b/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.csproj index d9f51c46fe8b..28395182c78c 100644 --- a/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.csproj +++ b/src/rgen/Microsoft.Macios.Transformer/Microsoft.Macios.Transformer.csproj @@ -4,8 +4,6 @@ Exe net$(BundledNETCoreAppTargetFrameworkVersion) enable - enable - true true diff --git a/src/safariservices.cs b/src/safariservices.cs index d793a1265d17..ac7bf906bf92 100644 --- a/src/safariservices.cs +++ b/src/safariservices.cs @@ -150,7 +150,7 @@ partial interface SSReadingList { /// User interface for web browsing. /// - /// Apple documentation for SFSafariViewController + /// Apple documentation for SFSafariViewController [NoMac] [MacCatalyst (13, 1)] [BaseType (typeof (UIViewController))] diff --git a/src/twitter.cs b/src/twitter.cs index 57acdd0650ea..5dc2fa7aab45 100644 --- a/src/twitter.cs +++ b/src/twitter.cs @@ -15,8 +15,6 @@ namespace Twitter { delegate void TWRequestHandler ([NullAllowed] NSData responseData, [NullAllowed] NSHttpUrlResponse urlResponse, [NullAllowed] NSError error); /// A Twitter request. - /// - /// Apple documentation for TWRequest [Deprecated (PlatformName.iOS, 6, 0, message: "Use the 'Social' framework.")] [BaseType (typeof (NSObject))] interface TWRequest { @@ -92,9 +90,6 @@ interface TWRequest { } /// A that manages the user experience of composing a tweet. - /// - /// Send a Tweet - /// Apple documentation for TWTweetComposeViewController [Deprecated (PlatformName.iOS, 6, 0, message: "Use the 'Social' framework.")] [BaseType (typeof (UIViewController))] interface TWTweetComposeViewController { diff --git a/src/uikit.cs b/src/uikit.cs index 852499dc19fb..ebceb52728f9 100644 --- a/src/uikit.cs +++ b/src/uikit.cs @@ -15172,8 +15172,6 @@ interface UIPickerViewDataSource { interface IUIPickerViewDataSource { } /// The model for the UIPickerView. - /// - /// Apple documentation for UIPickerViewModel [NoTV] [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] diff --git a/src/videosubscriberaccount.cs b/src/videosubscriberaccount.cs index 3f967f2fb81e..4f56f90f7310 100644 --- a/src/videosubscriberaccount.cs +++ b/src/videosubscriberaccount.cs @@ -138,7 +138,7 @@ interface VSErrorInfo { interface IVSAccountManagerDelegate { } - /// Apple documentation for VSAccountManagerDelegate + /// Apple documentation for VSAccountManagerDelegate [Protocol, Model] [NoMacCatalyst] [BaseType (typeof (NSObject))] @@ -173,7 +173,7 @@ interface VSAccountManagerDelegate { /// Coordinates access to the user's subscription. /// - /// Apple documentation for VSAccountManager + /// Apple documentation for VSAccountManager [NoMacCatalyst] [BaseType (typeof (NSObject))] interface VSAccountManager { @@ -261,7 +261,7 @@ interface VSAccountManagerAccessOptions { /// Represents a cancellable request that is still "in flight". /// - /// Apple documentation for VSAccountManagerResult + /// Apple documentation for VSAccountManagerResult [NoMacCatalyst] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -275,7 +275,7 @@ interface VSAccountManagerResult { /// Information about a subscription. /// - /// Apple documentation for VSAccountMetadata + /// Apple documentation for VSAccountMetadata [NoMacCatalyst] [BaseType (typeof (NSObject))] interface VSAccountMetadata { @@ -328,7 +328,7 @@ interface VSAccountMetadata { /// Specifies information being requested from the subscriber's account. /// - /// Apple documentation for VSAccountMetadataRequest + /// Apple documentation for VSAccountMetadataRequest [NoMacCatalyst] [BaseType (typeof (NSObject))] interface VSAccountMetadataRequest { diff --git a/src/videotoolbox.cs b/src/videotoolbox.cs index 85f89d3fadd6..f2342abc5803 100644 --- a/src/videotoolbox.cs +++ b/src/videotoolbox.cs @@ -2906,6 +2906,8 @@ public enum VTFrameRateConversionParametersSubmissionMode : long { SequentialReferencesUnchanged = 3, } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [MacCatalyst (18, 4), NoTV, iOS (26, 0), Mac (15, 4)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -2946,6 +2948,8 @@ interface VTFrameRateConversionConfiguration : VTFrameProcessorConfiguration { bool Supported { [Bind ("isSupported")] get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [MacCatalyst (18, 4), NoTV, iOS (26, 0), Mac (15, 4)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -2987,6 +2991,8 @@ public enum VTMotionBlurParametersSubmissionMode : long { Sequential = 2, } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [MacCatalyst (26, 0), NoTV, iOS (26, 0), Mac (15, 4)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -3027,6 +3033,8 @@ interface VTMotionBlurConfiguration : VTFrameProcessorConfiguration { bool Supported { [Bind ("isSupported")] get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [MacCatalyst (26, 0), NoTV, iOS (26, 0), Mac (15, 4)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -3073,6 +3081,8 @@ public enum VTOpticalFlowParametersSubmissionMode : long { Sequential = 2, } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [MacCatalyst (26, 0), NoTV, iOS (26, 0), Mac (15, 4)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -3110,6 +3120,8 @@ interface VTOpticalFlowConfiguration : VTFrameProcessorConfiguration { bool Supported { [Bind ("isSupported")] get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [MacCatalyst (26, 0), NoTV, iOS (26, 0), Mac (15, 4)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -3127,6 +3139,8 @@ interface VTOpticalFlowParameters : VTFrameProcessorParameters { VTFrameProcessorOpticalFlow DestinationOpticalFlow { get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [TV (26, 0), MacCatalyst (26, 0), Mac (26, 0), iOS (26, 0)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -3156,6 +3170,8 @@ interface VTLowLatencyFrameInterpolationConfiguration : VTFrameProcessorConfigur bool Supported { [Bind ("isSupported")] get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [TV (26, 0), MacCatalyst (26, 0), Mac (26, 0), iOS (26, 0)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -3171,6 +3187,8 @@ interface VTLowLatencyFrameInterpolationParameters : VTFrameProcessorParameters NSNumber [] InterpolationPhase { get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [TV (26, 0), MacCatalyst (26, 0), Mac (26, 0), iOS (26, 0)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -3197,6 +3215,8 @@ interface VTLowLatencySuperResolutionScalerConfiguration : VTFrameProcessorConfi NSNumber [] GetSupportedScaleFactors (nint frameWidth, nint frameHeight); } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [NoTV, MacCatalyst (26, 0), Mac (26, 0), iOS (26, 0)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -3255,6 +3275,8 @@ interface VTSuperResolutionScalerConfiguration : VTFrameProcessorConfiguration { delegate void VTSuperResolutionScalerConfigurationDownloadConfigurationModelCallback ([NullAllowed] NSError error); + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [MacCatalyst (26, 0), NoTV, Mac (26, 0), iOS (26, 0)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -3275,6 +3297,8 @@ interface VTSuperResolutionScalerParameters : VTFrameProcessorParameters { VTSuperResolutionScalerParametersSubmissionMode SubmissionMode { get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [MacCatalyst (26, 0), NoTV, Mac (26, 0), iOS (26, 0)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -3298,6 +3322,8 @@ interface VTTemporalNoiseFilterConfiguration : VTFrameProcessorConfiguration { bool Supported { [Bind ("isSupported")] get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [MacCatalyst (26, 0), NoTV, Mac (26, 0), iOS (26, 0)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] @@ -3345,6 +3371,8 @@ interface VTMotionEstimationSessionCreationOptionKey { NSString Label { get; } } + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] [TV (26, 0), MacCatalyst (26, 0), Mac (26, 0), iOS (26, 0)] [BaseType (typeof (NSObject))] [DisableDefaultCtor] diff --git a/src/xkit.cs b/src/xkit.cs index 312e24d8b258..e6980d88c3ae 100644 --- a/src/xkit.cs +++ b/src/xkit.cs @@ -1582,7 +1582,7 @@ interface NSLayoutManager_NSTextViewSupport { interface INSLayoutManagerDelegate { } /// A delegate object that exposes events for s. - /// Apple documentation for NSLayoutManagerDelegate + /// Apple documentation for NSLayoutManagerDelegate [BaseType (typeof (NSObject))] [Model] [Protocol] @@ -2914,7 +2914,7 @@ partial interface NSTextAttachmentContainer { /// An attachment to a . /// /// - /// Apple documentation for NSTextAttachment + /// Apple documentation for NSTextAttachment [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] partial interface NSTextAttachment : NSTextAttachmentContainer, NSSecureCoding, NSTextAttachmentLayout @@ -3152,7 +3152,7 @@ nint ChangeInLength { interface INSTextStorageDelegate { } /// A delegate object that provides events relating to processing editing for . - /// Apple documentation for NSTextStorageDelegate + /// Apple documentation for NSTextStorageDelegate [MacCatalyst (13, 1)] [Model] [BaseType (typeof (NSObject))] @@ -3523,7 +3523,7 @@ interface NSShadow : NSSecureCoding, NSCopying { /// Represents a tab location in Text Kit. /// - /// Apple documentation for NSTextTab + /// Apple documentation for NSTextTab [MacCatalyst (13, 1)] [BaseType (typeof (NSObject))] interface NSTextTab : NSSecureCoding, NSCopying { diff --git a/system-dependencies.sh b/system-dependencies.sh index 292a7c8c12eb..912f671b6c90 100755 --- a/system-dependencies.sh +++ b/system-dependencies.sh @@ -6,7 +6,7 @@ cd $(dirname $0) # Detect if we're running on Linux if [[ "$(uname -s)" == "Linux" ]]; then - IS_LINUX=1 + NO_XCODE=1 # On Linux, ignore all macOS-specific dependencies IGNORE_OSX=1 IGNORE_XCODE=1 @@ -20,7 +20,7 @@ if [[ "$(uname -s)" == "Linux" ]]; then IGNORE_YAMLLINT=1 IGNORE_PYTHON3=1 else - IS_LINUX= + NO_XCODE= fi FAIL= @@ -31,6 +31,37 @@ VERBOSE= OPTIONAL_SIMULATORS=1 OPTIONAL_OLD_SIMULATORS=1 +if test -f configure.inc; then + source configure.inc + + if test -n "$NO_XCODE"; then + IGNORE_OSX=1 + IGNORE_XCODE=1 + IGNORE_SIMULATORS=1 + IGNORE_OLD_SIMULATORS=1 + IGNORE_XCODE_COMPONENTS=1 + fi +fi + +function get_xcode_developer_root () +{ + local suffix="${1:-}" + + if test -z "$suffix"; then + if test -n "${XCODE_DEVELOPER_ROOT:-}"; then + echo "$XCODE_DEVELOPER_ROOT" + return + fi + + if XCODE_DEVELOPER_ROOT_ASSIGNMENT=$(grep "^XCODE_DEVELOPER_ROOT=" configure.inc 2>/dev/null); then + echo "${XCODE_DEVELOPER_ROOT_ASSIGNMENT#*=}" + return + fi + fi + + grep "^XCODE${suffix}_DEVELOPER_ROOT[?:]*=" Make.config | sed 's/^[^=]*=//' +} + # parse command-line arguments while ! test -z $1; do case $1 in @@ -207,6 +238,12 @@ while ! test -z $1; do esac done +if test -z "${NO_XCODE:-}"; then + XCODE_DEVELOPER_ROOT=$(get_xcode_developer_root) + export XCODE_DEVELOPER_ROOT + export DEVELOPER_DIR="$XCODE_DEVELOPER_ROOT" +fi + # reporting functions COLOR_RED=$(tput setaf 1 2>/dev/null || true) COLOR_ORANGE=$(tput setaf 3 2>/dev/null || true) @@ -339,7 +376,7 @@ function xcodebuild_download_selected_platforms () local TVOS_NUGET_OS_VERSION local TVOS_BUILD_VERSION - XCODE_DEVELOPER_ROOT=$(grep XCODE_DEVELOPER_ROOT= Make.config | sed 's/.*=//') + XCODE_DEVELOPER_ROOT=$(get_xcode_developer_root) XCODE_NAME=$(basename "$(dirname "$(dirname "$XCODE_DEVELOPER_ROOT")")") # we use the same logic here as in Make.config to determine whether we're using a stable version of Xcode or not (search for XCODE_IS_STABLE/XCODE_IS_PREVIEW) XCODE_IS_STABLE=$(echo "$XCODE_NAME" | sed -e 's@^Xcode[_0-9.]*[.]app$@YES@') @@ -580,7 +617,7 @@ function install_coresimulator () local TARGET_CORESIMULATOR_VERSION local CURRENT_CORESIMULATOR_VERSION - XCODE_DEVELOPER_ROOT=$(grep XCODE_DEVELOPER_ROOT= Make.config | sed 's/.*=//') + XCODE_DEVELOPER_ROOT=$(get_xcode_developer_root) XCODE_ROOT=$(dirname "$(dirname "$XCODE_DEVELOPER_ROOT")") CORESIMULATOR_PKG=$XCODE_ROOT/Contents/Resources/Packages/XcodeSystemResources.pkg @@ -646,9 +683,13 @@ function install_coresimulator () } function check_specific_xcode () { - local XCODE_DEVELOPER_ROOT=`grep XCODE$1_DEVELOPER_ROOT= Make.config | sed 's/.*=//'` - local XCODE_VERSION=`grep XCODE$1_VERSION= Make.config | sed 's/.*=//'` - local XCODE_ROOT=$(dirname `dirname $XCODE_DEVELOPER_ROOT`) + local XCODE_DEVELOPER_ROOT + local XCODE_VERSION + local XCODE_ROOT + + XCODE_DEVELOPER_ROOT=$(get_xcode_developer_root "$1") + XCODE_VERSION=$(grep "XCODE$1_VERSION=" Make.config | sed 's/.*=//') + XCODE_ROOT=$(dirname "$(dirname "$XCODE_DEVELOPER_ROOT")") if ! test -d $XCODE_DEVELOPER_ROOT; then if ! test -z $PROVISION_XCODE; then @@ -686,11 +727,13 @@ function check_xcode () { if ! test -z $IGNORE_XCODE; then return; fi # must have latest Xcode in /Applications/Xcode.app - check_specific_xcode + check_specific_xcode "" install_coresimulator local IOS_SDK_VERSION MACOS_SDK_VERSION TVOS_SDK_VERSION - local XCODE_DEVELOPER_ROOT=`grep ^XCODE_DEVELOPER_ROOT= Make.config | sed 's/.*=//'` + local XCODE_DEVELOPER_ROOT + + XCODE_DEVELOPER_ROOT=$(get_xcode_developer_root) IOS_SDK_VERSION=$(grep ^IOS_NUGET_OS_VERSION= Make.versions | sed -e 's/.*=//') MACOS_SDK_VERSION=$(grep ^MACOS_NUGET_OS_VERSION= Make.versions | sed -e 's/.*=//') TVOS_SDK_VERSION=$(grep ^TVOS_NUGET_OS_VERSION= Make.versions | sed -e 's/.*=//') @@ -848,8 +891,8 @@ function check_osx_version () { } function check_checkout_dir () { - # Skip on Linux - this check is macOS-specific - if test -n "$IS_LINUX"; then + # Skip without Xcode - this check is macOS-specific + if test -n "$NO_XCODE"; then return fi @@ -916,7 +959,7 @@ function check_old_simulators () local XCODE local XCODE_DEVELOPER_ROOT - XCODE_DEVELOPER_ROOT=$(grep XCODE$1_DEVELOPER_ROOT= Make.config | sed 's/.*=//') + XCODE_DEVELOPER_ROOT=$(get_xcode_developer_root "$1") IFS=' ' read -r -a EXTRA_SIMULATORS <<< "$(grep ^EXTRA_SIMULATORS= Make.config | sed 's/.*=//')" XCODE=$(dirname "$(dirname "$XCODE_DEVELOPER_ROOT")") @@ -964,8 +1007,8 @@ function check_old_simulators () echo "Checking system..." -if test -n "$IS_LINUX"; then - ok "Running on ${COLOR_BLUE}Linux${COLOR_CLEAR} - skipping macOS-specific checks" +if test -n "$NO_XCODE"; then + ok "No Xcode available - skipping Xcode-specific checks" ok "Only .NET download and managed code builds will be available" fi @@ -994,4 +1037,3 @@ else echo "System check failed" exit 1 fi - diff --git a/tests/BundledResources/ResourcesTest.cs b/tests/BundledResources/ResourcesTest.cs index 9b1917c7a726..573102ee7133 100644 --- a/tests/BundledResources/ResourcesTest.cs +++ b/tests/BundledResources/ResourcesTest.cs @@ -21,10 +21,10 @@ public void Bundled () { // files are extracted (by MonoDevelop) so we can see them in the file system // that's true for simulator or devices and whatever the linker settings are - var dir = NSBundle.MainBundle.ResourcePath; - Assert.True (File.Exists (Path.Combine (dir, "basn3p08.png")), "file-basn3p08.png"); - Assert.True (File.Exists (Path.Combine (dir, "basn3p08_with_loc.png")), "file-basn3p08_with_loc.png"); - Assert.True (File.Exists (Path.Combine (dir, "xamvideotest.mp4")), "xamvideotest.mp4"); + var dir = NSBundle.MainBundle.ResourcePath!; + Assert.That (File.Exists (Path.Combine (dir, "basn3p08.png")), Is.True, "file-basn3p08.png"); + Assert.That (File.Exists (Path.Combine (dir, "basn3p08_with_loc.png")), Is.True, "file-basn3p08_with_loc.png"); + Assert.That (File.Exists (Path.Combine (dir, "xamvideotest.mp4")), Is.True, "xamvideotest.mp4"); // resources are removed by the linker or an extra step (e.g. "link sdk" or "don't link") but that // extra step is done only on device (to keep the simulator builds as fast as possible) diff --git a/tests/EmbeddedResources/ResourcesTest.cs b/tests/EmbeddedResources/ResourcesTest.cs index 04f35a6856e8..e8c83f5d9b08 100644 --- a/tests/EmbeddedResources/ResourcesTest.cs +++ b/tests/EmbeddedResources/ResourcesTest.cs @@ -23,13 +23,13 @@ public class ResourcesTest { public void Embedded () { var manager = new ResourceManager ("EmbeddedResources.Welcome", typeof (ResourcesTest).Assembly); - Assert.AreEqual ("Welcome", manager.GetString ("String1", new CultureInfo ("en")), "en"); - Assert.AreEqual ("G'day", manager.GetString ("String1", new CultureInfo ("en-AU")), "en-AU"); - Assert.AreEqual ("Willkommen", manager.GetString ("String1", new CultureInfo ("de")), "de"); - Assert.AreEqual ("Willkommen", manager.GetString ("String1", new CultureInfo ("de-DE")), "de-DE"); - Assert.AreEqual ("Bienvenido", manager.GetString ("String1", new CultureInfo ("es")), "es"); - Assert.AreEqual ("Bienvenido", manager.GetString ("String1", new CultureInfo ("es-AR")), "es-AR"); - Assert.AreEqual ("Bienvenido", manager.GetString ("String1", new CultureInfo ("es-ES")), "es-ES"); + Assert.That (manager.GetString ("String1", new CultureInfo ("en")), Is.EqualTo ("Welcome"), "en"); + Assert.That (manager.GetString ("String1", new CultureInfo ("en-AU")), Is.EqualTo ("G'day"), "en-AU"); + Assert.That (manager.GetString ("String1", new CultureInfo ("de")), Is.EqualTo ("Willkommen"), "de"); + Assert.That (manager.GetString ("String1", new CultureInfo ("de-DE")), Is.EqualTo ("Willkommen"), "de-DE"); + Assert.That (manager.GetString ("String1", new CultureInfo ("es")), Is.EqualTo ("Bienvenido"), "es"); + Assert.That (manager.GetString ("String1", new CultureInfo ("es-AR")), Is.EqualTo ("Bienvenido"), "es-AR"); + Assert.That (manager.GetString ("String1", new CultureInfo ("es-ES")), Is.EqualTo ("Bienvenido"), "es-ES"); } } } diff --git a/tests/EmbeddedResources/dotnet/shared.csproj b/tests/EmbeddedResources/dotnet/shared.csproj index bc88c7a465a4..5e93461f732e 100644 --- a/tests/EmbeddedResources/dotnet/shared.csproj +++ b/tests/EmbeddedResources/dotnet/shared.csproj @@ -11,10 +11,6 @@ $(NoWarn);CS8981 - - - true - Nullable diff --git a/tests/Makefile b/tests/Makefile index a43f5bfdc685..6a0802b2f561 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -2,9 +2,9 @@ TOP = .. include $(TOP)/Make.config -# Skip test-libraries on Linux (requires native compilation with Xcode/clang) +# Skip test-libraries without Xcode (requires native compilation with Xcode/clang) ifndef ONLY_SHARPIE -ifndef IS_LINUX +ifndef NO_XCODE SUBDIRS=test-libraries endif endif @@ -164,14 +164,14 @@ test-msbuild run-tests-msbuild: # Docs: https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-test#filter-option-details test-macdev-tests: export MSBUILD_EXE_PATH= test-macdev-tests: verify-system-vsmac-xcode-match - $(Q) $(DOTNET) test $(TOP)/tests/msbuild/Xamarin.MacDev.Tests/Xamarin.MacDev.Tests.csproj $(TEST_FILTER) + $(Q) $(DOTNET) test $(TOP)/tests/msbuild/Xamarin.MacDev.Tests/Xamarin.MacDev.Tests.csproj $(TEST_FILTER) /p:NuGetPackageRoot=$(abspath $(TOP)/packages)/ # Example TEST_FILTER: # TEST_FILTER="--filter:FullyQualifiedName~BuildMyCocoaApp" # Docs: https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-test#filter-option-details test-macdev-tasks: export MSBUILD_EXE_PATH= test-macdev-tasks: verify-system-vsmac-xcode-match - $(Q) $(DOTNET) test $(TOP)/tests/msbuild/Xamarin.MacDev.Tasks.Tests/Xamarin.MacDev.Tasks.Tests.csproj $(TEST_FILTER) + $(Q) $(DOTNET) test $(TOP)/tests/msbuild/Xamarin.MacDev.Tasks.Tests/Xamarin.MacDev.Tasks.Tests.csproj $(TEST_FILTER) /p:NuGetPackageRoot=$(abspath $(TOP)/packages)/ mac-test-package.zip: ifdef INCLUDE_MAC diff --git a/tests/bgen/BGenTests.cs b/tests/bgen/BGenTests.cs index 7a7ad37fb471..656c8ac2c867 100644 --- a/tests/bgen/BGenTests.cs +++ b/tests/bgen/BGenTests.cs @@ -1155,6 +1155,64 @@ public void GeneratedAttributeOnPropertyAccessors2 () Assert.That (RenderSupportedOSPlatformAttributes (setter), Is.EqualTo (expectedSetterAttributes), "Setter Attributes"); } + [Test] + public void DynamicDependencyAttribute () + { + var bgen = BuildFile (Profile.macOSMobile, "dynamic-dependency-attribute.cs"); + + var type = bgen.ApiAssembly.MainModule.Types.First (v => v.Name == "MyClass"); + var getter = type.Methods.First (v => v.Name == "get_CurrentContext"); + var setter = type.Methods.First (v => v.Name == "set_CurrentContext"); + var doSomething = type.Methods.First (v => v.Name == "DoSomething"); + var doSomethingElse = type.Methods.First (v => v.Name == "DoSomethingElse"); + var doAnother = type.Methods.First (v => v.Name == "DoAnother"); + var doYetAnother = type.Methods.First (v => v.Name == "DoYetAnother"); + var doAll = type.Methods.First (v => v.Name == "DoAll"); + + // (DynamicallyAccessedMemberTypes, string, string) on property getter + var getterDDA = getter.CustomAttributes.Where (ca => ca.AttributeType.Name == "DynamicDependencyAttribute").ToArray (); + Assert.That (getterDDA.Length, Is.EqualTo (1), "Getter DynamicDependency count"); + Assert.That ((int) getterDDA [0].ConstructorArguments [0].Value, Is.EqualTo (7), "Getter DynamicDependency MemberTypes (PublicConstructors | NonPublicConstructors)"); + Assert.That (getterDDA [0].ConstructorArguments [1].Value, Is.EqualTo ("Foundation.NSProxy"), "Getter DynamicDependency TypeName"); + Assert.That (getterDDA [0].ConstructorArguments [2].Value, Is.EqualTo ("Microsoft.macOS"), "Getter DynamicDependency AssemblyName"); + + // Setter should not have it + var setterDDA = setter.CustomAttributes.Where (ca => ca.AttributeType.Name == "DynamicDependencyAttribute").ToArray (); + Assert.That (setterDDA.Length, Is.EqualTo (0), "Setter DynamicDependency count"); + + // (string, string, string) on method + var methodDDA = doSomething.CustomAttributes.Where (ca => ca.AttributeType.Name == "DynamicDependencyAttribute").ToArray (); + Assert.That (methodDDA.Length, Is.EqualTo (1), "DoSomething DynamicDependency count"); + Assert.That (methodDDA [0].ConstructorArguments [0].Value, Is.EqualTo ("Create"), "DoSomething DynamicDependency MemberSignature"); + Assert.That (methodDDA [0].ConstructorArguments [1].Value, Is.EqualTo ("NS.MyClass"), "DoSomething DynamicDependency TypeName"); + Assert.That (methodDDA [0].ConstructorArguments [2].Value, Is.EqualTo ("api0"), "DoSomething DynamicDependency AssemblyName"); + + // (string) - single member signature + var elseDDA = doSomethingElse.CustomAttributes.Where (ca => ca.AttributeType.Name == "DynamicDependencyAttribute").ToArray (); + Assert.That (elseDDA.Length, Is.EqualTo (1), "DoSomethingElse DynamicDependency count"); + Assert.That (elseDDA [0].ConstructorArguments.Count, Is.EqualTo (1), "DoSomethingElse DynamicDependency arg count"); + Assert.That (elseDDA [0].ConstructorArguments [0].Value, Is.EqualTo ("Activate"), "DoSomethingElse DynamicDependency MemberSignature"); + + // (DynamicallyAccessedMemberTypes, Type) + var anotherDDA = doAnother.CustomAttributes.Where (ca => ca.AttributeType.Name == "DynamicDependencyAttribute").ToArray (); + Assert.That (anotherDDA.Length, Is.EqualTo (1), "DoAnother DynamicDependency count"); + Assert.That ((int) anotherDDA [0].ConstructorArguments [0].Value, Is.EqualTo (8 | 512), "DoAnother DynamicDependency MemberTypes (PublicMethods | PublicProperties)"); + Assert.That (((Mono.Cecil.TypeReference) anotherDDA [0].ConstructorArguments [1].Value).Name, Is.EqualTo ("NSObject"), "DoAnother DynamicDependency Type"); + + // (string, Type) + var yetAnotherDDA = doYetAnother.CustomAttributes.Where (ca => ca.AttributeType.Name == "DynamicDependencyAttribute").ToArray (); + Assert.That (yetAnotherDDA.Length, Is.EqualTo (1), "DoYetAnother DynamicDependency count"); + Assert.That (yetAnotherDDA [0].ConstructorArguments [0].Value, Is.EqualTo ("Create"), "DoYetAnother DynamicDependency MemberSignature"); + Assert.That (((Mono.Cecil.TypeReference) yetAnotherDDA [0].ConstructorArguments [1].Value).Name, Is.EqualTo ("NSObject"), "DoYetAnother DynamicDependency Type"); + + // (DynamicallyAccessedMemberTypes.All, string, string) + var allDDA = doAll.CustomAttributes.Where (ca => ca.AttributeType.Name == "DynamicDependencyAttribute").ToArray (); + Assert.That (allDDA.Length, Is.EqualTo (1), "DoAll DynamicDependency count"); + Assert.That ((int) allDDA [0].ConstructorArguments [0].Value, Is.EqualTo (-1), "DoAll DynamicDependency MemberTypes (All)"); + Assert.That (allDDA [0].ConstructorArguments [1].Value, Is.EqualTo ("NS.MyClass"), "DoAll DynamicDependency TypeName"); + Assert.That (allDDA [0].ConstructorArguments [2].Value, Is.EqualTo ("api0"), "DoAll DynamicDependency AssemblyName"); + } + [Test] [TestCase (Profile.iOS)] public void NewerAvailabilityInInlinedProtocol (Profile profile) @@ -1657,5 +1715,72 @@ public void BothProtectedAndInternal (Profile profile) var bgen = BuildFile (profile, "both-protected-and-internal.cs"); bgen.AssertNoWarnings (); } + + [Test] + [TestCase (Profile.iOS)] + [TestCase (Profile.tvOS)] + public void SimulatorAvailabilityAttributes (Profile profile) + { + Configuration.IgnoreIfIgnoredPlatform (profile.AsPlatform ()); + var bgen = BuildFile (profile, "simulator-availability-attributes.cs"); + bgen.AssertNoWarnings (); + + var module = bgen.ApiAssembly.MainModule; + + // Verify [UnsupportedSimulator] is copied for the current platform + var unsupportedAll = module.GetType ("NS", "UnsupportedOnAllSimulators"); + var unsupportedAttrs = unsupportedAll.CustomAttributes + .Where (a => a.AttributeType.Name == "UnsupportedSimulatorAttribute") + .ToArray (); + Assert.That (unsupportedAttrs.Length, Is.EqualTo (1), "UnsupportedOnAllSimulators: one attribute for current platform"); + var platformName = (string) unsupportedAttrs [0].ConstructorArguments [0].Value; + var expectedPlatform = profile == Profile.iOS ? "ios" : "tvos"; + Assert.That (platformName, Is.EqualTo (expectedPlatform), "UnsupportedOnAllSimulators platform name"); + + // Verify only the current platform's attribute is emitted + var iosOnly = module.GetType ("NS", "UnsupportedOnIosSimulatorOnly"); + var iosOnlyAttrs = iosOnly.CustomAttributes + .Where (a => a.AttributeType.Name == "UnsupportedSimulatorAttribute") + .ToArray (); + if (profile == Profile.iOS) + Assert.That (iosOnlyAttrs.Length, Is.EqualTo (1), "UnsupportedOnIosSimulatorOnly: present for iOS"); + else + Assert.That (iosOnlyAttrs.Length, Is.EqualTo (0), "UnsupportedOnIosSimulatorOnly: absent for tvOS"); + + // Verify [SupportedSimulator] with version is copied + var supported = module.GetType ("NS", "SupportedOnSimulatorFromVersion"); + var supportedAttrs = supported.CustomAttributes + .Where (a => a.AttributeType.Name == "SupportedSimulatorAttribute") + .ToArray (); + Assert.That (supportedAttrs.Length, Is.EqualTo (1), "SupportedOnSimulatorFromVersion: one attribute"); + var expectedVersion = profile == Profile.iOS ? "ios17.0" : "tvos17.0"; + Assert.That ((string) supportedAttrs [0].ConstructorArguments [0].Value, Is.EqualTo (expectedVersion), "SupportedOnSimulatorFromVersion platform name"); + + // Verify no simulator attributes when none are specified + var noAttrs = module.GetType ("NS", "NoSimulatorAttributes"); + var simulatorAttrs = noAttrs.CustomAttributes + .Where (a => a.AttributeType.Name == "UnsupportedSimulatorAttribute" || a.AttributeType.Name == "SupportedSimulatorAttribute") + .ToArray (); + Assert.That (simulatorAttrs.Length, Is.EqualTo (0), "NoSimulatorAttributes: no simulator attributes"); + } + + [Test] + [TestCase (Profile.macOSMobile)] + [TestCase (Profile.MacCatalyst)] + public void SimulatorAvailabilityAttributes_NotEmittedForMacPlatforms (Profile profile) + { + Configuration.IgnoreIfIgnoredPlatform (profile.AsPlatform ()); + var bgen = BuildFile (profile, "simulator-availability-attributes.cs"); + bgen.AssertNoWarnings (); + + var module = bgen.ApiAssembly.MainModule; + foreach (var typeName in new [] { "UnsupportedOnAllSimulators", "UnsupportedOnIosSimulatorOnly", "SupportedOnSimulatorFromVersion", "NoSimulatorAttributes" }) { + var type = module.GetType ("NS", typeName); + var simulatorAttrs = type.CustomAttributes + .Where (a => a.AttributeType.Name == "UnsupportedSimulatorAttribute" || a.AttributeType.Name == "SupportedSimulatorAttribute") + .ToArray (); + Assert.That (simulatorAttrs.Length, Is.EqualTo (0), $"{typeName}: no simulator attributes on Mac platforms"); + } + } } } diff --git a/tests/bgen/ProtocolTests.cs b/tests/bgen/ProtocolTests.cs index 6dad62853715..fa26326de7b1 100644 --- a/tests/bgen/ProtocolTests.cs +++ b/tests/bgen/ProtocolTests.cs @@ -97,23 +97,23 @@ public void Members (Profile profile) "ObjCRuntime.NativeHandle api0.Messaging::NativeHandle_objc_msgSend_NativeHandle(System.IntPtr,System.IntPtr,ObjCRuntime.NativeHandle)", "ObjCRuntime.NativeHandle api0.Messaging::NativeHandle_objc_msgSend_ref_NativeHandle(System.IntPtr,System.IntPtr,ObjCRuntime.NativeHandle*)", "ObjCRuntime.NativeHandle api0.Messaging::NativeHandle_objc_msgSend(System.IntPtr,System.IntPtr)", - "ObjCRuntime.NativeHandle api0.Messaging::NativeHandle_objc_msgSendSuper_NativeHandle(System.IntPtr,System.IntPtr,ObjCRuntime.NativeHandle)", - "ObjCRuntime.NativeHandle api0.Messaging::NativeHandle_objc_msgSendSuper_ref_NativeHandle(System.IntPtr,System.IntPtr,ObjCRuntime.NativeHandle*)", - "ObjCRuntime.NativeHandle api0.Messaging::NativeHandle_objc_msgSendSuper(System.IntPtr,System.IntPtr)", + "ObjCRuntime.NativeHandle api0.Messaging::NativeHandle_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*,System.IntPtr,ObjCRuntime.NativeHandle)", + "ObjCRuntime.NativeHandle api0.Messaging::NativeHandle_objc_msgSendSuper_ref_NativeHandle(ObjCRuntime.ObjCSuper*,System.IntPtr,ObjCRuntime.NativeHandle*)", + "ObjCRuntime.NativeHandle api0.Messaging::NativeHandle_objc_msgSendSuper(ObjCRuntime.ObjCSuper*,System.IntPtr)", "ObjCRuntime.NativeHandle Protocols.IProtocolWithStaticMembers::Method()", "ObjCRuntime.NativeHandle Protocols.MyObject::get_ClassHandle()", "ObjCRuntime.NativeHandle Protocols.MyObject2::get_ClassHandle()", "System.Action ObjCRuntime.Trampolines/NIDAction::Create(System.IntPtr)", "System.Boolean Protocols.IProtocolWithStaticMembers::GetProperty()", "System.Byte api0.Messaging::bool_objc_msgSend(System.IntPtr,System.IntPtr)", - "System.Byte api0.Messaging::bool_objc_msgSendSuper(System.IntPtr,System.IntPtr)", + "System.Byte api0.Messaging::bool_objc_msgSendSuper(ObjCRuntime.ObjCSuper*,System.IntPtr)", "System.IAsyncResult ObjCRuntime.Trampolines/DAction::BeginInvoke(System.IntPtr,System.AsyncCallback,System.Object)", "System.Int32 api0.Messaging::int_objc_msgSend_int_out_Byte_ref_Int16(System.IntPtr,System.IntPtr,System.Int32,System.Byte*,System.Int16*)", "System.Int32 api0.Messaging::int_objc_msgSend_NativeHandle(System.IntPtr,System.IntPtr,ObjCRuntime.NativeHandle)", "System.Int32 api0.Messaging::int_objc_msgSend(System.IntPtr,System.IntPtr)", - "System.Int32 api0.Messaging::int_objc_msgSendSuper_int_out_Byte_ref_Int16(System.IntPtr,System.IntPtr,System.Int32,System.Byte*,System.Int16*)", - "System.Int32 api0.Messaging::int_objc_msgSendSuper_NativeHandle(System.IntPtr,System.IntPtr,ObjCRuntime.NativeHandle)", - "System.Int32 api0.Messaging::int_objc_msgSendSuper(System.IntPtr,System.IntPtr)", + "System.Int32 api0.Messaging::int_objc_msgSendSuper_int_out_Byte_ref_Int16(ObjCRuntime.ObjCSuper*,System.IntPtr,System.Int32,System.Byte*,System.Int16*)", + "System.Int32 api0.Messaging::int_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*,System.IntPtr,ObjCRuntime.NativeHandle)", + "System.Int32 api0.Messaging::int_objc_msgSendSuper(ObjCRuntime.ObjCSuper*,System.IntPtr)", "System.Int32 Protocols.IOptionalProtocol::_GetInternalOptionalProperty(Protocols.IOptionalProtocol)", "System.Int32 Protocols.IOptionalProtocol::_GetOptionalProperty(Protocols.IOptionalProtocol)", "System.Int32 Protocols.IOptionalProtocol::_InternalOptionalMethod(Protocols.IOptionalProtocol,System.Int32,System.Byte&,System.Int16&)", @@ -211,8 +211,8 @@ public void Members (Profile profile) "System.Int32 Protocols.RequiredProtocolWrapper::RequiredMethod(System.Int32,System.Byte&,System.Int16&)", "System.IntPtr api0.Messaging::IntPtr_objc_msgSend_IntPtr(System.IntPtr,System.IntPtr,System.IntPtr)", "System.IntPtr api0.Messaging::IntPtr_objc_msgSend(System.IntPtr,System.IntPtr)", - "System.IntPtr api0.Messaging::IntPtr_objc_msgSendSuper_IntPtr(System.IntPtr,System.IntPtr,System.IntPtr)", - "System.IntPtr api0.Messaging::IntPtr_objc_msgSendSuper(System.IntPtr,System.IntPtr)", + "System.IntPtr api0.Messaging::IntPtr_objc_msgSendSuper_IntPtr(ObjCRuntime.ObjCSuper*,System.IntPtr,System.IntPtr)", + "System.IntPtr api0.Messaging::IntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*,System.IntPtr)", "System.String Protocols.IOptionalProtocol::_GetNullableOptionalProperty(Protocols.IOptionalProtocol)", "System.String Protocols.IOptionalProtocol::get_NullableOptionalProperty()", "System.String Protocols.IOptionalProtocol::GetNullableStaticOptionalProperty()", @@ -238,9 +238,9 @@ public void Members (Profile profile) "System.Void api0.Messaging::void_objc_msgSend_bool(System.IntPtr,System.IntPtr,System.Byte)", "System.Void api0.Messaging::void_objc_msgSend_int(System.IntPtr,System.IntPtr,System.Int32)", "System.Void api0.Messaging::void_objc_msgSend_NativeHandle(System.IntPtr,System.IntPtr,ObjCRuntime.NativeHandle)", - "System.Void api0.Messaging::void_objc_msgSendSuper_bool(System.IntPtr,System.IntPtr,System.Byte)", - "System.Void api0.Messaging::void_objc_msgSendSuper_int(System.IntPtr,System.IntPtr,System.Int32)", - "System.Void api0.Messaging::void_objc_msgSendSuper_NativeHandle(System.IntPtr,System.IntPtr,ObjCRuntime.NativeHandle)", + "System.Void api0.Messaging::void_objc_msgSendSuper_bool(ObjCRuntime.ObjCSuper*,System.IntPtr,System.Byte)", + "System.Void api0.Messaging::void_objc_msgSendSuper_int(ObjCRuntime.ObjCSuper*,System.IntPtr,System.Int32)", + "System.Void api0.Messaging::void_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*,System.IntPtr,ObjCRuntime.NativeHandle)", "System.Void ObjCRuntime.Trampolines/DAction::.ctor(System.Object,System.IntPtr)", "System.Void ObjCRuntime.Trampolines/DAction::EndInvoke(System.IAsyncResult)", "System.Void ObjCRuntime.Trampolines/DAction::Invoke(System.IntPtr)", diff --git a/tests/bgen/bgen-tests.csproj b/tests/bgen/bgen-tests.csproj index 0a21be053805..f4f30d3edb79 100644 --- a/tests/bgen/bgen-tests.csproj +++ b/tests/bgen/bgen-tests.csproj @@ -5,8 +5,6 @@ bgen_tests false - true - enable $(DefaultItemExcludesInProjectFolder);tests/** diff --git a/tests/bgen/tests/ExpectedXmlDocs.MacCatalyst.xml b/tests/bgen/tests/ExpectedXmlDocs.MacCatalyst.xml index 57467f2576c7..05163498b7fd 100644 --- a/tests/bgen/tests/ExpectedXmlDocs.MacCatalyst.xml +++ b/tests/bgen/tests/ExpectedXmlDocs.MacCatalyst.xml @@ -158,7 +158,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -383,7 +387,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -578,7 +586,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -688,7 +700,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -768,7 +784,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> diff --git a/tests/bgen/tests/ExpectedXmlDocs.iOS.xml b/tests/bgen/tests/ExpectedXmlDocs.iOS.xml index ca171d315bba..03904bb8b865 100644 --- a/tests/bgen/tests/ExpectedXmlDocs.iOS.xml +++ b/tests/bgen/tests/ExpectedXmlDocs.iOS.xml @@ -158,7 +158,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -383,7 +387,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -578,7 +586,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -688,7 +700,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -768,7 +784,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -858,7 +878,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> diff --git a/tests/bgen/tests/ExpectedXmlDocs.macOS.xml b/tests/bgen/tests/ExpectedXmlDocs.macOS.xml index 57467f2576c7..05163498b7fd 100644 --- a/tests/bgen/tests/ExpectedXmlDocs.macOS.xml +++ b/tests/bgen/tests/ExpectedXmlDocs.macOS.xml @@ -158,7 +158,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -383,7 +387,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -578,7 +586,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -688,7 +700,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -768,7 +784,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> diff --git a/tests/bgen/tests/ExpectedXmlDocs.tvOS.xml b/tests/bgen/tests/ExpectedXmlDocs.tvOS.xml index 57467f2576c7..05163498b7fd 100644 --- a/tests/bgen/tests/ExpectedXmlDocs.tvOS.xml +++ b/tests/bgen/tests/ExpectedXmlDocs.tvOS.xml @@ -158,7 +158,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -383,7 +387,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -578,7 +586,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -688,7 +700,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> @@ -768,7 +784,11 @@ if (IsDirectBinding) { Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame); } else { - Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame); + unsafe { + var __objc_super__ = new ObjCRuntime.ObjCSuper (this); + Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (&__objc_super__, initWithFrame, frame); + } + GC.KeepAlive (this); } } ]]> diff --git a/tests/bgen/tests/dynamic-dependency-attribute.cs b/tests/bgen/tests/dynamic-dependency-attribute.cs new file mode 100644 index 000000000000..5ffbc3ac5d1e --- /dev/null +++ b/tests/bgen/tests/dynamic-dependency-attribute.cs @@ -0,0 +1,42 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using Foundation; +using ObjCRuntime; + +namespace NS { + [BaseType (typeof (NSObject))] + interface MyClass { + [Static, Export ("currentContext"), NullAllowed] + NSObject CurrentContext { + // (DynamicallyAccessedMemberTypes, string, string) + [DynamicDependency (DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors, "Foundation.NSProxy", "Microsoft.macOS")] + get; + set; + } + + // (string, string, string) + [Export ("doSomething")] + [DynamicDependency ("Create", "NS.MyClass", "api0")] + void DoSomething (); + + // (string) - single member signature + [Export ("doSomethingElse")] + [DynamicDependency ("Activate")] + void DoSomethingElse (); + + // (DynamicallyAccessedMemberTypes, Type) + [Export ("doAnother")] + [DynamicDependency (DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicProperties, typeof (NSObject))] + void DoAnother (); + + // (string, Type) + [Export ("doYetAnother")] + [DynamicDependency ("Create", typeof (NSObject))] + void DoYetAnother (); + + // (DynamicallyAccessedMemberTypes.All, string, string) + [Export ("doAll")] + [DynamicDependency (DynamicallyAccessedMemberTypes.All, "NS.MyClass", "api0")] + void DoAll (); + } +} diff --git a/tests/bgen/tests/simulator-availability-attributes.cs b/tests/bgen/tests/simulator-availability-attributes.cs new file mode 100644 index 000000000000..1cce845e0b80 --- /dev/null +++ b/tests/bgen/tests/simulator-availability-attributes.cs @@ -0,0 +1,30 @@ +using System; +using Foundation; +using ObjCRuntime; + +namespace NS { + [UnsupportedSimulator ("ios")] + [UnsupportedSimulator ("tvos")] + [iOS (16, 0), TV (16, 0), Mac (13, 0), MacCatalyst (16, 0)] + [BaseType (typeof (NSObject))] + interface UnsupportedOnAllSimulators { + } + + [UnsupportedSimulator ("ios")] + [iOS (16, 0), TV (16, 0), Mac (13, 0), MacCatalyst (16, 0)] + [BaseType (typeof (NSObject))] + interface UnsupportedOnIosSimulatorOnly { + } + + [SupportedSimulator ("ios17.0")] + [SupportedSimulator ("tvos17.0")] + [iOS (16, 0), TV (16, 0), Mac (13, 0), MacCatalyst (16, 0)] + [BaseType (typeof (NSObject))] + interface SupportedOnSimulatorFromVersion { + } + + [iOS (16, 0), TV (16, 0), Mac (13, 0), MacCatalyst (16, 0)] + [BaseType (typeof (NSObject))] + interface NoSimulatorAttributes { + } +} diff --git a/tests/bindings-test/ProtocolTest.cs b/tests/bindings-test/ProtocolTest.cs index c85278667de0..f94355ccc85f 100644 --- a/tests/bindings-test/ProtocolTest.cs +++ b/tests/bindings-test/ProtocolTest.cs @@ -10,12 +10,17 @@ public class ProtocolTest { bool HasProtocolAttributes { get { if (TestRuntime.IsLinkAll) { -#if OPTIMIZEALL && __MACOS__ - return false; +#if OPTIMIZEALL + var registeredProtocols = true; +#elif __MACOS__ + var registeredProtocols = false; #else - if (!Runtime.DynamicRegistrationSupported) - return false; + var registeredProtocols = true; #endif + if (!registeredProtocols) + return Runtime.DynamicRegistrationSupported; + + return !IsStaticRegistrar; } @@ -23,6 +28,12 @@ bool HasProtocolAttributes { } } + bool IsStaticRegistrar { + get { + return global::XamarinTests.ObjCRuntime.Registrar.IsStaticRegistrar; + } + } + bool IsTrimmableStaticRegistrar { get { return global::XamarinTests.ObjCRuntime.Registrar.IsTrimmableStaticRegistrar; @@ -34,24 +45,24 @@ public void Constructors () { using var dateNow = (NSDate) DateTime.Now; - using (var obj = IConstructorProtocol.CreateInstance ("Hello world")) { - Assert.AreEqual ("Hello world", obj.StringValue, "A StringValue"); - Assert.IsNull (obj.DateValue, "A DateValue"); + using (var obj = IConstructorProtocol.CreateInstance ("Hello world")!) { + Assert.That (obj.StringValue, Is.EqualTo ("Hello world"), "A StringValue"); + Assert.That (obj.DateValue, Is.Null, "A DateValue"); } - using (var obj = IConstructorProtocol.CreateInstance (dateNow)) { - Assert.IsNull (obj.StringValue, "B StringValue"); - Assert.AreEqual (dateNow, obj.DateValue, "B DateValue"); + using (var obj = IConstructorProtocol.CreateInstance (dateNow)!) { + Assert.That (obj.StringValue, Is.Null, "B StringValue"); + Assert.That (obj.DateValue, Is.EqualTo (dateNow), "B DateValue"); } - using (var obj = IConstructorProtocol.CreateInstance ("Hello Subclassed")) { - Assert.AreEqual ("Hello Subclassed", obj.StringValue, "C1 StringValue"); - Assert.IsNull (obj.DateValue, "C1 DateValue"); + using (var obj = IConstructorProtocol.CreateInstance ("Hello Subclassed")!) { + Assert.That (obj.StringValue, Is.EqualTo ("Hello Subclassed"), "C1 StringValue"); + Assert.That (obj.DateValue, Is.Null, "C1 DateValue"); } - using (var obj = IConstructorProtocol.CreateInstance (dateNow)) { - Assert.IsNull (obj.StringValue, "C2 StringValue"); - Assert.AreEqual (dateNow, obj.DateValue, "C2 DateValue"); + using (var obj = IConstructorProtocol.CreateInstance (dateNow)!) { + Assert.That (obj.StringValue, Is.Null, "C2 StringValue"); + Assert.That (obj.DateValue, Is.EqualTo (dateNow), "C2 DateValue"); } if (global::XamarinTests.ObjCRuntime.Registrar.IsDynamicRegistrar) { @@ -59,9 +70,9 @@ public void Constructors () IConstructorProtocol.CreateInstance ("Hello Subclassed 2"); }, "D1 Exception"); } else { - using (var obj = IConstructorProtocol.CreateInstance ("Hello Subclassed 2")) { - Assert.AreEqual ("Managed interceptor! Hello Subclassed 2", obj.StringValue, "D1 StringValue"); - Assert.IsNull (obj.DateValue, "D1 DateValue"); + using (var obj = IConstructorProtocol.CreateInstance ("Hello Subclassed 2")!) { + Assert.That (obj.StringValue, Is.EqualTo ("Managed interceptor! Hello Subclassed 2"), "D1 StringValue"); + Assert.That (obj.DateValue, Is.Null, "D1 DateValue"); } } @@ -70,9 +81,9 @@ public void Constructors () IConstructorProtocol.CreateInstance (dateNow); }, "D2 Exception"); } else { - using (var obj = IConstructorProtocol.CreateInstance (dateNow)) { - Assert.IsNull (obj.StringValue, "D2 StringValue"); - Assert.AreEqual (dateNow.AddSeconds (42), obj.DateValue, "D2 DateValue"); + using (var obj = IConstructorProtocol.CreateInstance (dateNow)!) { + Assert.That (obj.StringValue, Is.Null, "D2 StringValue"); + Assert.That (obj.DateValue, Is.EqualTo (dateNow.AddSeconds (42)), "D2 DateValue"); } } } @@ -106,28 +117,28 @@ public void OnlyProtocol () var bindingAssembly = GetType ().Assembly; // the interface must be created - var IP1 = bindingAssembly.GetType ("Bindings.Test.Protocol.IP1"); - Assert.IsNotNull (IP1, "IP1"); + var IP1 = bindingAssembly.GetType ("Bindings.Test.Protocol.IP1")!; + Assert.That (IP1, Is.Not.Null, "IP1"); // with a [Protocol] attribute var IP1Attributes = IP1.GetCustomAttributes (typeof (ProtocolAttribute), false); if (HasProtocolAttributes) { - Assert.AreEqual (1, IP1Attributes.Length, "[Protocol] IP1"); + Assert.That (IP1Attributes.Length, Is.EqualTo (1), "[Protocol] IP1"); var IP1Protocol = (ProtocolAttribute) IP1Attributes [0]; - Assert.AreEqual ("P1", IP1Protocol.Name, "Name"); + Assert.That (IP1Protocol.Name, Is.EqualTo ("P1"), "Name"); // and a wrapper type var wrapperType = bindingAssembly.GetType ("Bindings.Test.Protocol.P1Wrapper"); - Assert.IsNotNull (wrapperType, "P1_Wrapper"); - Assert.AreEqual (wrapperType, IP1Protocol.WrapperType, "WrapperType"); + Assert.That (wrapperType, Is.Not.Null, "P1_Wrapper"); + Assert.That (IP1Protocol.WrapperType, Is.EqualTo (wrapperType), "WrapperType"); } else { - Assert.AreEqual (0, IP1Attributes.Length, "[Protocol] IP1"); + Assert.That (IP1Attributes.Length, Is.EqualTo (0), "[Protocol] IP1"); // and a wrapper type var wrapperType = bindingAssembly.GetType ("Bindings.Test.Protocol.P1Wrapper"); - Assert.IsNotNull (wrapperType, "P1_Wrapper"); + Assert.That (wrapperType, Is.Not.Null, "P1_Wrapper"); } // but not the model - Assert.IsNull (bindingAssembly.GetType ("Bindings.Test.Protocol.P1"), "P1"); + Assert.That (bindingAssembly.GetType ("Bindings.Test.Protocol.P1"), Is.Null, "P1"); } [Test] @@ -138,33 +149,33 @@ public void ProtocolWithBaseType () var bindingAssembly = GetType ().Assembly; // the interface must be created - var IP2 = bindingAssembly.GetType ("Bindings.Test.Protocol.IP2"); - Assert.IsNotNull (IP2, "IP2"); + var IP2 = bindingAssembly.GetType ("Bindings.Test.Protocol.IP2")!; + Assert.That (IP2, Is.Not.Null, "IP2"); // with a [Protocol] attribute var IP2Attributes = IP2.GetCustomAttributes (typeof (ProtocolAttribute), false); if (HasProtocolAttributes) { - Assert.AreEqual (1, IP2Attributes.Length, "[Protocol] IP2"); + Assert.That (IP2Attributes.Length, Is.EqualTo (1), "[Protocol] IP2"); var IP2Protocol = (ProtocolAttribute) IP2Attributes [0]; - Assert.AreEqual ("P2", IP2Protocol.Name, "Name"); + Assert.That (IP2Protocol.Name, Is.EqualTo ("P2"), "Name"); // and a wrapper type var wrapperType = bindingAssembly.GetType ("Bindings.Test.Protocol.P2Wrapper"); - Assert.IsNotNull (wrapperType, "P2_Wrapper"); - Assert.AreEqual (wrapperType, IP2Protocol.WrapperType, "WrapperType"); + Assert.That (wrapperType, Is.Not.Null, "P2_Wrapper"); + Assert.That (IP2Protocol.WrapperType, Is.EqualTo (wrapperType), "WrapperType"); } else { - Assert.AreEqual (0, IP2Attributes.Length, "[Protocol] IP2"); + Assert.That (IP2Attributes.Length, Is.EqualTo (0), "[Protocol] IP2"); // and a wrapper type var wrapperType = bindingAssembly.GetType ("Bindings.Test.Protocol.P2Wrapper"); - Assert.IsNotNull (wrapperType, "P2_Wrapper"); + Assert.That (wrapperType, Is.Not.Null, "P2_Wrapper"); } // and a model-like class - var model = bindingAssembly.GetType ("Bindings.Test.Protocol.P2"); - Assert.IsNotNull (model, "P2"); + var model = bindingAssembly.GetType ("Bindings.Test.Protocol.P2")!; + Assert.That (model, Is.Not.Null, "P2"); // but without the [Model] attribute - Assert.False (model.IsDefined (typeof (ModelAttribute), false), "model"); + Assert.That (model.IsDefined (typeof (ModelAttribute), false), Is.False, "model"); } [Test] @@ -175,33 +186,33 @@ public void ProtocolWithBaseTypeAndModel () var bindingAssembly = GetType ().Assembly; // the interface must be created - var IP3 = bindingAssembly.GetType ("Bindings.Test.Protocol.IP3"); - Assert.IsNotNull (IP3, "IP3"); + var IP3 = bindingAssembly.GetType ("Bindings.Test.Protocol.IP3")!; + Assert.That (IP3, Is.Not.Null, "IP3"); // with a [Protocol] attribute var IP3Attributes = IP3.GetCustomAttributes (typeof (ProtocolAttribute), false); if (HasProtocolAttributes) { - Assert.AreEqual (1, IP3Attributes.Length, "[Protocol] IP3"); + Assert.That (IP3Attributes.Length, Is.EqualTo (1), "[Protocol] IP3"); var IP3Protocol = (ProtocolAttribute) IP3Attributes [0]; - Assert.AreEqual ("P3", IP3Protocol.Name, "Name"); + Assert.That (IP3Protocol.Name, Is.EqualTo ("P3"), "Name"); // and a wrapper type var wrapperType = bindingAssembly.GetType ("Bindings.Test.Protocol.P3Wrapper"); - Assert.IsNotNull (wrapperType, "P3_Wrapper"); - Assert.AreEqual (wrapperType, IP3Protocol.WrapperType, "WrapperType"); + Assert.That (wrapperType, Is.Not.Null, "P3_Wrapper"); + Assert.That (IP3Protocol.WrapperType, Is.EqualTo (wrapperType), "WrapperType"); } else { - Assert.AreEqual (0, IP3Attributes.Length, "[Protocol] IP3"); + Assert.That (IP3Attributes.Length, Is.EqualTo (0), "[Protocol] IP3"); // and a wrapper type var wrapperType = bindingAssembly.GetType ("Bindings.Test.Protocol.P3Wrapper"); - Assert.IsNotNull (wrapperType, "P3_Wrapper"); + Assert.That (wrapperType, Is.Not.Null, "P3_Wrapper"); } // and a model class - var model = bindingAssembly.GetType ("Bindings.Test.Protocol.P3"); - Assert.IsNotNull (model, "P3"); + var model = bindingAssembly.GetType ("Bindings.Test.Protocol.P3")!; + Assert.That (model, Is.Not.Null, "P3"); // with a [Model] attribute - Assert.True (model.IsDefined (typeof (ModelAttribute), false), "model"); + Assert.That (model.IsDefined (typeof (ModelAttribute), false), Is.True, "model"); } class MembersImplementation : NSObject, Bindings.Test.Protocol.IMemberAttributes { @@ -210,12 +221,12 @@ public void RequiredInstanceMethod () } public string RequiredInstanceProperty { - get { return null; } + get { return null!; } set { } } public NSString RequiredReadonlyProperty { - get { return null; } + get { return null!; } } } @@ -230,14 +241,14 @@ void CleanupSignatures (objc_method_description [] methods) public void ProtocolMembers () { IntPtr protocol = objc_getProtocol ("MemberAttributes"); - Assert.AreNotEqual (IntPtr.Zero, protocol, "a"); + Assert.That (protocol, Is.Not.EqualTo (IntPtr.Zero), "a"); objc_method_description [] methods; // Required instance methods methods = protocol_copyMethodDescriptionList (protocol, true, true); CleanupSignatures (methods); - Assert.AreEqual (4, methods.Length, "Required Instance Methods: Count"); + Assert.That (methods.Length, Is.EqualTo (4), "Required Instance Methods: Count"); AssertContains (methods, new objc_method_description ("requiredInstanceMethod", "v@:"), "Required Instance Methods: requiredInstanceMethod"); AssertContains (methods, new objc_method_description ("requiredInstanceProperty", "@@:"), "Required Instance Methods: requiredInstanceProperty"); AssertContains (methods, new objc_method_description ("setRequiredInstanceProperty:", "v@:@"), "Required Instance Methods: setRequiredInstanceProperty"); @@ -246,7 +257,7 @@ public void ProtocolMembers () // Required static methods methods = protocol_copyMethodDescriptionList (protocol, true, false); CleanupSignatures (methods); - Assert.AreEqual (3, methods.Length, "Required Static Methods: Count"); + Assert.That (methods.Length, Is.EqualTo (3), "Required Static Methods: Count"); AssertContains (methods, new objc_method_description ("requiredStaticMethod", "v@:"), "Required Static Methods: requiredStaticMethod"); AssertContains (methods, new objc_method_description ("setRequiredStaticProperty:", "v@:@"), "Required Static Methods: setRequiredStaticProperty:"); AssertContains (methods, new objc_method_description ("requiredStaticProperty", "@@:"), "Required Static Methods: requiredStaticProperty"); @@ -254,7 +265,7 @@ public void ProtocolMembers () // Optional instance methods methods = protocol_copyMethodDescriptionList (protocol, false, true); CleanupSignatures (methods); - Assert.AreEqual (19, methods.Length, "Optional Instance Methods: Count"); + Assert.That (methods.Length, Is.EqualTo (19), "Optional Instance Methods: Count"); AssertContains (methods, new objc_method_description ("variadicMethod:", "v@:^v"), "Optional Instance Methods: variadicMethod:"); AssertContains (methods, new objc_method_description ("methodWithReturnType", "@@:"), "Optional Instance Methods: methodWithReturnType"); AssertContains (methods, new objc_method_description ("methodWithParameter:", "v@:i"), "Optional Instance Methods: methodWithParameter:"); @@ -278,7 +289,7 @@ public void ProtocolMembers () // Optional static methods methods = protocol_copyMethodDescriptionList (protocol, false, false); CleanupSignatures (methods); - Assert.AreEqual (3, methods.Length, "Optional Static Methods: Count"); + Assert.That (methods.Length, Is.EqualTo (3), "Optional Static Methods: Count"); AssertContains (methods, new objc_method_description ("optionalStaticMethod", "v@:"), "Optional Static Methods: optionalStaticMethod"); AssertContains (methods, new objc_method_description ("optionalStaticProperty", "@@:"), "Optional Static Methods: optionalStaticProperty"); AssertContains (methods, new objc_method_description ("setOptionalStaticProperty:", "v@:@"), "Optional Static Methods: setOptionalStaticProperty:"); @@ -290,9 +301,9 @@ public void ProtocolMembers () // see file objc4-647/runtime/objc-runtime-old.mm in Apple's open source code), // so we need to verify differently for the dynamic registrar. if (XamarinTests.ObjCRuntime.Registrar.IsStaticRegistrar) { - Assert.AreEqual (9, properties.Length, "Properties: Count"); + Assert.That (properties.Length, Is.EqualTo (9), "Properties: Count"); } else { - Assert.AreEqual (2, properties.Length, "Properties: Count"); + Assert.That (properties.Length, Is.EqualTo (2), "Properties: Count"); } AssertContains (properties, new objc_property ("requiredInstanceProperty", "T@\"NSString\",N", new objc_property_attribute [] { @@ -381,7 +392,7 @@ static objc_method_description [] protocol_copyMethodDescriptionList (IntPtr pro var rv = new objc_method_description [count]; for (int i = 0; i < count; i++) { var sel = new Selector (Marshal.ReadIntPtr (methods + (IntPtr.Size * 2) * i)).Name; - var types = Marshal.PtrToStringAuto (Marshal.ReadIntPtr (methods + (IntPtr.Size * 2) * i + IntPtr.Size)); + var types = Marshal.PtrToStringAuto (Marshal.ReadIntPtr (methods + (IntPtr.Size * 2) * i + IntPtr.Size))!; rv [i] = new objc_method_description (sel, types); } return rv; @@ -406,12 +417,13 @@ static objc_property [] protocol_copyPropertyList (IntPtr protocol) Trace ($"Protocol {new Protocol (protocol)} has {rv} properties"); try { for (int i = 0; i < count; i++) { - var prop = new objc_property (); IntPtr p = Marshal.ReadIntPtr (list, IntPtr.Size * i); + var prop = new objc_property ( + property_getName (p), + property_getAttributes (p), + property_copyAttributeList (p) + ); rv [i] = prop; - prop.Name = property_getName (p); - prop.Attributes = property_getAttributes (p); - prop.AttributeList = property_copyAttributeList (p); Trace ($" #{i + 1}: Name={prop.Name} Attributes={prop.Attributes} AttributeList={prop.AttributeList}"); } return rv; @@ -429,7 +441,7 @@ static objc_property [] protocol_copyPropertyList (IntPtr protocol) static string property_getName (IntPtr property) { - return Marshal.PtrToStringAuto (_property_getName (property)); + return Marshal.PtrToStringAuto (_property_getName (property))!; } [DllImport ("/usr/lib/libobjc.dylib", EntryPoint = "property_getAttributes")] @@ -437,7 +449,7 @@ static string property_getName (IntPtr property) static string property_getAttributes (IntPtr property) { - var v = Marshal.PtrToStringAuto (_property_getAttributes (property)); + var v = Marshal.PtrToStringAuto (_property_getAttributes (property))!; // Ignore any "?" attributes, apparently it's a new property attribute in Xcode 16, but since there's no documentation about it yet, just ignore it. var attribs = v.Split (',').Where (v => v != "?").ToArray (); @@ -454,11 +466,12 @@ static objc_property_attribute [] property_copyAttributeList (IntPtr property) var rv = new List (count); try { for (int i = 0; i < count; i++) { - var attrib = new objc_property_attribute (); IntPtr n = Marshal.ReadIntPtr (list, (IntPtr.Size * 2) * i); IntPtr v = Marshal.ReadIntPtr (list, (IntPtr.Size * 2) * i + IntPtr.Size); - attrib.Name = Marshal.PtrToStringAuto (n); - attrib.Value = Marshal.PtrToStringAuto (v); + var attrib = new objc_property_attribute ( + Marshal.PtrToStringAuto (n)!, + Marshal.PtrToStringAuto (v)! + ); // Ignore any "?" attributes, apparently it's a new property attribute in Xcode 16, but since there's no documentation about it yet, just ignore it. if (attrib.Name == "?" && string.IsNullOrEmpty (attrib.Value)) continue; @@ -477,25 +490,23 @@ class objc_property_attribute : IEquatable { public string Name; public string Value; - public objc_property_attribute () - { - } - public objc_property_attribute (string name, string value) { this.Name = name; this.Value = value; } - bool IEquatable.Equals (objc_property_attribute other) + bool IEquatable.Equals (objc_property_attribute? other) { + if (other is null) + return false; + return Name == other.Name && Value == other.Value; } - public override bool Equals (object obj) + public override bool Equals (object? obj) { - var other = (objc_property_attribute) obj; - if (other is null) + if (obj is not objc_property_attribute other) return false; return Name == other.Name && Value == other.Value; } @@ -515,11 +526,11 @@ class objc_property : IEquatable { public string Name; public string Attributes; public objc_property_attribute [] AttributeList; - - public objc_property () - { - } - + /* + public objc_property () + { + } + */ public objc_property (string name, string attributes, objc_property_attribute [] list) { this.Name = name; @@ -532,8 +543,11 @@ public override string ToString () return string.Format ("[{0}; {1}; {2}]", Name, Attributes, string.Join (", ", new List (AttributeList).Select ((v) => string.Format ("{0} = {1}", v.Name, v.Value)))); } - bool IEquatable.Equals (objc_property other) + bool IEquatable.Equals (objc_property? other) { + if (other is null) + return false; + if (other.Name != Name) return false; if (other.Attributes != Attributes) @@ -562,8 +576,11 @@ public override string ToString () return string.Format ("[{0}; {1}]", Name, Types); } - bool IEquatable.Equals (objc_method_description other) + bool IEquatable.Equals (objc_method_description? other) { + if (other is null) + return false; + return other.Name == Name && other.Types == Types; } } diff --git a/tests/bindings-test/Registrar.cs b/tests/bindings-test/Registrar.cs index e9c9a17a876c..2a24d386946f 100644 --- a/tests/bindings-test/Registrar.cs +++ b/tests/bindings-test/Registrar.cs @@ -48,7 +48,7 @@ public static bool IsTrimmableStaticRegistrar { [UnconditionalSuppressMessage ("Trimming", "IL2026", Justification = "This test accesses internals, and this code seems to work fine with the trimmer enabled.")] public static Registrars CurrentRegistrar { get { - var isTrimmableStaticRegistrar = (bool) typeof (Runtime).GetProperty ("IsTrimmableStaticRegistrar", BindingFlags.NonPublic | BindingFlags.Static)!.GetValue (null); + var isTrimmableStaticRegistrar = (bool) typeof (Runtime).GetProperty ("IsTrimmableStaticRegistrar", BindingFlags.NonPublic | BindingFlags.Static)!.GetValue (null)!; if (isTrimmableStaticRegistrar) return Registrars.TrimmableStatic; @@ -56,9 +56,9 @@ public static Registrars CurrentRegistrar { if (__registrar__ is not null) return Registrars.ManagedStatic; var types = new Type [] { typeof (NativeHandle), typeof (bool).MakeByRefType () }; - var find_type = typeof (Class).GetMethod ("FindType", BindingFlags.Static | BindingFlags.NonPublic, null, types, null); + var find_type = typeof (Class).GetMethod ("FindType", BindingFlags.Static | BindingFlags.NonPublic, null, types, null)!; var type_to_find = typeof (RegistrationTestClass); - var type = (Type) find_type.Invoke (null, new object [] { Class.GetHandle (type_to_find), false }); + var type = (Type) find_type.Invoke (null!, new object? [] { Class.GetHandle (type_to_find), false })!; var is_static = type_to_find == type; if (is_static) { return Registrars.Static; diff --git a/tests/bindings-test/RegistrarBindingTest.cs b/tests/bindings-test/RegistrarBindingTest.cs index 93bba2d9c9e2..fb3cf6821c83 100644 --- a/tests/bindings-test/RegistrarBindingTest.cs +++ b/tests/bindings-test/RegistrarBindingTest.cs @@ -57,7 +57,7 @@ public static void OptionalStaticCallback (Action completionHandler) public Action RequiredReturnValue () { return new Action ((v) => { - Assert.AreEqual (42, v, "RequiredReturnValue"); + Assert.That (v, Is.EqualTo (42), "RequiredReturnValue"); }); } @@ -65,7 +65,7 @@ public Action RequiredReturnValue () public Action OptionalReturnValue () { return new Action ((v) => { - Assert.AreEqual (42, v, "RequiredReturnValue"); + Assert.That (v, Is.EqualTo (42), "RequiredReturnValue"); }); } @@ -73,7 +73,7 @@ public Action OptionalReturnValue () public static Action RequiredStaticReturnValue () { return new Action ((v) => { - Assert.AreEqual (42, v, "RequiredReturnValue"); + Assert.That (v, Is.EqualTo (42), "RequiredReturnValue"); }); } @@ -81,7 +81,7 @@ public static Action RequiredStaticReturnValue () public static Action OptionalStaticReturnValue () { return new Action ((v) => { - Assert.AreEqual (42, v, "RequiredReturnValue"); + Assert.That (v, Is.EqualTo (42), "RequiredReturnValue"); }); } } @@ -99,10 +99,10 @@ public void DerivedClassBlockCallback () ObjCBlockTester.CallOptionalStaticCallback (); DerivedBlockCallbackClass.Answer = 2; - Assert.IsFalse (obj.InvokeNullableCallbackNatively (null), "NullableCallback A rv"); + Assert.That (obj.InvokeNullableCallbackNatively (null), Is.False, "NullableCallback A rv"); int nullableResult = -1; - Assert.IsTrue (obj.InvokeNullableCallbackNatively ((v) => nullableResult = v), "NullableCallback B rv"); - Assert.AreEqual (24, nullableResult, "NullableCallback result"); + Assert.That (obj.InvokeNullableCallbackNatively ((v) => nullableResult = v), Is.True, "NullableCallback B rv"); + Assert.That (nullableResult, Is.EqualTo (24), "NullableCallback result"); } } @@ -141,7 +141,7 @@ public static void OptionalStaticCallback (Action completionHandler) public override Action RequiredReturnValue () { return new Action ((v) => { - Assert.AreEqual (Answer, v, "RequiredReturnValue"); + Assert.That (v, Is.EqualTo (Answer), "RequiredReturnValue"); }); } @@ -150,7 +150,7 @@ public Action OptionalReturnValue () { return new Action ((v) => { Console.WriteLine ("OptionalReturnValue"); - Assert.AreEqual (Answer, v, "RequiredReturnValue"); + Assert.That (v, Is.EqualTo (Answer), "RequiredReturnValue"); }); } @@ -158,7 +158,7 @@ public Action OptionalReturnValue () public static Action RequiredStaticReturnValue () { return new Action ((v) => { - Assert.AreEqual (Answer, v, "RequiredReturnValue"); + Assert.That (v, Is.EqualTo (Answer), "RequiredReturnValue"); }); } @@ -167,7 +167,7 @@ public static Action OptionalStaticReturnValue () { return new Action ((v) => { Console.WriteLine ("OptionalStaticReturnValue"); - Assert.AreEqual (Answer, v, "RequiredReturnValue"); + Assert.That (v, Is.EqualTo (Answer), "RequiredReturnValue"); }); } } @@ -201,7 +201,7 @@ public static void OptionalRequiredCallback (Action completionHandler) Action IObjCProtocolBlockTest.RequiredReturnValue () { return new Action ((v) => { - Assert.AreEqual (42, v, "RequiredReturnValue"); + Assert.That (v, Is.EqualTo (42), "RequiredReturnValue"); }); } @@ -209,7 +209,7 @@ Action IObjCProtocolBlockTest.RequiredReturnValue () public Action OptionalReturnValue () { return new Action ((v) => { - Assert.AreEqual (42, v, "RequiredReturnValue"); + Assert.That (v, Is.EqualTo (42), "RequiredReturnValue"); }); } @@ -217,7 +217,7 @@ public Action OptionalReturnValue () public static Action RequiredStaticReturnValue () { return new Action ((v) => { - Assert.AreEqual (42, v, "RequiredReturnValue"); + Assert.That (v, Is.EqualTo (42), "RequiredReturnValue"); }); } @@ -225,7 +225,7 @@ public static Action RequiredStaticReturnValue () public static Action OptionalStaticReturnValue () { return new Action ((v) => { - Assert.AreEqual (42, v, "RequiredReturnValue"); + Assert.That (v, Is.EqualTo (42), "RequiredReturnValue"); }); } } @@ -311,7 +311,7 @@ public void ProtocolWithBlockProperties (bool required, bool instance) } } ObjCBlockTester.CallProtocolWithBlockProperties (pb, required, instance); - Assert.IsTrue (callbackCalled, "Callback"); + Assert.That (callbackCalled, Is.True, "Callback"); } } @@ -338,7 +338,7 @@ public void ProtocolWithNativeBlockProperties (bool required, bool instance) PropertyBlock.MyOptionalStaticProperty! (); } } - Assert.AreEqual (calledCounter + 1, ObjCBlockTester.CalledBlockCount, "Blocks called"); + Assert.That (ObjCBlockTester.CalledBlockCount, Is.EqualTo (calledCounter + 1), "Blocks called"); } } [Test] @@ -372,7 +372,7 @@ public void LinkedAway (bool required, bool instance) if (re.Code == 8009) { Assert.That (re.Message, Does.StartWith ("Unable to locate the block to delegate conversion method for the method Xamarin.BindingTests.RegistrarBindingTest+FakePropertyBlock.set_"), re.Message, "Message"); } else { - Assert.AreEqual ("The runtime function get_block_wrapper_creator has been linked away.", re.Message, "Message"); + Assert.That (re.Message, Is.EqualTo ("The runtime function get_block_wrapper_creator has been linked away."), "Message"); } } } diff --git a/tests/bindings-test/RuntimeTest.cs b/tests/bindings-test/RuntimeTest.cs index 4cebd518ae96..f445ec7bca9e 100644 --- a/tests/bindings-test/RuntimeTest.cs +++ b/tests/bindings-test/RuntimeTest.cs @@ -9,7 +9,7 @@ public class RuntimeTest { [Test] public void GlobalStringTest () { - Assert.AreEqual ("There's nothing cruvus here!", (string) Globals.GlobalString, "Global string"); + Assert.That ((string) Globals.GlobalString, Is.EqualTo ("There's nothing cruvus here!"), "Global string"); } [Test] @@ -95,7 +95,7 @@ public void SwiftTest () { TestRuntime.AssertXcodeVersion (13, 0); using var obj = new SwiftTestClass (); - Assert.AreEqual ("Hello from Swift", obj.SayHello (), "Hello"); + Assert.That (obj.SayHello (), Is.EqualTo ("Hello from Swift"), "Hello"); } [Test] @@ -105,18 +105,18 @@ public void SwiftTypeEncodings () using var obj = new SwiftTestClass (); - Assert.AreEqual ("42", obj.DoSomething ("42"), "DoSomething"); + Assert.That (obj.DoSomething ("42"), Is.EqualTo ("42"), "DoSomething"); - string asyncResult = null; + string? asyncResult = null; obj.DoSomethingAsync ("dolphins", (v) => asyncResult = v); var done = TestRuntime.RunAsync (TimeSpan.FromSeconds (5), () => asyncResult is not null); - Assert.AreEqual ("dolphins", asyncResult, "DoSomethingAsync"); - Assert.IsTrue (done, "Done"); + Assert.That (asyncResult, Is.EqualTo ("dolphins"), "DoSomethingAsync"); + Assert.That (done, Is.True, "Done"); obj.DoSomethingComplexAsync ("fish", IntPtr.Zero, (v) => asyncResult = v); done = TestRuntime.RunAsync (TimeSpan.FromSeconds (5), () => asyncResult is not null); - Assert.AreEqual ("fish", asyncResult, "DoSomethingComplexAsync"); - Assert.IsTrue (done, "Done 2"); + Assert.That (asyncResult, Is.EqualTo ("fish"), "DoSomethingComplexAsync"); + Assert.That (done, Is.True, "Done 2"); } [Test] @@ -124,7 +124,7 @@ public void SwiftTestClass2 () { TestRuntime.AssertXcodeVersion (13, 0); using var obj = new SwiftTestClass2 (); - Assert.AreEqual ("Hello from Swift 2", obj.SayHello2 (), "Hello"); + Assert.That (obj.SayHello2 (), Is.EqualTo ("Hello from Swift 2"), "Hello"); } [Test] diff --git a/tests/bindings-test/dotnet/shared.csproj b/tests/bindings-test/dotnet/shared.csproj index 710148d2d1c0..3acadaec8a62 100644 --- a/tests/bindings-test/dotnet/shared.csproj +++ b/tests/bindings-test/dotnet/shared.csproj @@ -16,10 +16,6 @@ $(NoWarn);CS8981 - - true - Nullable - $(DefineConstants);BINDINGS_TEST diff --git a/tests/bindings-test2/BindingTest.cs b/tests/bindings-test2/BindingTest.cs index 7da68e8bbfc5..803e3bf91624 100644 --- a/tests/bindings-test2/BindingTest.cs +++ b/tests/bindings-test2/BindingTest.cs @@ -9,8 +9,8 @@ public class BindingTest { [Test] public void Test () { - Assert.AreEqual (42, CFunctions.getIntOfChocolate (), "chocolate"); - Assert.AreEqual (42, Bindings.Test.CFunctions.theUltimateAnswer (), "theUltimateAnswer"); + Assert.That (CFunctions.getIntOfChocolate (), Is.EqualTo (42), "chocolate"); + Assert.That (Bindings.Test.CFunctions.theUltimateAnswer (), Is.EqualTo (42), "theUltimateAnswer"); } } } diff --git a/tests/cecil-tests/Documentation.KnownFailures.txt b/tests/cecil-tests/Documentation.KnownFailures.txt index 259d2d5ebdf1..9e1603a34248 100644 --- a/tests/cecil-tests/Documentation.KnownFailures.txt +++ b/tests/cecil-tests/Documentation.KnownFailures.txt @@ -25152,7 +25152,6 @@ T:AppKit.NSPrintingPageOrder T:AppKit.NSPrintingPaginationMode T:AppKit.NSPrintPanelOptions T:AppKit.NSPrintPanelResult -T:AppKit.NSPrintPreviewGraphicsContext T:AppKit.NSPrintRenderingQuality T:AppKit.NSProgressIndicatorStyle T:AppKit.NSProgressIndicatorThickness diff --git a/tests/cecil-tests/Helper.cs b/tests/cecil-tests/Helper.cs index 30f4e487e42f..f06c07616a8a 100644 --- a/tests/cecil-tests/Helper.cs +++ b/tests/cecil-tests/Helper.cs @@ -616,7 +616,7 @@ public static void LoadWithoutNetworkAccess (this XmlDocument doc, string filena using (var fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) { var settings = new XmlReaderSettings () { XmlResolver = null, - DtdProcessing = DtdProcessing.Parse, + DtdProcessing = DtdProcessing.Ignore, }; using (var reader = XmlReader.Create (fs, settings)) { doc.Load (reader); diff --git a/tests/cecil-tests/cecil-tests.csproj b/tests/cecil-tests/cecil-tests.csproj index 51cfe5e183e4..a9d4c1fc8192 100644 --- a/tests/cecil-tests/cecil-tests.csproj +++ b/tests/cecil-tests/cecil-tests.csproj @@ -4,9 +4,6 @@ net$(BundledNETCoreAppTargetFrameworkVersion) ceciltests cecil-tests - latest - enable - Nullable diff --git a/tests/common/AppDelegate.cs b/tests/common/AppDelegate.cs index cb322e2e2b75..cac8bcae5512 100644 --- a/tests/common/AppDelegate.cs +++ b/tests/common/AppDelegate.cs @@ -7,18 +7,17 @@ using MonoTouch.NUnit.UI; using NUnit.Framework.Internal; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { - static internal UIWindow MainWindow; - public static TouchRunner Runner { get; set; } + static internal UIWindow? MainWindow; + public static TouchRunner? Runner { get; set; } partial void PostFinishedLaunching (); - public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary? launchOptions) { #if __MACCATALYST__ || __MACOS__ TestRuntime.NotifyLaunchCompleted (); @@ -61,7 +60,7 @@ public override UISceneConfiguration GetConfiguration (UIApplication application public partial class SceneDelegate : UIResponder, IUIWindowSceneDelegate { [Export ("window")] - public UIWindow Window { get; set; } + public UIWindow? Window { get; set; } [Export ("scene:willConnectToSession:options:")] public void WillConnect (UIScene scene, UISceneSession session, UISceneConnectionOptions connectionOptions) diff --git a/tests/common/Assert.cs b/tests/common/Assert.cs index 5f1b7bb0f344..e16866ee8362 100644 --- a/tests/common/Assert.cs +++ b/tests/common/Assert.cs @@ -92,7 +92,7 @@ protected virtual void SetUp () public static void Assert (string msg, bool condition) { - NUnit.Framework.Assert.True (condition, msg); + Assert.That (condition, Is.True, msg); } public static void AssertEquals (object a, object b) diff --git a/tests/common/AssertHelpers.cs b/tests/common/AssertHelpers.cs index cb4aba3fe4ca..4975c7d26110 100644 --- a/tests/common/AssertHelpers.cs +++ b/tests/common/AssertHelpers.cs @@ -11,7 +11,7 @@ public static void Throws (Action action, string expectedExceptionMessage, st action (); throw new AssertionException (string.Format ("Expected {0}, but no exception was thrown. {1}.", typeof (T).FullName, message)); } catch (T ex) { - Assert.AreEqual (expectedExceptionMessage, ex.Message, message); + Assert.That (ex.Message, Is.EqualTo (expectedExceptionMessage), message); } } diff --git a/tests/common/BinLog.cs b/tests/common/BinLog.cs index f02f5123bfec..e8afbc729d96 100644 --- a/tests/common/BinLog.cs +++ b/tests/common/BinLog.cs @@ -210,6 +210,9 @@ public static IEnumerable GetBuildLogWarnings (string path) .Where (v => v.Type == BuildLogEventType.Warning) // We're often referencing earlier .NET projects (Touch.Unit/MonoTouch.Dialog), so ignore any out-of-support warnings. .Where (v => v.Message?.Contains ("is out of support and will not receive security updates in the future") != true) + // Ignore any messages about the settings files, we get *a lot* of those + .Where (v => !(v.Message?.Contains ("The settings file '/Users/") == true && v.Message?.Contains ("/Library/Preferences/maui/Settings.plist' is deprecated, and will be ignored in .NET 11+. ") == true)) + .Where (v => !(v.Message?.Contains ("The settings file '/Users/") == true && v.Message?.Contains ("/Library/Preferences/Xamarin/Settings.plist' is deprecated, and will be ignored in .NET 11+. ") == true)) ; } diff --git a/tests/common/BundlerTool.cs b/tests/common/BundlerTool.cs index 7a5754620653..3f45c28b1bf7 100644 --- a/tests/common/BundlerTool.cs +++ b/tests/common/BundlerTool.cs @@ -321,7 +321,7 @@ public virtual void AssertExecute (string message = null) public void AssertExecuteFailure (string message = null) { - Assert.AreEqual (1, Execute (), message); + Assert.That (Execute (), Is.EqualTo (1), message); } public abstract void CreateTemporaryApp (Profile profile, string appName = "testApp", string code = null, IList extraArgs = null, string extraCode = null, string usings = null); diff --git a/tests/common/Configuration.cs b/tests/common/Configuration.cs index e4313eb46264..8154d4e9b100 100644 --- a/tests/common/Configuration.cs +++ b/tests/common/Configuration.cs @@ -6,23 +6,23 @@ using System.Threading; using Xamarin.Utils; -#nullable disable // until we get around to fixing this file +#nullable enable namespace Xamarin.Tests { static partial class Configuration { public const string XI_ProductName = "MonoTouch"; public const string XM_ProductName = "Xamarin.Mac"; - public static string DotNetBclDir; - public static string DotNetCscCommand; + public static string DotNetBclDir = ""; + public static string DotNetCscCommand = ""; public static string DotNetExecutable; public static string DotNetTfm; - public static string mt_src_root; + public static string? mt_src_root; public static string sdk_version; public static string tvos_sdk_version; public static string macos_sdk_version; public static string xcode_root; - public static string XcodeVersionString; + public static string? XcodeVersionString; public static string xcode83_root; public static string xcode94_root; #if MONOMAC @@ -37,12 +37,12 @@ static partial class Configuration { public static bool XcodeIsStable; public static string DOTNET_DIR; - static Version xcode_version; + static Version? xcode_version; public static Version XcodeVersion { get { if (xcode_version is null) - xcode_version = Version.Parse (XcodeVersionString); + xcode_version = Version.Parse (XcodeVersionString!); return xcode_version; } } @@ -101,11 +101,11 @@ public static string XcodeLocation { } // This is the location of an Xcode which is older than the recommended one. - public static string GetOldXcodeRoot (Version min_version = null) + public static string? GetOldXcodeRoot (Version? min_version = null) { var with_versions = new List> (); - var max_version = Version.Parse (XcodeVersionString); + var max_version = Version.Parse (XcodeVersionString!); foreach (var xcode in GetAllXcodes ()) { var path = xcode.Path; var version = xcode.Version; @@ -153,8 +153,8 @@ static void ParseConfigFiles () if (!test_config.Any () && Environment.OSVersion.Platform != PlatformID.Win32NT) { // Run 'make test.config' in the tests/ directory // First find the tests/ directory - var dir = TestAssemblyDirectory; - string tests_dir = null; + var dir = TestAssemblyDirectory!; + string? tests_dir = null; while (dir.Length > 1) { var file = Path.Combine (dir, "tests"); if (Directory.Exists (file)) { @@ -162,7 +162,7 @@ static void ParseConfigFiles () break; } - dir = Path.GetDirectoryName (dir); + dir = Path.GetDirectoryName (dir)!; } if (tests_dir is null) @@ -202,7 +202,8 @@ static void ParseConfigFile (string file) } } - internal static string GetVariable (string variable, string @default) + [return: NotNullIfNotNull (nameof (@default))] + internal static string? GetVariable (string variable, string? @default) { var result = Environment.GetEnvironmentVariable (variable); if (string.IsNullOrEmpty (result)) @@ -239,7 +240,7 @@ public static string EvaluateVariable (string variable) return result.Substring (variable.Length + 1); } - static string GetXcodeVersion (string xcode_path) + static string? GetXcodeVersion (string xcode_path) { var version_plist = Path.Combine (xcode_path, "..", "version.plist"); if (!File.Exists (version_plist)) @@ -248,7 +249,7 @@ static string GetXcodeVersion (string xcode_path) return GetPListStringValue (version_plist, "CFBundleShortVersionString"); } - public static string GetPListStringValue (string plist, string key) + public static string? GetPListStringValue (string plist, string key) { var settings = new System.Xml.XmlReaderSettings (); settings.DtdProcessing = System.Xml.DtdProcessing.Ignore; @@ -256,15 +257,15 @@ public static string GetPListStringValue (string plist, string key) using (var fs = new StringReader (ReadPListAsXml (plist))) { using (var reader = System.Xml.XmlReader.Create (fs, settings)) { doc.Load (reader); - return doc.DocumentElement - .SelectSingleNode ($"//dict/key[text()='{key}']/following-sibling::string[1]/text()").Value; + return doc.DocumentElement! + .SelectSingleNode ($"//dict/key[text()='{key}']/following-sibling::string[1]/text()")!.Value; } } } public static string ReadPListAsXml (string path) { - string tmpfile = null; + string? tmpfile = null; try { tmpfile = Path.GetTempFileName (); File.Copy (path, tmpfile, true); @@ -295,10 +296,10 @@ static Configuration () include_mac = !string.IsNullOrEmpty (GetVariable ("INCLUDE_MAC", "")); include_tvos = !string.IsNullOrEmpty (GetVariable ("INCLUDE_TVOS", "")); include_maccatalyst = !string.IsNullOrEmpty (GetVariable ("INCLUDE_MACCATALYST", "")); - DotNetBclDir = GetVariable ("DOTNET_BCL_DIR", null); - DotNetCscCommand = GetVariable ("DOTNET_CSC_COMMAND", null)?.Trim ('\''); - DotNetExecutable = GetVariable ("DOTNET", null); - DotNetTfm = GetVariable ("DOTNET_TFM", null); + DotNetBclDir = GetVariable ("DOTNET_BCL_DIR", ""); + DotNetCscCommand = GetVariable ("DOTNET_CSC_COMMAND", "").Trim ('\''); + DotNetExecutable = GetVariable ("DOTNET", ""); + DotNetTfm = GetVariable ("DOTNET_TFM", ""); XcodeIsStable = string.Equals (GetVariable ("XCODE_IS_STABLE", ""), "true", StringComparison.OrdinalIgnoreCase); DOTNET_DIR = GetVariable ("DOTNET_DIR", ""); @@ -359,7 +360,7 @@ public static string RootPath { } } - public static bool TryGetRootPath (out string rootPath) + public static bool TryGetRootPath ([NotNullWhen (true)] out string? rootPath) { try { rootPath = RootPath; @@ -643,7 +644,7 @@ public static string CloneTestDirectory (string directory) foreach (var file in files) { var src = Path.Combine (directory, file); var tgt = Path.Combine (testsTemporaryDirectory, file); - var tgtDir = Path.GetDirectoryName (tgt); + var tgtDir = Path.GetDirectoryName (tgt)!; Directory.CreateDirectory (tgtDir); File.Copy (src, tgt); if (tgt.EndsWith (".csproj", StringComparison.OrdinalIgnoreCase)) { @@ -681,19 +682,19 @@ public static void FixupTestFiles (string directory, string mode) } } - public static Dictionary GetBuildEnvironment (ApplePlatform platform) + public static Dictionary GetBuildEnvironment (ApplePlatform platform) { - var environment = new Dictionary (); + var environment = new Dictionary (); SetBuildVariables (platform, ref environment); return environment; } - public static void SetBuildVariables (ApplePlatform platform, ref Dictionary environment) + public static void SetBuildVariables (ApplePlatform platform, [NotNullIfNotNull (nameof (environment))] ref Dictionary? environment) { if (environment is null) - environment = new Dictionary (); + environment = new Dictionary (); - environment ["MD_APPLE_SDK_ROOT"] = Path.GetDirectoryName (Path.GetDirectoryName (xcode_root)); + environment ["DEVELOPER_DIR"] = Path.GetDirectoryName (Path.GetDirectoryName (xcode_root)!)!; // This is set by `dotnet test` and can cause building legacy projects to fail to build with: // Microsoft.NET.Build.Extensions.ConflictResolution.targets(30,5): @@ -713,13 +714,13 @@ public static string GetTestLibraryDirectory (ApplePlatform platform, bool? simu switch (platform) { case ApplePlatform.iOS: - dir = simulator.Value ? "iphonesimulator" : "iphoneos"; + dir = simulator == true ? "iphonesimulator" : "iphoneos"; break; case ApplePlatform.MacOSX: dir = "macos"; break; case ApplePlatform.TVOS: - dir = simulator.Value ? "tvsimulator" : "tvos"; + dir = simulator == true ? "tvsimulator" : "tvos"; break; case ApplePlatform.MacCatalyst: dir = "maccatalyst"; @@ -751,7 +752,7 @@ static bool IsAPFS { } else { var exit_code = ExecutionHelper.Execute ("/bin/df", new string [] { "-t", "apfs", "/" }, out var output, TimeSpan.FromSeconds (10)); - is_apfs = exit_code == 0 && output.Trim ().Split ('\n').Length >= 2; + is_apfs = exit_code == 0 && output?.Trim ()?.Split ('\n')?.Length >= 2; } } @@ -790,7 +791,7 @@ public static bool CanRunArm64 { [DllImport ("libc")] static extern int sysctlbyname (string name, ref int value, ref IntPtr size, IntPtr zero, IntPtr zeroAgain); - public static IEnumerable CallNM (string file, string nmArguments, string arch = null) + public static IEnumerable CallNM (string file, string nmArguments, string? arch = null) { var arguments = new List (new [] { nmArguments, file }); if (!string.IsNullOrEmpty (arch)) { @@ -809,12 +810,12 @@ public static IEnumerable CallNM (string file, string nmArguments, strin }); } - public static IEnumerable GetNativeSymbols (string file, string arch = null) + public static IEnumerable GetNativeSymbols (string file, string? arch = null) { return CallNM (file, "-gUjA", arch); } - public static IEnumerable GetUndefinedNativeSymbols (string file, string arch = null) + public static IEnumerable GetUndefinedNativeSymbols (string file, string? arch = null) { return CallNM (file, "-gujA", arch); } @@ -829,7 +830,7 @@ public static bool IsStableRelease { } public static bool TryGetApiDefinitionRsp (TargetFramework framework, - [NotNullWhen (true)] out string rspPath) + [NotNullWhen (true)] out string? rspPath) { rspPath = null; var platform = framework.Platform switch { @@ -846,7 +847,7 @@ public static bool TryGetApiDefinitionRsp (TargetFramework framework, } public static bool TryGetPlatformPreprocessorSymbolsRsp (TargetFramework framework, - [NotNullWhen (true)] out string rspPath) + [NotNullWhen (true)] out string? rspPath) { rspPath = null; var platform = framework.Platform switch { diff --git a/tests/common/ConfigurationNUnit.cs b/tests/common/ConfigurationNUnit.cs index 43a82b38bb15..b351d3b6cf80 100644 --- a/tests/common/ConfigurationNUnit.cs +++ b/tests/common/ConfigurationNUnit.cs @@ -6,7 +6,7 @@ using Xamarin.Utils; -#nullable disable // until we get around to fixing this file +#nullable enable namespace Xamarin.Tests { static partial class Configuration { diff --git a/tests/common/DotNet.cs b/tests/common/DotNet.cs index 0d0b0de77088..1f7a5c73e868 100644 --- a/tests/common/DotNet.cs +++ b/tests/common/DotNet.cs @@ -33,7 +33,7 @@ public static ExecutionResult AssertPack (string project, Dictionary? properties = null, bool? msbuildParallelism = null) { var rv = Execute ("pack", project, properties, false, msbuildParallelism: msbuildParallelism); - Assert.AreNotEqual (0, rv.ExitCode, "Unexpected success"); + Assert.That (rv.ExitCode, Is.Not.EqualTo (0), "Unexpected success"); return rv; } @@ -45,7 +45,7 @@ public static ExecutionResult AssertPublish (string project, Dictionary? properties = null) { var rv = Execute ("publish", project, properties, false); - Assert.AreNotEqual (0, rv.ExitCode, "Unexpected success"); + Assert.That (rv.ExitCode, Is.Not.EqualTo (0), "Unexpected success"); return rv; } @@ -73,7 +73,7 @@ public static ExecutionResult AssertRun (string project, Dictionary? properties = null) { var rv = Execute ("build", project, properties, false); - Assert.AreNotEqual (0, rv.ExitCode, "Unexpected success"); + Assert.That (rv.ExitCode, Is.Not.EqualTo (0), "Unexpected success"); return rv; } @@ -107,7 +107,7 @@ public static ExecutionResult AssertNew (string outputDirectory, string template if (rv.ExitCode != 0) { Console.WriteLine ($"'{Executable} {StringUtils.FormatArguments (args)}' failed with exit code {rv.ExitCode}."); Console.WriteLine (output); - Assert.AreEqual (0, rv.ExitCode, $"Exit code: {Executable} {StringUtils.FormatArguments (args)}"); + Assert.That (rv.ExitCode, Is.EqualTo (0), $"Exit code: {Executable} {StringUtils.FormatArguments (args)}"); } return new ExecutionResult (output, output, rv.ExitCode); } @@ -336,7 +336,7 @@ public static ExecutionResult Execute (string verb, string project, Dictionary arguments, TimeSpan? t return Execute (fileName, arguments, null, null, null, timeout); } - public static int Execute (string fileName, IList arguments, string working_directory = null, Action stdout_callback = null, Action stderr_callback = null, TimeSpan? timeout = null) + public static int Execute (string fileName, IList arguments, string? working_directory = null, Action? stdout_callback = null, Action? stderr_callback = null, TimeSpan? timeout = null) { return Execute (fileName, arguments, timed_out: out var _, workingDirectory: working_directory, stdout_callback: stdout_callback, stderr_callback: stderr_callback, timeout: timeout); } @@ -60,19 +60,19 @@ public static int Execute (string fileName, IList arguments, out StringB return Execute (fileName, arguments, out output, null, null); } - public static int Execute (string fileName, IList arguments, out StringBuilder output, string working_directory, TimeSpan? timeout = null) + public static int Execute (string fileName, IList arguments, out StringBuilder output, string? working_directory, TimeSpan? timeout = null) { output = new StringBuilder (); return Execute (fileName, arguments, out var _, workingDirectory: working_directory, stdout: output, stderr: output, timeout: timeout); } - public static int Execute (string fileName, IList arguments, out StringBuilder output, string working_directory, Dictionary environment_variables, TimeSpan? timeout = null) + public static int Execute (string fileName, IList arguments, out StringBuilder output, string? working_directory, Dictionary? environment_variables, TimeSpan? timeout = null) { output = new StringBuilder (); return Execute (fileName, arguments, out var _, workingDirectory: working_directory, stdout: output, stderr: output, timeout: timeout, environment_variables: environment_variables); } - public static int Execute (string fileName, IList arguments, out bool timed_out, string workingDirectory = null, Dictionary environment_variables = null, StringBuilder stdout = null, StringBuilder stderr = null, TimeSpan? timeout = null) + public static int Execute (string fileName, IList arguments, out bool timed_out, string? workingDirectory = null, Dictionary? environment_variables = null, StringBuilder? stdout = null, StringBuilder? stderr = null, TimeSpan? timeout = null) { var rv = Execution.RunAsync (fileName, arguments, workingDirectory: workingDirectory, environment: environment_variables, timeout: timeout).Result; if (stdout is not null) @@ -81,11 +81,11 @@ public static int Execute (string fileName, IList arguments, out bool ti stderr.Append (rv.Output.StandardError); timed_out = rv.TimedOut; if (rv.TimedOut) - Console.WriteLine ($"Command '{fileName} {StringUtils.FormatArguments (arguments)}' didn't finish in {timeout.Value.TotalMilliseconds} ms, and was killed.", timeout.Value.TotalMinutes); + Console.WriteLine ($"Command '{fileName} {StringUtils.FormatArguments (arguments)}' didn't finish in {timeout!.Value.TotalMilliseconds} ms, and was killed.", timeout!.Value.TotalMinutes); return rv.ExitCode; } - public static int Execute (string fileName, IList arguments, out bool timed_out, string workingDirectory = null, Dictionary environment_variables = null, Action stdout_callback = null, Action stderr_callback = null, TimeSpan? timeout = null) + public static int Execute (string fileName, IList arguments, out bool timed_out, string? workingDirectory = null, Dictionary? environment_variables = null, Action? stdout_callback = null, Action? stderr_callback = null, TimeSpan? timeout = null) { if (stdout_callback is null) stdout_callback = Console.WriteLine; @@ -95,11 +95,11 @@ public static int Execute (string fileName, IList arguments, out bool ti var rv = Execution.RunWithCallbacksAsync (fileName, arguments, workingDirectory: workingDirectory, environment: environment_variables, standardOutput: stdout_callback, standardError: stderr_callback, timeout: timeout).Result; timed_out = rv.TimedOut; if (rv.TimedOut) - Console.WriteLine ($"Command '{fileName} {StringUtils.FormatArguments (arguments)}' didn't finish in {timeout.Value.TotalMilliseconds} ms, and was killed.", timeout.Value.TotalMinutes); + Console.WriteLine ($"Command '{fileName} {StringUtils.FormatArguments (arguments)}' didn't finish in {timeout!.Value.TotalMilliseconds} ms, and was killed.", timeout!.Value.TotalMinutes); return rv.ExitCode; } - public static int Execute (string fileName, IList arguments, out string output, TimeSpan? timeout = null) + public static int Execute (string fileName, IList arguments, out string? output, TimeSpan? timeout = null) { var sb = new StringBuilder (); var rv = Execute (fileName, arguments, timed_out: out var _, stdout: sb, stderr: sb, timeout: timeout); @@ -107,12 +107,12 @@ public static int Execute (string fileName, IList arguments, out string return rv; } - public static int Execute (string fileName, IList arguments, Dictionary environmentVariables, StringBuilder stdout, StringBuilder stderr, TimeSpan? timeout = null, string workingDirectory = null) + public static int Execute (string fileName, IList arguments, Dictionary? environmentVariables, StringBuilder? stdout, StringBuilder? stderr, TimeSpan? timeout = null, string? workingDirectory = null) { return Execute (fileName, arguments, timed_out: out var _, workingDirectory: workingDirectory, environment_variables: environmentVariables, stdout: stdout, stderr: stderr, timeout: timeout); } - public static string Execute (string fileName, IList arguments, bool throwOnError = true, Dictionary environmentVariables = null, bool hide_output = false, TimeSpan? timeout = null) + public static string Execute (string fileName, IList arguments, bool throwOnError = true, Dictionary? environmentVariables = null, bool hide_output = false, TimeSpan? timeout = null) { var rv = Execution.RunAsync (fileName, arguments, environment: environmentVariables, timeout: timeout).Result; var output = rv.Output.MergedOutput; diff --git a/tests/common/GlobalUsings.cs b/tests/common/GlobalUsings.cs index 9f7637a0e6f9..bb2e71447ba4 100644 --- a/tests/common/GlobalUsings.cs +++ b/tests/common/GlobalUsings.cs @@ -3,6 +3,7 @@ global using System; global using System.Collections.Generic; +global using System.Diagnostics.CodeAnalysis; global using System.Runtime.InteropServices; global using CoreFoundation; diff --git a/tests/common/MonoTouch.Dialog/shared.csproj b/tests/common/MonoTouch.Dialog/shared.csproj index dbb2c9e2083c..e44199d2ca28 100644 --- a/tests/common/MonoTouch.Dialog/shared.csproj +++ b/tests/common/MonoTouch.Dialog/shared.csproj @@ -11,9 +11,6 @@ $(NoWarn);CA1422 - - enable - Nullable diff --git a/tests/common/PlatformInfo.cs b/tests/common/PlatformInfo.cs index f88e7abd8b46..b89dd2810312 100644 --- a/tests/common/PlatformInfo.cs +++ b/tests/common/PlatformInfo.cs @@ -18,14 +18,13 @@ using Xamarin.Utils; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Xamarin.Tests { public sealed class PlatformInfo { static PlatformInfo GetHostPlatformInfo () { - string name; + string? name; string version; #if __MACCATALYST__ name = "MacCatalyst"; @@ -35,8 +34,8 @@ static PlatformInfo GetHostPlatformInfo () version = UIDevice.CurrentDevice.SystemVersion; #elif MONOMAC || __MACOS__ using (var plist = NSDictionary.FromFile ("/System/Library/CoreServices/SystemVersion.plist")) { - name = (NSString) plist ["ProductName"]; - version = (NSString) plist ["ProductVersion"]; + name = (NSString) plist ["ProductName"]!; + version = (NSString) plist ["ProductVersion"]!; } #else #error Unknown platform @@ -58,21 +57,21 @@ static PlatformInfo GetHostPlatformInfo () else throw new FormatException ($"Unknown product name: {name}"); - platformInfo.Version = Version.Parse (version); + platformInfo.Version = Version.Parse (version)!; return platformInfo; } #if __MACCATALYST__ - static string _iOSSupportVersion; + static string? _iOSSupportVersion; internal static string iOSSupportVersion { get { if (_iOSSupportVersion is null) { // This is how Apple does it: https://github.com/llvm/llvm-project/blob/62ec4ac90738a5f2d209ed28c822223e58aaaeb7/lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm#L100-L105 using var dict = NSMutableDictionary.FromFile ("/System/Library/CoreServices/SystemVersion.plist"); using var str = (NSString) "iOSSupportVersion"; - using var obj = dict.ObjectForKey (str); - _iOSSupportVersion = obj.ToString (); + using var obj = dict.ObjectForKey (str)!; + _iOSSupportVersion = obj.ToString ()!; } return _iOSSupportVersion; } @@ -82,7 +81,7 @@ internal static string iOSSupportVersion { public static readonly PlatformInfo Host = GetHostPlatformInfo (); public ApplePlatform Name { get; private set; } - public Version Version { get; private set; } + public Version? Version { get; private set; } public bool IsMac => Name == ApplePlatform.MacOSX; public bool IsIos => Name == ApplePlatform.iOS; @@ -98,6 +97,54 @@ public static bool IsAvailableOnHostPlatform (this ICustomAttributeProvider attr return attributeProvider.IsAvailable (PlatformInfo.Host); } + public static bool IsAvailableInSimulator (this ICustomAttributeProvider attributeProvider) + { + if (!TestRuntime.IsSimulator) + return true; + + var customAttributes = attributeProvider.GetCustomAttributes (true); + + string platformPrefix; + switch (PlatformInfo.Host.Name) { + case ApplePlatform.iOS: + platformPrefix = "ios"; + break; + case ApplePlatform.TVOS: + platformPrefix = "tvos"; + break; + default: + return true; + } + + // Check for [UnsupportedSimulator] attributes + foreach (var attr in customAttributes.OfType ()) { + if (attr.PlatformName.StartsWith (platformPrefix, StringComparison.OrdinalIgnoreCase)) + return false; + } + + // Check for [SupportedSimulator] attributes + var supportedAttrs = customAttributes.OfType () + .Where (a => a.PlatformName.StartsWith (platformPrefix, StringComparison.OrdinalIgnoreCase)) + .ToArray (); + + // If no SupportedSimulator attributes for the current platform, assume available + if (supportedAttrs.Length == 0) + return true; + + // There's a SupportedSimulator attribute for the current platform - check version + foreach (var attr in supportedAttrs) { + var versionString = attr.PlatformName.AsSpan (platformPrefix.Length); + if (versionString.IsEmpty) + return true; // supported, no version constraint + if (!Version.TryParse (versionString, out var version)) + throw new InvalidOperationException ($"Invalid version string in SupportedSimulator attribute: '{attr.PlatformName}'"); + if (PlatformInfo.Host.Version >= version) + return true; + } + + return false; + } + [UnconditionalSuppressMessage ("Trimming", "IL2045", Justification = "Some of the attributes this method uses may have been linked away, so things might not work. It actually works though, so unless something changes, we're going to assume it's trimmer-compatible.")] public static bool IsAvailable (this ICustomAttributeProvider attributeProvider, PlatformInfo targetPlatform) { @@ -117,7 +164,7 @@ public static bool IsAvailableOnHostPlatform (this IEnumerable ParseAttributes (IEnumerable attributes) + static IEnumerable<(OSPlatformAttribute Attribute, ApplePlatform Platform, Version? Version)> ParseAttributes (IEnumerable attributes) { foreach (var attr in attributes) { if (!attr.TryParse (out ApplePlatform? platform, out var version)) @@ -153,7 +200,7 @@ public static bool IsAvailable (this IEnumerable attributes } [UnconditionalSuppressMessage ("Trimming", "IL2045", Justification = "Some of the attributes this method uses may have been linked away, so things might not work. It actually works though, so unless something changes, we're going to assume it's trimmer-compatible.")] - public static bool? IsAvailable (IEnumerable<(OSPlatformAttribute Attribute, ApplePlatform Platform, Version Version)> attributes, PlatformInfo targetPlatform, ApplePlatform attributePlatform) + public static bool? IsAvailable (IEnumerable<(OSPlatformAttribute Attribute, ApplePlatform Platform, Version? Version)> attributes, PlatformInfo targetPlatform, ApplePlatform attributePlatform) { // First we check for any unsupported attributes, and only once we know that there aren't any unsupported // attributes, we check for supported attributes. Otherwise we might determine that an API is available diff --git a/tests/common/ProductTests.cs b/tests/common/ProductTests.cs index cd00328e78d4..8d4a4d3d1063 100644 --- a/tests/common/ProductTests.cs +++ b/tests/common/ProductTests.cs @@ -18,7 +18,7 @@ public void MonoVersion () // Verify that the mono version is in the Versions.plist, and that it's a parsable version number. var settings = new XmlReaderSettings () { XmlResolver = null, - DtdProcessing = DtdProcessing.Parse + DtdProcessing = DtdProcessing.Ignore }; var plist = Path.Combine (Configuration.SdkRoot, "Versions.plist"); @@ -71,7 +71,7 @@ public void MinOSVersion (Profile profile, MachO.LoadCommands load_command, Mach Version lc_min_version; var mincmd = lc as MinCommand; if (mincmd is not null) { - Assert.AreEqual (load_command, mincmd.Command, "Unexpected min load command"); + Assert.That (mincmd.Command, Is.EqualTo (load_command), "Unexpected min load command"); lc_min_version = mincmd.Version; } else { // starting from iOS SDK 12 the LC_BUILD_VERSION is used instead @@ -159,7 +159,7 @@ public void MinOSVersion (Profile profile, MachO.LoadCommands load_command, Mach failed.Add ($"No minOS version found in {machoFile}."); } } - CollectionAssert.IsEmpty (failed, "Failures"); + Assert.That (failed, Is.Empty, "Failures"); } } diff --git a/tests/common/TestProjects/ComplexAssembly/ComplexAssembly.csproj b/tests/common/TestProjects/ComplexAssembly/ComplexAssembly.csproj index 7ae6339505aa..278df341f401 100644 --- a/tests/common/TestProjects/ComplexAssembly/ComplexAssembly.csproj +++ b/tests/common/TestProjects/ComplexAssembly/ComplexAssembly.csproj @@ -2,7 +2,6 @@ net$(BundledNETCoreAppTargetFrameworkVersion) - latest Library diff --git a/tests/common/TestProjects/MyActionExtension/MyActionExtension.csproj b/tests/common/TestProjects/MyActionExtension/MyActionExtension.csproj index 2aa268c86be3..c83e49e39d8d 100644 --- a/tests/common/TestProjects/MyActionExtension/MyActionExtension.csproj +++ b/tests/common/TestProjects/MyActionExtension/MyActionExtension.csproj @@ -9,7 +9,6 @@ MyActionExtension Resources MyActionExtension - latest true diff --git a/tests/common/TestProjects/MyActionExtension/MyActionExtension.dotnet.csproj b/tests/common/TestProjects/MyActionExtension/MyActionExtension.dotnet.csproj index 32ff962a0897..1ac1c4b5a976 100644 --- a/tests/common/TestProjects/MyActionExtension/MyActionExtension.dotnet.csproj +++ b/tests/common/TestProjects/MyActionExtension/MyActionExtension.dotnet.csproj @@ -5,7 +5,6 @@ iossimulator-x64 true $(CustomBeforeMicrosoftCommonTargets);$(MSBuildThisFileDirectory)../../SupportedOSPlatformVersions.targets - latest diff --git a/tests/common/TestProjects/MyDocumentPickerExtension/MyDocumentPickerExtension.csproj b/tests/common/TestProjects/MyDocumentPickerExtension/MyDocumentPickerExtension.csproj index c7f6c7eb738e..bee7378c9d21 100644 --- a/tests/common/TestProjects/MyDocumentPickerExtension/MyDocumentPickerExtension.csproj +++ b/tests/common/TestProjects/MyDocumentPickerExtension/MyDocumentPickerExtension.csproj @@ -9,7 +9,6 @@ MyDocumentPickerExtension Resources MyDocumentPickerExtension - latest true diff --git a/tests/common/TestProjects/MyDocumentPickerExtension/MyDocumentPickerExtension.dotnet.csproj b/tests/common/TestProjects/MyDocumentPickerExtension/MyDocumentPickerExtension.dotnet.csproj index 32ff962a0897..1ac1c4b5a976 100644 --- a/tests/common/TestProjects/MyDocumentPickerExtension/MyDocumentPickerExtension.dotnet.csproj +++ b/tests/common/TestProjects/MyDocumentPickerExtension/MyDocumentPickerExtension.dotnet.csproj @@ -5,7 +5,6 @@ iossimulator-x64 true $(CustomBeforeMicrosoftCommonTargets);$(MSBuildThisFileDirectory)../../SupportedOSPlatformVersions.targets - latest diff --git a/tests/common/TestProjects/MyIBToolLinkTest/MyIBToolLinkTest.csproj b/tests/common/TestProjects/MyIBToolLinkTest/MyIBToolLinkTest.csproj index f89438905d31..4c615e91248c 100644 --- a/tests/common/TestProjects/MyIBToolLinkTest/MyIBToolLinkTest.csproj +++ b/tests/common/TestProjects/MyIBToolLinkTest/MyIBToolLinkTest.csproj @@ -9,7 +9,6 @@ MyIBToolLinkTest MyIBToolLinkTest Resources - latest true diff --git a/tests/common/TestProjects/MyIBToolLinkTest/MyIBToolLinkTest.dotnet.csproj b/tests/common/TestProjects/MyIBToolLinkTest/MyIBToolLinkTest.dotnet.csproj index 1c42a286d69d..3388bc17e7dc 100644 --- a/tests/common/TestProjects/MyIBToolLinkTest/MyIBToolLinkTest.dotnet.csproj +++ b/tests/common/TestProjects/MyIBToolLinkTest/MyIBToolLinkTest.dotnet.csproj @@ -5,7 +5,6 @@ Exe iossimulator-x64 $(CustomBeforeMicrosoftCommonTargets);$(MSBuildThisFileDirectory)../../SupportedOSPlatformVersions.targets - latest diff --git a/tests/common/TestProjects/MyKeyboardExtension/MyKeyboardExtension.csproj b/tests/common/TestProjects/MyKeyboardExtension/MyKeyboardExtension.csproj index ee8400c43c3c..5d6826b0ecaf 100644 --- a/tests/common/TestProjects/MyKeyboardExtension/MyKeyboardExtension.csproj +++ b/tests/common/TestProjects/MyKeyboardExtension/MyKeyboardExtension.csproj @@ -9,7 +9,6 @@ MyKeyboardExtension Resources MyKeyboardExtension - latest true diff --git a/tests/common/TestProjects/MyKeyboardExtension/MyKeyboardExtension.dotnet.csproj b/tests/common/TestProjects/MyKeyboardExtension/MyKeyboardExtension.dotnet.csproj index 32ff962a0897..1ac1c4b5a976 100644 --- a/tests/common/TestProjects/MyKeyboardExtension/MyKeyboardExtension.dotnet.csproj +++ b/tests/common/TestProjects/MyKeyboardExtension/MyKeyboardExtension.dotnet.csproj @@ -5,7 +5,6 @@ iossimulator-x64 true $(CustomBeforeMicrosoftCommonTargets);$(MSBuildThisFileDirectory)../../SupportedOSPlatformVersions.targets - latest diff --git a/tests/common/TestProjects/MyPhotoEditingExtension/MyPhotoEditingExtension.csproj b/tests/common/TestProjects/MyPhotoEditingExtension/MyPhotoEditingExtension.csproj index c99cd4a6b527..44399686f9a6 100644 --- a/tests/common/TestProjects/MyPhotoEditingExtension/MyPhotoEditingExtension.csproj +++ b/tests/common/TestProjects/MyPhotoEditingExtension/MyPhotoEditingExtension.csproj @@ -9,7 +9,6 @@ MyPhotoEditingExtension Resources MyPhotoEditingExtension - latest true diff --git a/tests/common/TestProjects/MyPhotoEditingExtension/MyPhotoEditingExtension.dotnet.csproj b/tests/common/TestProjects/MyPhotoEditingExtension/MyPhotoEditingExtension.dotnet.csproj index 32ff962a0897..1ac1c4b5a976 100644 --- a/tests/common/TestProjects/MyPhotoEditingExtension/MyPhotoEditingExtension.dotnet.csproj +++ b/tests/common/TestProjects/MyPhotoEditingExtension/MyPhotoEditingExtension.dotnet.csproj @@ -5,7 +5,6 @@ iossimulator-x64 true $(CustomBeforeMicrosoftCommonTargets);$(MSBuildThisFileDirectory)../../SupportedOSPlatformVersions.targets - latest diff --git a/tests/common/TestProjects/MyShareExtension/MyShareExtension.csproj b/tests/common/TestProjects/MyShareExtension/MyShareExtension.csproj index 8246218191be..e9f195e1c515 100644 --- a/tests/common/TestProjects/MyShareExtension/MyShareExtension.csproj +++ b/tests/common/TestProjects/MyShareExtension/MyShareExtension.csproj @@ -9,7 +9,6 @@ MyShareExtension Resources MyShareExtension - latest true diff --git a/tests/common/TestProjects/MyShareExtension/MyShareExtension.dotnet.csproj b/tests/common/TestProjects/MyShareExtension/MyShareExtension.dotnet.csproj index 32ff962a0897..1ac1c4b5a976 100644 --- a/tests/common/TestProjects/MyShareExtension/MyShareExtension.dotnet.csproj +++ b/tests/common/TestProjects/MyShareExtension/MyShareExtension.dotnet.csproj @@ -5,7 +5,6 @@ iossimulator-x64 true $(CustomBeforeMicrosoftCommonTargets);$(MSBuildThisFileDirectory)../../SupportedOSPlatformVersions.targets - latest diff --git a/tests/common/TestProjects/MyTVApp/MyTVApp.csproj b/tests/common/TestProjects/MyTVApp/MyTVApp.csproj index ffca4a0da55b..f8ff01569afb 100644 --- a/tests/common/TestProjects/MyTVApp/MyTVApp.csproj +++ b/tests/common/TestProjects/MyTVApp/MyTVApp.csproj @@ -11,7 +11,6 @@ MyTVApp Resources MyTVApp - latest true diff --git a/tests/common/TestProjects/MyTVApp/MyTVApp.dotnet.csproj b/tests/common/TestProjects/MyTVApp/MyTVApp.dotnet.csproj index 860f20cc1599..9a9145d6101b 100644 --- a/tests/common/TestProjects/MyTVApp/MyTVApp.dotnet.csproj +++ b/tests/common/TestProjects/MyTVApp/MyTVApp.dotnet.csproj @@ -5,7 +5,6 @@ tvossimulator-x64 Exe $(CustomBeforeMicrosoftCommonTargets);$(MSBuildThisFileDirectory)../../SupportedOSPlatformVersions.targets - latest diff --git a/tests/common/TestProjects/MyTVServicesExtension/MyTVServicesExtension.csproj b/tests/common/TestProjects/MyTVServicesExtension/MyTVServicesExtension.csproj index 3344a305abfe..452be8e6258f 100644 --- a/tests/common/TestProjects/MyTVServicesExtension/MyTVServicesExtension.csproj +++ b/tests/common/TestProjects/MyTVServicesExtension/MyTVServicesExtension.csproj @@ -11,7 +11,6 @@ Resources 8.0.30703 2.0 - latest true diff --git a/tests/common/TestProjects/MyTVServicesExtension/MyTVServicesExtension.dotnet.csproj b/tests/common/TestProjects/MyTVServicesExtension/MyTVServicesExtension.dotnet.csproj index 4c6a3b015169..78785deda223 100644 --- a/tests/common/TestProjects/MyTVServicesExtension/MyTVServicesExtension.dotnet.csproj +++ b/tests/common/TestProjects/MyTVServicesExtension/MyTVServicesExtension.dotnet.csproj @@ -5,7 +5,6 @@ tvossimulator-x64 true $(CustomBeforeMicrosoftCommonTargets);$(MSBuildThisFileDirectory)../../SupportedOSPlatformVersions.targets - latest diff --git a/tests/common/TestProjects/MyTodayExtension/MyTodayExtension.csproj b/tests/common/TestProjects/MyTodayExtension/MyTodayExtension.csproj index 1e13d1b6f145..aef827c7ab64 100644 --- a/tests/common/TestProjects/MyTodayExtension/MyTodayExtension.csproj +++ b/tests/common/TestProjects/MyTodayExtension/MyTodayExtension.csproj @@ -9,7 +9,6 @@ MyTodayExtension Resources MyTodayExtension - latest true diff --git a/tests/common/TestProjects/MyTodayExtension/MyTodayExtension.dotnet.csproj b/tests/common/TestProjects/MyTodayExtension/MyTodayExtension.dotnet.csproj index 32ff962a0897..1ac1c4b5a976 100644 --- a/tests/common/TestProjects/MyTodayExtension/MyTodayExtension.dotnet.csproj +++ b/tests/common/TestProjects/MyTodayExtension/MyTodayExtension.dotnet.csproj @@ -5,7 +5,6 @@ iossimulator-x64 true $(CustomBeforeMicrosoftCommonTargets);$(MSBuildThisFileDirectory)../../SupportedOSPlatformVersions.targets - latest diff --git a/tests/common/TestRuntime.cs b/tests/common/TestRuntime.cs index 97209524c931..296c348ac2cf 100644 --- a/tests/common/TestRuntime.cs +++ b/tests/common/TestRuntime.cs @@ -210,7 +210,7 @@ public static void AssertXcodeVersion (int major, int minor, int build = 0) if (CheckXcodeVersion (major, minor, build)) return; - NUnit.Framework.Assert.Ignore ("Requires the platform version shipped with Xcode {0}.{1}", major, minor); + NUnit.Framework.Assert.Ignore ($"Requires the platform version shipped with Xcode {major}.{minor}"); } public static void AssertDevice (string message = "This test only runs on device.") @@ -1674,6 +1674,11 @@ public static void IgnoreInCIIfTimedOut (Exception ex) IgnoreInCI ($"Ignored due to network error: {wex}"); } } + + var se = FindInner (ex); + if (se is not null && se.SocketErrorCode == System.Net.Sockets.SocketError.TimedOut) { + IgnoreInCI ($"Ignored due to socket timeout: {se.Message}"); + } } public static void IgnoreInCIIfForbidden (Exception ex) @@ -1727,9 +1732,19 @@ public static void IgnoreInCIIfNoNetworkConnection (NSError error) public static void IgnoreInCIIfSshConnectionError (Exception ex) { - var msg = ex.Message; - if (msg.Contains ("The SSL connection could not be established")) { - IgnoreInCI ($"Ignored due to network error: {ex}"); + // Check all exceptions in the chain for TLS/SSL error messages + var current = ex; + while (current is not null) { + var msg = current.Message; + if (msg.Contains ("The SSL connection could not be established") || + msg.Contains ("A TLS error caused the secure connection to fail")) { + IgnoreInCI ($"Ignored due to network error: {ex}"); + } + if (current is NSErrorException nex) { + // CFNetworkErrors.SecureConnectionFailed = -1200 + IgnoreNetworkError (nex.Error, CFNetworkErrors.SecureConnectionFailed); + } + current = current.InnerException; } } @@ -1852,7 +1867,7 @@ public static void AssertNoNonNUnitException (Exception ex, string message) case InconclusiveException: throw new InconclusiveException (ex.Message, ex); case ResultStateException: throw ex; default: - Assert.IsNull (ex, message); + Assert.That (ex, Is.Null, message); break; } } diff --git a/tests/common/Touch.Unit/Touch.Client/Runner/TestResultElement.cs b/tests/common/Touch.Unit/Touch.Client/Runner/TestResultElement.cs index 880741dcc9a2..c9f1ef8af194 100644 --- a/tests/common/Touch.Unit/Touch.Client/Runner/TestResultElement.cs +++ b/tests/common/Touch.Unit/Touch.Client/Runner/TestResultElement.cs @@ -32,7 +32,7 @@ namespace MonoTouch.NUnit.UI { class TestResultElement : StyledMultilineElement { public TestResultElement (TestResult result) : - base (result.Message ?? "Unknown error", result.StackTrace, UITableViewCellStyle.Subtitle) + base (result.Message ?? "Unknown error", result.StackTrace ?? "", UITableViewCellStyle.Subtitle) { } } diff --git a/tests/common/Touch.Unit/Touch.Client/Runner/TouchRunner.cs b/tests/common/Touch.Unit/Touch.Client/Runner/TouchRunner.cs index a2a873e133e8..1c23046fb905 100644 --- a/tests/common/Touch.Unit/Touch.Client/Runner/TouchRunner.cs +++ b/tests/common/Touch.Unit/Touch.Client/Runner/TouchRunner.cs @@ -568,8 +568,8 @@ public virtual void TestFinished (ITestResult r) #endif string? stacktrace = result.StackTrace; - if (!String.IsNullOrEmpty (result.StackTrace)) { - string [] lines = stacktrace.Split (new char [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); + if (!String.IsNullOrEmpty (stacktrace)) { + string [] lines = stacktrace!.Split (new char [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) writer.WriteLine ("\t\t{0}", line); } @@ -689,9 +689,11 @@ public void Run (Test test) var tsr = new TestSuiteResult (suite); foreach (var runner in runners) { - var rv = (TestResult) (find_result (runner.Result) ?? runner.Result); - if (rv is not null) - tsr.AddResult (rv); + var runnerResult = runner.Result is not null ? (find_result (runner.Result) ?? runner.Result) : null; + if (runnerResult is null) + continue; + var rv = (TestResult) runnerResult; + tsr.AddResult (rv); } Result = tsr; #else diff --git a/tests/common/Touch.Unit/Touch.Client/dotnet/shared.csproj b/tests/common/Touch.Unit/Touch.Client/dotnet/shared.csproj index d2d40080acff..97edb9f41e74 100644 --- a/tests/common/Touch.Unit/Touch.Client/dotnet/shared.csproj +++ b/tests/common/Touch.Unit/Touch.Client/dotnet/shared.csproj @@ -1,16 +1,12 @@ NUNITLITE_NUGET - latest Touch.Client $(NoWarn);CA1416 $(NoWarn);CA1422 - - enable - Nullable @@ -59,10 +55,10 @@ - 3.12.0 + $(NUnitLitePackageVersion) - 3.6.0 + $(NUnitV2ResultWriterPackageVersion) 6.12.0.148 diff --git a/tests/common/mac/MacMain.fs b/tests/common/mac/MacMain.fs index 0c1869fb3248..20e2c057169f 100644 --- a/tests/common/mac/MacMain.fs +++ b/tests/common/mac/MacMain.fs @@ -11,8 +11,11 @@ module PInvokes = extern void _exit (int exit_code) type MainClass = - static member ThreadMonitor(obj : System.Object) = - let exit_code = obj :?> int + static member ThreadMonitor (state : obj | null) = + let exit_code = + match state with + | :? int as value -> value + | _ -> failwith "Expected an exit code." Thread.Sleep (3000) Console.WriteLine ($"The process didn't exit within 3s of returning from Main. Assuming something is deadlocked, and will now exit immediately and forcefully (with exit code {exit_code}).") Console.Out.Flush () diff --git a/tests/common/mac/ProjectTestHelpers.cs b/tests/common/mac/ProjectTestHelpers.cs index b6e1ce1c1920..1fd30f43685b 100644 --- a/tests/common/mac/ProjectTestHelpers.cs +++ b/tests/common/mac/ProjectTestHelpers.cs @@ -247,11 +247,11 @@ static string ProjectTextReplacement (UnifiedTestConfig config, string text) public static string RunEXEAndVerifyGUID (string tmpDir, Guid guid, string path) { // Assert that the program actually runs and returns our guid - Assert.IsTrue (File.Exists (path), string.Format ("{0} did not generate an exe?", path)); + Assert.That (File.Exists (path), Is.True, string.Format ("{0} did not generate an exe?", path)); string output = RunAndAssert (path, Array.Empty (), "Run"); string guidPath = Path.Combine (tmpDir, guid.ToString ()); - Assert.IsTrue (File.Exists (guidPath), "Generated program did not create expected guid file: " + output); + Assert.That (File.Exists (guidPath), Is.True, "Generated program did not create expected guid file: " + output); // Let's delete the guid file so re-runs inside same tests are accurate File.Delete (guidPath); @@ -442,7 +442,7 @@ public static string FindSourceDirectory () public static void CopyDirectory (string src, string target) { - Assert.AreEqual (0, ExecutionHelper.Execute ("/bin/cp", new [] { "-r", src, target })); + Assert.That (ExecutionHelper.Execute ("/bin/cp", new [] { "-r", src, target }), Is.EqualTo (0)); } public static string CopyFileWithSubstitutions (string src, string target, Func replacementAction) diff --git a/tests/common/shared-dotnet.csproj b/tests/common/shared-dotnet.csproj index e3ea873d0c75..27ee7da59ae3 100644 --- a/tests/common/shared-dotnet.csproj +++ b/tests/common/shared-dotnet.csproj @@ -54,9 +54,6 @@ true - - latest - CA1416;$(NoWarn) @@ -83,6 +80,11 @@ $(DefineConstants);NATIVEAOT false + + true + false @@ -104,13 +106,17 @@ true + + true + + - + @@ -129,6 +135,11 @@ $(DefineConstants);NATIVEAOT false + + true + false + true + <_IsPublishing>true + full + + strict + $(DefineConstants);STATIC_NATIVE_SYMBOL_LOOKUP + + strict + managed-static + + <_TestVariationApplied>true + + partial <_TestVariationApplied>true @@ -147,6 +167,29 @@ <_TestVariationApplied>true + + compatibility + <_TestVariationApplied>true + + + + strict + <_TestVariationApplied>true + + $(DefineConstants);STATIC_NATIVE_SYMBOL_LOOKUP + + + + compatibility + <_TestVariationApplied>true + + + + strict + managed-static + <_TestVariationApplied>true + + <_InvalidTestVariations Include="$(TestVariation.Split('|'))" Exclude="@(TestVariations)" /> diff --git a/tests/dotnet/AppWithComposerIcon/AppDelegate.cs b/tests/dotnet/AppWithComposerIcon/AppDelegate.cs new file mode 100644 index 000000000000..13cf28d17265 --- /dev/null +++ b/tests/dotnet/AppWithComposerIcon/AppDelegate.cs @@ -0,0 +1,35 @@ +using System; +using Foundation; + +#if !__MACOS__ +using UIKit; +#endif + +#nullable enable + +namespace AppWithComposerIcon { +#if !(__MACCATALYST__ || __MACOS__) + public class AppDelegate : UIApplicationDelegate { + public override bool FinishedLaunching (UIApplication app, NSDictionary? options) + { + return true; + } + } +#endif + + public class Program { + static int Main (string [] args) + { +#if __MACCATALYST__ || __MACOS__ +GC.KeepAlive (typeof (NSObject)); // prevent linking away the platform assembly + +Console.WriteLine (Environment.GetEnvironmentVariable ("MAGIC_WORD")); + +return args.Length; +#else + UIApplication.Main (args, null, typeof (AppDelegate)); + return 0; +#endif + } + } +} diff --git a/tests/dotnet/CentralPackageVersionsApp/MacCatalyst/CentralPackageVersionsApp.csproj b/tests/dotnet/AppWithComposerIcon/MacCatalyst/AppWithComposerIcon.csproj similarity index 78% rename from tests/dotnet/CentralPackageVersionsApp/MacCatalyst/CentralPackageVersionsApp.csproj rename to tests/dotnet/AppWithComposerIcon/MacCatalyst/AppWithComposerIcon.csproj index 9146ec230693..6b0e2c773180 100644 --- a/tests/dotnet/CentralPackageVersionsApp/MacCatalyst/CentralPackageVersionsApp.csproj +++ b/tests/dotnet/AppWithComposerIcon/MacCatalyst/AppWithComposerIcon.csproj @@ -1,6 +1,5 @@ - net$(BundledNETCoreAppTargetFrameworkVersion)-maccatalyst diff --git a/tests/dotnet/CentralPackageVersionsApp/MacCatalyst/Makefile b/tests/dotnet/AppWithComposerIcon/MacCatalyst/Makefile similarity index 100% rename from tests/dotnet/CentralPackageVersionsApp/MacCatalyst/Makefile rename to tests/dotnet/AppWithComposerIcon/MacCatalyst/Makefile diff --git a/tests/dotnet/AppWithComposerIcon/MacCatalyst/Resources/AppIcon.icon/Assets/back.png b/tests/dotnet/AppWithComposerIcon/MacCatalyst/Resources/AppIcon.icon/Assets/back.png new file mode 100644 index 000000000000..00c6bc6118f0 Binary files /dev/null and b/tests/dotnet/AppWithComposerIcon/MacCatalyst/Resources/AppIcon.icon/Assets/back.png differ diff --git a/tests/dotnet/AppWithComposerIcon/MacCatalyst/Resources/AppIcon.icon/Assets/front.png b/tests/dotnet/AppWithComposerIcon/MacCatalyst/Resources/AppIcon.icon/Assets/front.png new file mode 100644 index 000000000000..6dc4283df45a Binary files /dev/null and b/tests/dotnet/AppWithComposerIcon/MacCatalyst/Resources/AppIcon.icon/Assets/front.png differ diff --git a/tests/dotnet/AppWithComposerIcon/MacCatalyst/Resources/AppIcon.icon/icon.json b/tests/dotnet/AppWithComposerIcon/MacCatalyst/Resources/AppIcon.icon/icon.json new file mode 100644 index 000000000000..9cb9eee03bd1 --- /dev/null +++ b/tests/dotnet/AppWithComposerIcon/MacCatalyst/Resources/AppIcon.icon/icon.json @@ -0,0 +1,16 @@ +{ + "groups" : [ + { + "layers" : [ + { + "image-name" : "back.png", + "name" : "back" + }, + { + "image-name" : "front.png", + "name" : "front" + } + ] + } + ] +} diff --git a/tests/dotnet/CentralPackageVersionsApp/iOS/CentralPackageVersionsApp.csproj b/tests/dotnet/AppWithComposerIcon/iOS/AppWithComposerIcon.csproj similarity index 77% rename from tests/dotnet/CentralPackageVersionsApp/iOS/CentralPackageVersionsApp.csproj rename to tests/dotnet/AppWithComposerIcon/iOS/AppWithComposerIcon.csproj index 1ce755af9e0a..86d408734aa8 100644 --- a/tests/dotnet/CentralPackageVersionsApp/iOS/CentralPackageVersionsApp.csproj +++ b/tests/dotnet/AppWithComposerIcon/iOS/AppWithComposerIcon.csproj @@ -1,6 +1,5 @@ - net$(BundledNETCoreAppTargetFrameworkVersion)-ios diff --git a/tests/dotnet/CentralPackageVersionsApp/iOS/Makefile b/tests/dotnet/AppWithComposerIcon/iOS/Makefile similarity index 100% rename from tests/dotnet/CentralPackageVersionsApp/iOS/Makefile rename to tests/dotnet/AppWithComposerIcon/iOS/Makefile diff --git a/tests/dotnet/AppWithComposerIcon/iOS/Resources/AppIcon.icon/Assets/back.png b/tests/dotnet/AppWithComposerIcon/iOS/Resources/AppIcon.icon/Assets/back.png new file mode 100644 index 000000000000..00c6bc6118f0 Binary files /dev/null and b/tests/dotnet/AppWithComposerIcon/iOS/Resources/AppIcon.icon/Assets/back.png differ diff --git a/tests/dotnet/AppWithComposerIcon/iOS/Resources/AppIcon.icon/Assets/front.png b/tests/dotnet/AppWithComposerIcon/iOS/Resources/AppIcon.icon/Assets/front.png new file mode 100644 index 000000000000..6dc4283df45a Binary files /dev/null and b/tests/dotnet/AppWithComposerIcon/iOS/Resources/AppIcon.icon/Assets/front.png differ diff --git a/tests/dotnet/AppWithComposerIcon/iOS/Resources/AppIcon.icon/icon.json b/tests/dotnet/AppWithComposerIcon/iOS/Resources/AppIcon.icon/icon.json new file mode 100644 index 000000000000..9cb9eee03bd1 --- /dev/null +++ b/tests/dotnet/AppWithComposerIcon/iOS/Resources/AppIcon.icon/icon.json @@ -0,0 +1,16 @@ +{ + "groups" : [ + { + "layers" : [ + { + "image-name" : "back.png", + "name" : "back" + }, + { + "image-name" : "front.png", + "name" : "front" + } + ] + } + ] +} diff --git a/tests/dotnet/CentralPackageVersionsApp/macOS/CentralPackageVersionsApp.csproj b/tests/dotnet/AppWithComposerIcon/macOS/AppWithComposerIcon.csproj similarity index 77% rename from tests/dotnet/CentralPackageVersionsApp/macOS/CentralPackageVersionsApp.csproj rename to tests/dotnet/AppWithComposerIcon/macOS/AppWithComposerIcon.csproj index 391feb6d1b70..a77287b9ba00 100644 --- a/tests/dotnet/CentralPackageVersionsApp/macOS/CentralPackageVersionsApp.csproj +++ b/tests/dotnet/AppWithComposerIcon/macOS/AppWithComposerIcon.csproj @@ -1,6 +1,5 @@ - net$(BundledNETCoreAppTargetFrameworkVersion)-macos diff --git a/tests/dotnet/CentralPackageVersionsApp/macOS/Makefile b/tests/dotnet/AppWithComposerIcon/macOS/Makefile similarity index 100% rename from tests/dotnet/CentralPackageVersionsApp/macOS/Makefile rename to tests/dotnet/AppWithComposerIcon/macOS/Makefile diff --git a/tests/dotnet/AppWithComposerIcon/macOS/Resources/AppIcon.icon/Assets/back.png b/tests/dotnet/AppWithComposerIcon/macOS/Resources/AppIcon.icon/Assets/back.png new file mode 100644 index 000000000000..00c6bc6118f0 Binary files /dev/null and b/tests/dotnet/AppWithComposerIcon/macOS/Resources/AppIcon.icon/Assets/back.png differ diff --git a/tests/dotnet/AppWithComposerIcon/macOS/Resources/AppIcon.icon/Assets/front.png b/tests/dotnet/AppWithComposerIcon/macOS/Resources/AppIcon.icon/Assets/front.png new file mode 100644 index 000000000000..6dc4283df45a Binary files /dev/null and b/tests/dotnet/AppWithComposerIcon/macOS/Resources/AppIcon.icon/Assets/front.png differ diff --git a/tests/dotnet/AppWithComposerIcon/macOS/Resources/AppIcon.icon/icon.json b/tests/dotnet/AppWithComposerIcon/macOS/Resources/AppIcon.icon/icon.json new file mode 100644 index 000000000000..9cb9eee03bd1 --- /dev/null +++ b/tests/dotnet/AppWithComposerIcon/macOS/Resources/AppIcon.icon/icon.json @@ -0,0 +1,16 @@ +{ + "groups" : [ + { + "layers" : [ + { + "image-name" : "back.png", + "name" : "back" + }, + { + "image-name" : "front.png", + "name" : "front" + } + ] + } + ] +} diff --git a/tests/dotnet/AppWithComposerIcon/shared.csproj b/tests/dotnet/AppWithComposerIcon/shared.csproj new file mode 100644 index 000000000000..702960b9dd8e --- /dev/null +++ b/tests/dotnet/AppWithComposerIcon/shared.csproj @@ -0,0 +1,23 @@ + + + + Exe + + AppWithComposerIcon + com.xamarin.appwithcomposericon + + true + + + + + + AppIcon + + + + + + + + diff --git a/tests/dotnet/CentralPackageVersionsApp/shared.mk b/tests/dotnet/AppWithComposerIcon/shared.mk similarity index 67% rename from tests/dotnet/CentralPackageVersionsApp/shared.mk rename to tests/dotnet/AppWithComposerIcon/shared.mk index f555cad4e805..de0244100278 100644 --- a/tests/dotnet/CentralPackageVersionsApp/shared.mk +++ b/tests/dotnet/AppWithComposerIcon/shared.mk @@ -1,2 +1,3 @@ TOP=../../../.. +TESTNAME=AppWithComposerIcon include $(TOP)/tests/common/shared-dotnet.mk diff --git a/tests/dotnet/CentralPackageVersionsApp/tvOS/CentralPackageVersionsApp.csproj b/tests/dotnet/AppWithComposerIcon/tvOS/AppWithComposerIcon.csproj similarity index 77% rename from tests/dotnet/CentralPackageVersionsApp/tvOS/CentralPackageVersionsApp.csproj rename to tests/dotnet/AppWithComposerIcon/tvOS/AppWithComposerIcon.csproj index a441004a08a5..bd487ddcd88d 100644 --- a/tests/dotnet/CentralPackageVersionsApp/tvOS/CentralPackageVersionsApp.csproj +++ b/tests/dotnet/AppWithComposerIcon/tvOS/AppWithComposerIcon.csproj @@ -1,6 +1,5 @@ - net$(BundledNETCoreAppTargetFrameworkVersion)-tvos diff --git a/tests/dotnet/CentralPackageVersionsApp/tvOS/Makefile b/tests/dotnet/AppWithComposerIcon/tvOS/Makefile similarity index 100% rename from tests/dotnet/CentralPackageVersionsApp/tvOS/Makefile rename to tests/dotnet/AppWithComposerIcon/tvOS/Makefile diff --git a/tests/dotnet/AppWithComposerIcon/tvOS/Resources/AppIcon.icon/Assets/back.png b/tests/dotnet/AppWithComposerIcon/tvOS/Resources/AppIcon.icon/Assets/back.png new file mode 100644 index 000000000000..00c6bc6118f0 Binary files /dev/null and b/tests/dotnet/AppWithComposerIcon/tvOS/Resources/AppIcon.icon/Assets/back.png differ diff --git a/tests/dotnet/AppWithComposerIcon/tvOS/Resources/AppIcon.icon/Assets/front.png b/tests/dotnet/AppWithComposerIcon/tvOS/Resources/AppIcon.icon/Assets/front.png new file mode 100644 index 000000000000..6dc4283df45a Binary files /dev/null and b/tests/dotnet/AppWithComposerIcon/tvOS/Resources/AppIcon.icon/Assets/front.png differ diff --git a/tests/dotnet/AppWithComposerIcon/tvOS/Resources/AppIcon.icon/icon.json b/tests/dotnet/AppWithComposerIcon/tvOS/Resources/AppIcon.icon/icon.json new file mode 100644 index 000000000000..9cb9eee03bd1 --- /dev/null +++ b/tests/dotnet/AppWithComposerIcon/tvOS/Resources/AppIcon.icon/icon.json @@ -0,0 +1,16 @@ +{ + "groups" : [ + { + "layers" : [ + { + "image-name" : "back.png", + "name" : "back" + }, + { + "image-name" : "front.png", + "name" : "front" + } + ] + } + ] +} diff --git a/tests/dotnet/AppWithXCAssets/AppDelegate.cs b/tests/dotnet/AppWithXCAssets/AppDelegate.cs index a6edee7af51c..9dd9f6befa6c 100644 --- a/tests/dotnet/AppWithXCAssets/AppDelegate.cs +++ b/tests/dotnet/AppWithXCAssets/AppDelegate.cs @@ -19,9 +19,11 @@ public class AppDelegate : UIApplicationDelegate { UIColor blue = UIColor.FromRGB (31, 174, 206); UIColor green = UIColor.FromRGB (119, 187, 65); - public override bool FinishedLaunching (UIApplication app, NSDictionary options) + public override bool FinishedLaunching (UIApplication app, NSDictionary? options) { +#pragma warning disable CA1422 // Validate platform compatibility window = new UIWindow (UIScreen.MainScreen.Bounds); +#pragma warning restore CA1422 var dvc = new UIViewController (); var bounds = window.Bounds; diff --git a/tests/dotnet/BundleStructure/shared.csproj b/tests/dotnet/BundleStructure/shared.csproj index 2f8ad66ed705..e94d15aacf61 100644 --- a/tests/dotnet/BundleStructure/shared.csproj +++ b/tests/dotnet/BundleStructure/shared.csproj @@ -162,7 +162,7 @@ - + @@ -177,7 +177,7 @@ - + diff --git a/tests/dotnet/CentralPackageVersionsApp/Makefile b/tests/dotnet/CentralPackageVersionsApp/Makefile deleted file mode 100644 index 6affa45ff122..000000000000 --- a/tests/dotnet/CentralPackageVersionsApp/Makefile +++ /dev/null @@ -1,2 +0,0 @@ -TOP=../../.. -include $(TOP)/tests/common/shared-dotnet-test.mk diff --git a/tests/dotnet/CentralPackageVersionsApp/Packages.props b/tests/dotnet/CentralPackageVersionsApp/Packages.props deleted file mode 100644 index 8423b42e36a1..000000000000 --- a/tests/dotnet/CentralPackageVersionsApp/Packages.props +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/tests/dotnet/CentralPackageVersionsApp/README.md b/tests/dotnet/CentralPackageVersionsApp/README.md deleted file mode 100644 index 0f3d32a3be18..000000000000 --- a/tests/dotnet/CentralPackageVersionsApp/README.md +++ /dev/null @@ -1 +0,0 @@ -This test can be removed in .NET 7. diff --git a/tests/dotnet/CentralPackageVersionsApp/shared.csproj b/tests/dotnet/CentralPackageVersionsApp/shared.csproj deleted file mode 100644 index 4ec57f3f7a0e..000000000000 --- a/tests/dotnet/CentralPackageVersionsApp/shared.csproj +++ /dev/null @@ -1,25 +0,0 @@ - - - - - Exe - - com.xamarin.centralpackageversionsapp - true - true - - - - - - - - - - $(MSBuildThisFileDirectory)Packages.props - - - - - - diff --git a/tests/dotnet/CentralPackageVersionsApp/AppDelegate.cs b/tests/dotnet/ContentWithPublishFolderType/AppDelegate.cs similarity index 53% rename from tests/dotnet/CentralPackageVersionsApp/AppDelegate.cs rename to tests/dotnet/ContentWithPublishFolderType/AppDelegate.cs index db627351190b..b99d6adb454a 100644 --- a/tests/dotnet/CentralPackageVersionsApp/AppDelegate.cs +++ b/tests/dotnet/ContentWithPublishFolderType/AppDelegate.cs @@ -1,17 +1,12 @@ using System; -using System.Runtime.InteropServices; - using Foundation; -namespace MySimpleApp { +namespace ContentWithPublishFolderType { public class Program { static int Main (string [] args) { GC.KeepAlive (typeof (NSObject)); // prevent linking away the platform assembly - - Console.WriteLine (Environment.GetEnvironmentVariable ("MAGIC_WORD")); - - return args.Length; + return 0; } } } diff --git a/tests/dotnet/ContentWithPublishFolderType/helper/.gitignore b/tests/dotnet/ContentWithPublishFolderType/helper/.gitignore new file mode 100644 index 000000000000..9a16fc334d87 --- /dev/null +++ b/tests/dotnet/ContentWithPublishFolderType/helper/.gitignore @@ -0,0 +1,2 @@ +# Override root .gitignore to allow test DLL files +!*.dll diff --git a/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/.xamarin/osx-arm64/HeartBeatHandlerMac.dll b/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/.xamarin/osx-arm64/HeartBeatHandlerMac.dll new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.CSharp.dll b/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.CSharp.dll new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.VisualBasic.dll b/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.VisualBasic.dll new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.macOS.dll b/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.macOS.dll new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/AsyncIO.dll b/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/AsyncIO.dll new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/HeartbeatHandlerLib.dll b/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/HeartbeatHandlerLib.dll new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/System.ServiceModel.Security.dll b/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/System.ServiceModel.Security.dll new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/libclrgc.dylib b/tests/dotnet/ContentWithPublishFolderType/helper/SubApp.app/Contents/MonoBundle/libclrgc.dylib new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/dotnet/ContentWithPublishFolderType/macOS/ContentWithPublishFolderType.csproj b/tests/dotnet/ContentWithPublishFolderType/macOS/ContentWithPublishFolderType.csproj new file mode 100644 index 000000000000..f72ebb8816e7 --- /dev/null +++ b/tests/dotnet/ContentWithPublishFolderType/macOS/ContentWithPublishFolderType.csproj @@ -0,0 +1,22 @@ + + + + net$(BundledNETCoreAppTargetFrameworkVersion)-macos + Exe + ContentWithPublishFolderType + com.xamarin.contentwithpublishfoldertype + + + + + + + + + + + RootDirectory + Contents/SharedSupport/%(RecursiveDir)%(Filename)%(Extension) + + + diff --git a/tests/dotnet/CustomizedCodeSigning/shared.csproj b/tests/dotnet/CustomizedCodeSigning/shared.csproj index 5e0d08bca288..f2cbc49178e2 100644 --- a/tests/dotnet/CustomizedCodeSigning/shared.csproj +++ b/tests/dotnet/CustomizedCodeSigning/shared.csproj @@ -18,12 +18,12 @@ $(CreateAppBundleDependsOn);CopyCustomFiles; - + Contents/SharedSupport Contents/MacOS Contents/MonoBundle - + SharedSupport diff --git a/tests/dotnet/ExtensionProject/iOS/ShareViewController.cs b/tests/dotnet/ExtensionProject/iOS/ShareViewController.cs index 08d46e5378c8..f0361286f481 100644 --- a/tests/dotnet/ExtensionProject/iOS/ShareViewController.cs +++ b/tests/dotnet/ExtensionProject/iOS/ShareViewController.cs @@ -22,7 +22,7 @@ public override void DidSelectPost () // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments. // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context. - ExtensionContext.CompleteRequest (null, null); + ExtensionContext?.CompleteRequest ([], null); } public override SLComposeSheetConfigurationItem [] GetConfigurationItems () diff --git a/tests/dotnet/ExtensionProject/macOS/ShareViewController.cs b/tests/dotnet/ExtensionProject/macOS/ShareViewController.cs index 95a23c5e0d77..3d59f883e3b4 100644 --- a/tests/dotnet/ExtensionProject/macOS/ShareViewController.cs +++ b/tests/dotnet/ExtensionProject/macOS/ShareViewController.cs @@ -17,7 +17,7 @@ public override void LoadView () { base.LoadView (); - NSExtensionItem item = ExtensionContext.InputItems.First (); + NSExtensionItem item = ExtensionContext?.InputItems.First () ?? new NSExtensionItem (); Console.WriteLine ("Attachments {0}", item); } @@ -25,13 +25,13 @@ partial void Cancel (Foundation.NSObject sender) { NSExtensionItem outputItem = new NSExtensionItem (); var outputItems = new [] { outputItem }; - ExtensionContext.CompleteRequest (outputItems, null); + ExtensionContext?.CompleteRequest (outputItems, null); } partial void Send (Foundation.NSObject sender) { NSError cancelError = NSError.FromDomain (NSError.CocoaErrorDomain, 3072, null); - ExtensionContext.CancelRequest (cancelError); + ExtensionContext?.CancelRequest (cancelError); } } } diff --git a/tests/dotnet/ExtensionProject/tvOS/ServiceProvider.cs b/tests/dotnet/ExtensionProject/tvOS/ServiceProvider.cs index c845047d0816..d2fba535f273 100644 --- a/tests/dotnet/ExtensionProject/tvOS/ServiceProvider.cs +++ b/tests/dotnet/ExtensionProject/tvOS/ServiceProvider.cs @@ -13,7 +13,9 @@ protected ServiceProvider (IntPtr handle) : base (handle) public TVContentItem [] TopShelfItems { [Export ("topShelfItems")] get { +#pragma warning disable CA1422 return new TVContentItem [] { new TVContentItem (new TVContentIdentifier ("identifier", null)) { Title = "title" } }; +#pragma warning restore CA1422 } } diff --git a/tests/dotnet/ExtensionProjectWithFrameworks/iOS/ShareViewController.cs b/tests/dotnet/ExtensionProjectWithFrameworks/iOS/ShareViewController.cs index 08d46e5378c8..f0361286f481 100644 --- a/tests/dotnet/ExtensionProjectWithFrameworks/iOS/ShareViewController.cs +++ b/tests/dotnet/ExtensionProjectWithFrameworks/iOS/ShareViewController.cs @@ -22,7 +22,7 @@ public override void DidSelectPost () // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments. // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context. - ExtensionContext.CompleteRequest (null, null); + ExtensionContext?.CompleteRequest ([], null); } public override SLComposeSheetConfigurationItem [] GetConfigurationItems () diff --git a/tests/dotnet/ExtensionProjectWithFrameworks/macOS/ShareViewController.cs b/tests/dotnet/ExtensionProjectWithFrameworks/macOS/ShareViewController.cs index 95a23c5e0d77..3d59f883e3b4 100644 --- a/tests/dotnet/ExtensionProjectWithFrameworks/macOS/ShareViewController.cs +++ b/tests/dotnet/ExtensionProjectWithFrameworks/macOS/ShareViewController.cs @@ -17,7 +17,7 @@ public override void LoadView () { base.LoadView (); - NSExtensionItem item = ExtensionContext.InputItems.First (); + NSExtensionItem item = ExtensionContext?.InputItems.First () ?? new NSExtensionItem (); Console.WriteLine ("Attachments {0}", item); } @@ -25,13 +25,13 @@ partial void Cancel (Foundation.NSObject sender) { NSExtensionItem outputItem = new NSExtensionItem (); var outputItems = new [] { outputItem }; - ExtensionContext.CompleteRequest (outputItems, null); + ExtensionContext?.CompleteRequest (outputItems, null); } partial void Send (Foundation.NSObject sender) { NSError cancelError = NSError.FromDomain (NSError.CocoaErrorDomain, 3072, null); - ExtensionContext.CancelRequest (cancelError); + ExtensionContext?.CancelRequest (cancelError); } } } diff --git a/tests/dotnet/ExtensionProjectWithFrameworks/tvOS/ServiceProvider.cs b/tests/dotnet/ExtensionProjectWithFrameworks/tvOS/ServiceProvider.cs index c845047d0816..d2fba535f273 100644 --- a/tests/dotnet/ExtensionProjectWithFrameworks/tvOS/ServiceProvider.cs +++ b/tests/dotnet/ExtensionProjectWithFrameworks/tvOS/ServiceProvider.cs @@ -13,7 +13,9 @@ protected ServiceProvider (IntPtr handle) : base (handle) public TVContentItem [] TopShelfItems { [Export ("topShelfItems")] get { +#pragma warning disable CA1422 return new TVContentItem [] { new TVContentItem (new TVContentIdentifier ("identifier", null)) { Title = "title" } }; +#pragma warning restore CA1422 } } diff --git a/tests/dotnet/MyCatalystApp/AppDelegate.cs b/tests/dotnet/MyCatalystApp/AppDelegate.cs index c708592b35a2..1020d28aa4f9 100644 --- a/tests/dotnet/MyCatalystApp/AppDelegate.cs +++ b/tests/dotnet/MyCatalystApp/AppDelegate.cs @@ -11,7 +11,7 @@ namespace MySingleView { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window { + public override UIWindow? Window { get; set; } diff --git a/tests/dotnet/MyCatalystApp/Main.cs b/tests/dotnet/MyCatalystApp/Main.cs index c580453b1ecd..647a8a9cb566 100644 --- a/tests/dotnet/MyCatalystApp/Main.cs +++ b/tests/dotnet/MyCatalystApp/Main.cs @@ -11,7 +11,7 @@ static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); + UIApplication.Main (args, null, typeof (AppDelegate)); } } } diff --git a/tests/dotnet/MyInterpretedApp/AppDelegate.cs b/tests/dotnet/MyInterpretedApp/AppDelegate.cs index d650bf83ba7e..b4a9e301991f 100644 --- a/tests/dotnet/MyInterpretedApp/AppDelegate.cs +++ b/tests/dotnet/MyInterpretedApp/AppDelegate.cs @@ -5,11 +5,13 @@ namespace MyInterpretedApp { public partial class AppDelegate : UIApplicationDelegate { - UIWindow window; + UIWindow? window; - public override bool FinishedLaunching (UIApplication app, NSDictionary options) + public override bool FinishedLaunching (UIApplication app, NSDictionary? options) { +#pragma warning disable CA1422 window = new UIWindow (UIScreen.MainScreen.Bounds); +#pragma warning restore CA1422 var dvc = new UIViewController (); var button = new UIButton (window.Bounds); diff --git a/tests/dotnet/MyMauiApp/MacCatalyst/App.xaml.cs b/tests/dotnet/MyMauiApp/MacCatalyst/App.xaml.cs index 525041dbe4ac..f986a7ba7f2b 100644 --- a/tests/dotnet/MyMauiApp/MacCatalyst/App.xaml.cs +++ b/tests/dotnet/MyMauiApp/MacCatalyst/App.xaml.cs @@ -4,7 +4,10 @@ public partial class App : Application { public App () { InitializeComponent (); + } - MainPage = new AppShell (); + protected override Window CreateWindow (IActivationState? activationState) + { + return new Window (new AppShell ()); } } diff --git a/tests/dotnet/MyMauiApp/iOS/App.xaml.cs b/tests/dotnet/MyMauiApp/iOS/App.xaml.cs index 525041dbe4ac..f986a7ba7f2b 100644 --- a/tests/dotnet/MyMauiApp/iOS/App.xaml.cs +++ b/tests/dotnet/MyMauiApp/iOS/App.xaml.cs @@ -4,7 +4,10 @@ public partial class App : Application { public App () { InitializeComponent (); + } - MainPage = new AppShell (); + protected override Window CreateWindow (IActivationState? activationState) + { + return new Window (new AppShell ()); } } diff --git a/tests/dotnet/MyMauiApp/shared.csproj b/tests/dotnet/MyMauiApp/shared.csproj index bcf263936efe..cb7d9a2ec94d 100644 --- a/tests/dotnet/MyMauiApp/shared.csproj +++ b/tests/dotnet/MyMauiApp/shared.csproj @@ -5,7 +5,6 @@ true true enable - enable MyMauiApp diff --git a/tests/dotnet/MyNativeAotAppWithTrimAnalysisWarning/shared.csproj b/tests/dotnet/MyNativeAotAppWithTrimAnalysisWarning/shared.csproj index 7e098b544c44..40d5c9df0443 100644 --- a/tests/dotnet/MyNativeAotAppWithTrimAnalysisWarning/shared.csproj +++ b/tests/dotnet/MyNativeAotAppWithTrimAnalysisWarning/shared.csproj @@ -8,6 +8,7 @@ 3.14 true + false diff --git a/tests/dotnet/MyRegistrarApp/AppDelegate.cs b/tests/dotnet/MyRegistrarApp/AppDelegate.cs index a6ce71157904..d5a822b67142 100644 --- a/tests/dotnet/MyRegistrarApp/AppDelegate.cs +++ b/tests/dotnet/MyRegistrarApp/AppDelegate.cs @@ -26,9 +26,10 @@ static int StaticRegistrarValidationTest () Console.WriteLine ($"GCH: {gchandle}"); if (gchandle != IntPtr.Zero) { var gch = GCHandle.FromIntPtr (gchandle); - var exc = (Exception) gch.Target; + var exc = gch.Target as Exception; gch.Free (); - throw exc; + if (exc is not null) + throw exc; } return 1; // We're not supposed to get here } catch (Exception e) { diff --git a/tests/dotnet/MySingleView/AppDelegate.cs b/tests/dotnet/MySingleView/AppDelegate.cs index 6920ca9d8a6b..f3ac5c6cbc1e 100644 --- a/tests/dotnet/MySingleView/AppDelegate.cs +++ b/tests/dotnet/MySingleView/AppDelegate.cs @@ -5,11 +5,13 @@ namespace MySingleView { public partial class AppDelegate : UIApplicationDelegate { - UIWindow window; + UIWindow? window; - public override bool FinishedLaunching (UIApplication app, NSDictionary options) + public override bool FinishedLaunching (UIApplication app, NSDictionary? options) { +#pragma warning disable CA1422 window = new UIWindow (UIScreen.MainScreen.Bounds); +#pragma warning restore CA1422 var dvc = new UIViewController (); var button = new UIButton (window.Bounds); diff --git a/tests/dotnet/MyTVApp/AppDelegate.cs b/tests/dotnet/MyTVApp/AppDelegate.cs index 0b2fcc29d499..f806328b529c 100644 --- a/tests/dotnet/MyTVApp/AppDelegate.cs +++ b/tests/dotnet/MyTVApp/AppDelegate.cs @@ -6,7 +6,7 @@ namespace MyTVApp { public partial class AppDelegate : UIApplicationDelegate { - public override UIWindow Window { + public override UIWindow? Window { get; set; } diff --git a/tests/dotnet/SizeTestApp/AppDelegate.cs b/tests/dotnet/SizeTestApp/AppDelegate.cs index 05e173fcd149..a7f46829c690 100644 --- a/tests/dotnet/SizeTestApp/AppDelegate.cs +++ b/tests/dotnet/SizeTestApp/AppDelegate.cs @@ -27,11 +27,13 @@ static int Main (string [] args) #if HAS_UIKIT public partial class AppDelegate : UIApplicationDelegate { - UIWindow window; + UIWindow? window; - public override bool FinishedLaunching (UIApplication app, NSDictionary options) + public override bool FinishedLaunching (UIApplication app, NSDictionary? options) { +#pragma warning disable CA1422 window = new UIWindow (UIScreen.MainScreen.Bounds); +#pragma warning restore CA1422 var dvc = new UIViewController (); var button = new UIButton (window.Bounds); diff --git a/tests/dotnet/UnitTests/AppIconTest.cs b/tests/dotnet/UnitTests/AppIconTest.cs index e8bea97b7c7e..a5eb8dc0d9c3 100644 --- a/tests/dotnet/UnitTests/AppIconTest.cs +++ b/tests/dotnet/UnitTests/AppIconTest.cs @@ -656,7 +656,7 @@ void TestXCAssetsImpl (ApplePlatform platform, string runtimeIdentifiers, Dictio try { var doc = AssetsTest.ProcessAssets (assetsCar, AssetsTest.GetFullSdkVersion (platform, runtimeIdentifiers)); - Assert.IsNotNull (doc, "There was an issue processing the asset binary."); + Assert.That (doc, Is.Not.Null, "There was an issue processing the asset binary."); var foundAssets = AssetsTest.FindAssets (platform, doc); @@ -666,11 +666,45 @@ void TestXCAssetsImpl (ApplePlatform platform, string runtimeIdentifiers, Dictio expectedAssets.Add (asset); } - CollectionAssert.AreEquivalent (expectedAssets, foundAssets, "Incorrect assets"); + Assert.That (foundAssets, Is.EquivalentTo (expectedAssets), "Incorrect assets"); } catch { Console.WriteLine ($"Assets.car: {assetsCar}"); throw; } } + + [TestCase (ApplePlatform.iOS, "iossimulator-arm64")] + [TestCase (ApplePlatform.TVOS, "tvossimulator-arm64")] + [TestCase (ApplePlatform.MacCatalyst, "maccatalyst-arm64")] + [TestCase (ApplePlatform.MacOSX, "osx-arm64")] + public void ComposerIcon (ApplePlatform platform, string runtimeIdentifiers) + { + Configuration.AssertRuntimeIdentifiersAvailable (platform, runtimeIdentifiers); + Configuration.IgnoreIfIgnoredPlatform (platform); + + var project = "AppWithComposerIcon"; + var projectPath = GetProjectPath (project, runtimeIdentifiers: runtimeIdentifiers, platform: platform, out var appPath); + Clean (projectPath); + + var properties = GetDefaultProperties (runtimeIdentifiers); + DotNet.Execute ("build", projectPath, properties); + + var resourcesDirectory = GetResourcesDirectory (platform, appPath); + + // Verify that the raw .icon files are not in the app bundle as BundleResources + var iconJsonInBundle = Path.Combine (resourcesDirectory, "AppIcon.icon", "icon.json"); + Assert.That (iconJsonInBundle, Does.Not.Exist, "icon.json should not be in the app bundle as a raw BundleResource"); + + var frontPngInBundle = Path.Combine (resourcesDirectory, "AppIcon.icon", "Assets", "front.png"); + Assert.That (frontPngInBundle, Does.Not.Exist, "front.png should not be in the app bundle as a raw BundleResource"); + + var backPngInBundle = Path.Combine (resourcesDirectory, "AppIcon.icon", "Assets", "back.png"); + Assert.That (backPngInBundle, Does.Not.Exist, "back.png should not be in the app bundle as a raw BundleResource"); + + // Verify that the compiled asset catalog exists in the app bundle + var assetsCar = Path.Combine (resourcesDirectory, "Assets.car"); + Assert.That (assetsCar, Does.Exist, "Assets.car"); + } } } + diff --git a/tests/dotnet/UnitTests/AppSizeTest.cs b/tests/dotnet/UnitTests/AppSizeTest.cs index e3157fd6dbe8..701aed8bbf74 100644 --- a/tests/dotnet/UnitTests/AppSizeTest.cs +++ b/tests/dotnet/UnitTests/AppSizeTest.cs @@ -8,6 +8,7 @@ namespace Xamarin.Tests { [TestFixture] + [Ignore ("The results depend on the macOS version of the bot running the test")] public class AppSizeTest : TestBaseClass { [TestCase (ApplePlatform.iOS, "ios-arm64")] @@ -113,7 +114,8 @@ void Run (ApplePlatform platform, string runtimeIdentifiers, string configuratio DotNet.AssertBuild (project_path, properties); // FORCE_UPDATE_KNOWN_FAILURES will update the known failures files even if the test doesn't actually fail - // WRITE_KNOWN_FAILURES will only update the known failures files if the test fails + // WRITE_KNOWN_FAILURES will only update the known failures files if the test fails (and mark the test as passed) + // If neither is set, the updated expected file is uploaded as an Azure DevOps artifact. var forceUpdate = !string.IsNullOrEmpty (Environment.GetEnvironmentVariable ("FORCE_UPDATE_KNOWN_FAILURES")); var update = forceUpdate || !string.IsNullOrEmpty (Environment.GetEnvironmentVariable ("WRITE_KNOWN_FAILURES")); @@ -166,30 +168,21 @@ static void AssertAppSize (ApplePlatform platform, string name, string appPath, msg = $"App size changed significantly ({FormatBytes (appSizeDifference, true)} different > tolerance of +-{FormatBytes (toleranceInBytes)}). Expected app size: {FormatBytes (expectedAppBundleSize)}, actual app size: {FormatBytes (appBundleSize)}."; } - var updated = false; - if (forceUpdate || (update && !withinTolerance)) { - Directory.CreateDirectory (expectedDirectory); - File.WriteAllText (expectedSizeReportPath, report.ToString ()); - msg += " Check the modified files for more information."; - updated = true; - } else if (!withinTolerance) { - msg += " Set the environment variable WRITE_KNOWN_FAILURES=1, run the test again, and verify the modified files for more information."; - } - Console.WriteLine ($" {msg}"); + // Compare individual files in the app bundle var expectedLines = expectedSizeReport.SplitLines ().Skip (2).Where (v => v.IndexOf (':') >= 0).ToDictionary (v => v [..v.IndexOf (':')], v => v [(v.IndexOf (':') + 1)..]); var actualLines = report.ToString ().SplitLines ().Skip (2).Where (v => v.IndexOf (':') >= 0).ToDictionary (v => v [..v.IndexOf (':')], v => v [(v.IndexOf (':') + 1)..]); var allKeys = expectedLines.Keys.Union (actualLines.Keys).OrderBy (v => v); + var filesAdded = new List (); + var filesRemoved = new List (); foreach (var key in allKeys) { if (!expectedLines.TryGetValue (key, out var expectedLine)) { Console.WriteLine ($" File '{key}' was added to app bundle: {actualLines [key]}"); - if (!updated) - Assert.Fail ($"The file '{key}' was added to the app bundle."); + filesAdded.Add (key); } else if (!actualLines.TryGetValue (key, out var actualLine)) { Console.WriteLine ($" File '{key}' was removed from app bundle: {expectedLine}"); - if (!updated) - Assert.Fail ($"The file '{key}' was removed from the app bundle."); + filesRemoved.Add (key); } else if (expectedLine != actualLine) { Console.WriteLine ($" File '{key}' changed in app bundle:"); Console.WriteLine ($" -{expectedLine}"); @@ -197,8 +190,28 @@ static void AssertAppSize (ApplePlatform platform, string name, string appPath, } } - if (!updated && !withinTolerance) - Assert.Fail (msg); + // Determine if there are any meaningful differences + var hasFileDifferences = filesAdded.Count > 0 || filesRemoved.Count > 0; + var hasSizeDifference = !withinTolerance; + var hasDifferences = hasFileDifferences || hasSizeDifference; + + if (forceUpdate || (update && hasDifferences)) { + Directory.CreateDirectory (expectedDirectory); + File.WriteAllText (expectedSizeReportPath, report.ToString ()); + Console.WriteLine ($" Updated expected file: {expectedSizeReportPath}"); + } else if (hasDifferences) { + UploadUpdatedExpectedFile (expectedSizeReportPath, report.ToString ()); + var updateHint = GetUpdateHint (); + if (hasFileDifferences) { + var details = new List (); + foreach (var key in filesAdded) + details.Add ($"added: '{key}'"); + foreach (var key in filesRemoved) + details.Add ($"removed: '{key}'"); + Assert.Fail ($"The app bundle's file list changed ({string.Join (", ", details)}). {updateHint}"); + } + Assert.Fail ($"{msg} {updateHint}"); + } } // Create a file with all the APIs that survived the trimmer; this can be useful to determine what is not trimmed away. @@ -237,11 +250,38 @@ void AssertAssemblyReport (ApplePlatform platform, string name, string appPath, } if (!update) { - Assert.That (addedAPIs, Is.Empty, "No added APIs (set the environment variable WRITE_KNOWN_FAILURES=1 and run the test again to update the expected set of APIs)"); - Assert.That (removedAPIs, Is.Empty, "No removed APIs (set the environment variable WRITE_KNOWN_FAILURES=1 and run the test again to update the expected set of APIs)"); + if (addedAPIs.Count > 0 || removedAPIs.Count > 0) { + UploadUpdatedExpectedFile (expectedFile, string.Join ('\n', preservedAPIs) + "\n"); + var updateHint = " " + GetUpdateHint (); + Assert.That (addedAPIs, Is.Empty, "Unexpected APIs were added to the preserved set." + updateHint); + Assert.That (removedAPIs, Is.Empty, "APIs were unexpectedly removed from the preserved set." + updateHint); + } } } + static void UploadUpdatedExpectedFile (string expectedFilePath, string content) + { + var fileName = Path.GetFileName (expectedFilePath); + var artifactStagingDir = Environment.GetEnvironmentVariable ("BUILD_ARTIFACTSTAGINGDIRECTORY"); + string outputDir; + if (!string.IsNullOrEmpty (artifactStagingDir)) { + outputDir = Path.Combine (artifactStagingDir, "updated-expected-sizes"); + } else { + outputDir = Path.Combine (Cache.CreateTemporaryDirectory ("AppSizeTest"), "updated-expected-sizes"); + } + Directory.CreateDirectory (outputDir); + var outputFile = Path.Combine (outputDir, fileName); + File.WriteAllText (outputFile, content); + Console.WriteLine ($" Updated expected file written to: {outputFile}"); + } + + static string GetUpdateHint () + { + if (IsInCI) + return "The updated expected file is available as a build artifact (set WRITE_KNOWN_FAILURES=1 to update locally)."; + return "Set WRITE_KNOWN_FAILURES=1 to update the expected files in-place."; + } + static string FormatBytes (long bytes, bool alwaysShowSign = false) { return $"{(alwaysShowSign && bytes > 0 ? "+" : "")}{bytes:N0} bytes ({bytes / 1024.0:N1} KB = {bytes / (1024.0 * 1024.0):N1} MB)"; diff --git a/tests/dotnet/UnitTests/AssetsTest.cs b/tests/dotnet/UnitTests/AssetsTest.cs index 0f2655513ca4..3466457299e9 100644 --- a/tests/dotnet/UnitTests/AssetsTest.cs +++ b/tests/dotnet/UnitTests/AssetsTest.cs @@ -55,7 +55,7 @@ void TestXCAssetsImpl (ApplePlatform platform, string runtimeIdentifiers, bool i Assert.That (assetsCar, Does.Exist, "Assets.car"); var doc = ProcessAssets (assetsCar, GetFullSdkVersion (platform, runtimeIdentifiers)); - Assert.IsNotNull (doc, "There was an issue processing the asset binary."); + Assert.That (doc, Is.Not.Null, "There was an issue processing the asset binary."); var foundAssets = FindAssets (platform, doc); @@ -78,12 +78,12 @@ void TestXCAssetsImpl (ApplePlatform platform, string runtimeIdentifiers, bool i throw new ArgumentOutOfRangeException ($"Unknown platform: {platform}"); } - CollectionAssert.AreEquivalent (expectedAssets, foundAssets, $"Incorrect assets in {assetsCar}"); + Assert.That (foundAssets, Is.EquivalentTo (expectedAssets), $"Incorrect assets in {assetsCar}"); var arm64txt = Path.Combine (resourcesDirectory, "arm64.txt"); var x64txt = Path.Combine (resourcesDirectory, "x64.txt"); - Assert.AreEqual (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-arm64")), File.Exists (arm64txt), "arm64.txt"); - Assert.AreEqual (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-x64")), File.Exists (x64txt), "x64.txt"); + Assert.That (File.Exists (arm64txt), Is.EqualTo (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-arm64"))), "arm64.txt"); + Assert.That (File.Exists (x64txt), Is.EqualTo (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-x64"))), "x64.txt"); } void ConfigureAssets (string projectPath, string runtimeIdentifiers, string config, bool isStartingWithAssets) @@ -128,7 +128,7 @@ void MakeSymlinks (string sourceDir, string destDir) var executable = "ln"; var arguments = new string [] { "-s", sourceDir, destDir }; var rv = Execution.RunAsync (executable, arguments, timeout: TimeSpan.FromSeconds (60)).Result; - Assert.AreEqual (0, rv.ExitCode, $"Creating Symlink Error: {rv.Output.MergedOutput}. Unexpected ExitCode"); + Assert.That (rv.ExitCode, Is.EqualTo (0), $"Creating Symlink Error: {rv.Output.MergedOutput}. Unexpected ExitCode"); } public static string GetFullSdkVersion (ApplePlatform platform, string runtimeIdentifiers) @@ -161,12 +161,12 @@ void ProcessUpdateSymlink (string xcassetsDir) var assets = Directory.EnumerateFiles (xcassetsDir, "*.*", SearchOption.AllDirectories).ToArray (); // assets first value is a .DS_Store file that work trigger MSBuild recompile so we want the second value - Assert.Greater (assets.Length, 1); + Assert.That (assets.Length, Is.GreaterThan (1)); var executable = "touch"; var arguments = new string [] { assets [1] }; var rv = Execution.RunAsync (executable, arguments, timeout: TimeSpan.FromSeconds (120)).Result; - Assert.AreEqual (0, rv.ExitCode, $"Processing Update Symlink Error: {rv.Output.MergedOutput}. Unexpected ExitCode"); + Assert.That (rv.ExitCode, Is.EqualTo (0), $"Processing Update Symlink Error: {rv.Output.MergedOutput}. Unexpected ExitCode"); } public static JsonDocument ProcessAssets (string assetsPath, string sdkVersion) @@ -176,7 +176,7 @@ public static JsonDocument ProcessAssets (string assetsPath, string sdkVersion) var tmpfile = Path.Combine (tmpdir, "Assets.json"); var arguments = new string [] { "--sdk", sdkVersion, "assetutil", "--info", assetsPath, "-o", tmpfile }; var rv = Execution.RunAsync (executable, arguments, timeout: TimeSpan.FromSeconds (120)).Result; - Assert.AreEqual (0, rv.ExitCode, $"Processing Assets Error: {rv.Output.StandardError}. Unexpected ExitCode"); + Assert.That (rv.ExitCode, Is.EqualTo (0), $"Processing Assets Error: {rv.Output.StandardError}. Unexpected ExitCode"); var s = File.ReadAllText (tmpfile); try { @@ -212,7 +212,7 @@ public static HashSet FindAssets (ApplePlatform platform, JsonDocument d case ApplePlatform.MacCatalyst: case ApplePlatform.iOS: case ApplePlatform.TVOS: - Assert.AreEqual ("2", schemaVersion.ToString (), "Verify SchemaVersion"); + Assert.That (schemaVersion.ToString (), Is.EqualTo ("2"), "Verify SchemaVersion"); break; default: throw new ArgumentOutOfRangeException ($"Unknown platform: {platform}"); diff --git a/tests/dotnet/UnitTests/BundleStructureTest.cs b/tests/dotnet/UnitTests/BundleStructureTest.cs index 13b5f6ca256a..d751c42dbdd6 100644 --- a/tests/dotnet/UnitTests/BundleStructureTest.cs +++ b/tests/dotnet/UnitTests/BundleStructureTest.cs @@ -1,5 +1,7 @@ #nullable enable +using Xamarin.Bundler; + namespace Xamarin.Tests { [TestFixture] public class BundleStructureTest : TestBaseClass { @@ -311,6 +313,7 @@ internal static void CheckAppBundleContents (ApplePlatform platform, IEnumerable if (platform != ApplePlatform.MacOSX) AddMultiRidAssembly (platform, expectedFiles, assemblyDirectory, "MonoTouch.Dialog", runtimeIdentifiers, forceSingleRid: (platform == ApplePlatform.MacCatalyst && !isReleaseBuild), includeDebugFiles: includeDebugFiles); expectedFiles.Add (Path.Combine (assemblyDirectory, "nunit.framework.dll")); + expectedFiles.Add (Path.Combine (assemblyDirectory, "nunit.framework.legacy.dll")); expectedFiles.Add (Path.Combine (assemblyDirectory, "nunitlite.dll")); expectedFiles.Add (Path.Combine (assemblyDirectory, "Mono.Options.dll")); AddMultiRidAssembly (platform, expectedFiles, assemblyDirectory, "Touch.Client", runtimeIdentifiers, platform == ApplePlatform.MacOSX || (platform == ApplePlatform.MacCatalyst && !isReleaseBuild), includeDebugFiles: includeDebugFiles); @@ -680,7 +683,7 @@ public void Build (ApplePlatform platform, string runtimeIdentifiers, CodeSignat var appExecutable = GetNativeExecutable (platform, appPath); CheckAppBundleContents (platform, appPath, rids, signature, isReleaseBuild); - CollectionAssert.AreEqual (expectedWarnings, warningMessages, "Warnings"); + Assert.That (warningMessages, Is.EqualTo (expectedWarnings), "Warnings"); ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); // touch AppDelegate.cs, and rebuild should succeed and do the right thing @@ -692,7 +695,7 @@ public void Build (ApplePlatform platform, string runtimeIdentifiers, CodeSignat warningMessages = FilterWarnings (warnings); CheckAppBundleContents (platform, appPath, rids, signature, isReleaseBuild); - CollectionAssert.AreEqual (expectedWarnings, warningMessages, "Warnings Rebuild 1"); + Assert.That (warningMessages, Is.EqualTo (expectedWarnings), "Warnings Rebuild 1"); ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); // remove the bin directory, and rebuild should succeed and do the right thing @@ -704,7 +707,7 @@ public void Build (ApplePlatform platform, string runtimeIdentifiers, CodeSignat warningMessages = FilterWarnings (warnings); CheckAppBundleContents (platform, appPath, rids, signature, isReleaseBuild); - CollectionAssert.AreEqual (expectedWarnings, warningMessages, "Warnings Rebuild 2"); + Assert.That (warningMessages, Is.EqualTo (expectedWarnings), "Warnings Rebuild 2"); ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); // a simple rebuild should succeed @@ -713,7 +716,7 @@ public void Build (ApplePlatform platform, string runtimeIdentifiers, CodeSignat warningMessages = FilterWarnings (warnings); CheckAppBundleContents (platform, appPath, rids, signature, isReleaseBuild); - CollectionAssert.AreEqual (expectedWarnings, warningMessages, "Warnings Rebuild 3"); + Assert.That (warningMessages, Is.EqualTo (expectedWarnings), "Warnings Rebuild 3"); ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); } @@ -793,8 +796,8 @@ static void AssertLibraryArchitectures (string appBundle, string [] runtimeIdent return false; }); foreach (var lib in libraries) { - var libArchitectures = renderArchitectures (MachO.GetArchitectures (lib)); - Assert.AreEqual (expectedArchitectures, libArchitectures, $"Architectures in {lib}"); + var libArchitectures = renderArchitectures (MachO.GetArchitectures (ConsoleLog.Instance, lib)); + Assert.That (libArchitectures, Is.EqualTo (expectedArchitectures), $"Architectures in {lib}"); } } } diff --git a/tests/dotnet/UnitTests/ContentWithPublishFolderTypeTest.cs b/tests/dotnet/UnitTests/ContentWithPublishFolderTypeTest.cs new file mode 100644 index 000000000000..edd961ca624c --- /dev/null +++ b/tests/dotnet/UnitTests/ContentWithPublishFolderTypeTest.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Xamarin.Tests { + [TestFixture] + public class ContentWithPublishFolderTypeTest : TestBaseClass { + + [Test] + [TestCase (ApplePlatform.MacOSX, "osx-arm64")] + public void ContentFilesWithSdkAssemblyNamesAreIncluded (ApplePlatform platform, string runtimeIdentifiers) + { + // Regression test for https://github.com/dotnet/macios/issues/25497 + // When Content items have PublishFolderType=RootDirectory and filenames matching + // SDK assemblies (e.g., Microsoft.macOS.dll) or runtime files (e.g., libclrgc.dylib), + // they should still be copied to the app bundle. + var project = "ContentWithPublishFolderType"; + Configuration.IgnoreIfIgnoredPlatform (platform); + Configuration.AssertRuntimeIdentifiersAvailable (platform, runtimeIdentifiers); + + var project_path = GetProjectPath (project, runtimeIdentifiers: runtimeIdentifiers, platform: platform, out var appPath); + Clean (project_path); + + var properties = GetDefaultProperties (runtimeIdentifiers); + DotNet.AssertBuild (project_path, properties); + + // These are files in our helper directory that have the same names as SDK assemblies / runtime files. + // They should all be present in the app bundle's SharedSupport directory. + var expectedFiles = new string [] { + // Files that match SDK assembly names (these are the ones that go missing per the bug report) + "Contents/SharedSupport/SubApp.app/Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.macOS.dll", + "Contents/SharedSupport/SubApp.app/Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.CSharp.dll", + "Contents/SharedSupport/SubApp.app/Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.VisualBasic.dll", + // A runtime dylib that matches a known runtime file name + "Contents/SharedSupport/SubApp.app/Contents/MonoBundle/libclrgc.dylib", + // Files that don't match SDK assembly names (these work fine) + "Contents/SharedSupport/SubApp.app/Contents/MonoBundle/.xamarin/osx-arm64/HeartBeatHandlerMac.dll", + "Contents/SharedSupport/SubApp.app/Contents/MonoBundle/AsyncIO.dll", + "Contents/SharedSupport/SubApp.app/Contents/MonoBundle/HeartbeatHandlerLib.dll", + "Contents/SharedSupport/SubApp.app/Contents/MonoBundle/System.ServiceModel.Security.dll", + }; + + foreach (var expectedFile in expectedFiles) { + var fullPath = Path.Combine (appPath, expectedFile); + Assert.That (fullPath, Does.Exist, $"Expected file '{expectedFile}' to be in the app bundle"); + } + } + } +} diff --git a/tests/dotnet/UnitTests/DotNetUnitTests.csproj b/tests/dotnet/UnitTests/DotNetUnitTests.csproj index 82660ce36e45..e0bbb37b7ce5 100644 --- a/tests/dotnet/UnitTests/DotNetUnitTests.csproj +++ b/tests/dotnet/UnitTests/DotNetUnitTests.csproj @@ -3,14 +3,12 @@ net$(BundledNETCoreAppTargetFrameworkVersion) false $(DefineConstants);NET;TESTS - enable - true - - - + + + @@ -47,6 +45,9 @@ external\Cache.cs + + external\IToolLog.cs + external\TargetFramework.cs diff --git a/tests/dotnet/UnitTests/Extensions.cs b/tests/dotnet/UnitTests/Extensions.cs index 1d04abf51f24..ba97980be9a9 100644 --- a/tests/dotnet/UnitTests/Extensions.cs +++ b/tests/dotnet/UnitTests/Extensions.cs @@ -96,7 +96,7 @@ public static void AssertWarnings (this IEnumerable actualWarning Console.WriteLine ($"If this is expected, an updated list of expected warnings in stored in {fn}"); File.WriteAllText (fn, sb.ToString ()); - // Rather than doing an Assert.IsEmpty, which produces a horrendous error message, we'll do an Assert.Multiple which generates a + // Rather than doing an Assert.That(..., Is.Empty), which produces a horrendous error message, we'll do an Assert.Multiple which generates a // nice enumerated output of all the failures. Assert.Multiple (() => { // fail for each of the new warnings diff --git a/tests/dotnet/UnitTests/ExtensionsTest.cs b/tests/dotnet/UnitTests/ExtensionsTest.cs index cc2e89e0328c..cf50e2098e90 100644 --- a/tests/dotnet/UnitTests/ExtensionsTest.cs +++ b/tests/dotnet/UnitTests/ExtensionsTest.cs @@ -27,7 +27,7 @@ public void AdditionalAppExtensionTest (ApplePlatform platform, string runtimeId "-target", "NativeIntentsExtension", "-project", Path.Combine (xcodeProjectFolder, "NativeContainer.xcodeproj"), }; - var env = new Dictionary { + var env = new Dictionary { { "DEVELOPER_DIR", Configuration.XcodeLocation }, }; foreach (var action in new string [] { "clean", "build" }) diff --git a/tests/dotnet/UnitTests/MauiTest.cs b/tests/dotnet/UnitTests/MauiTest.cs index cf64f548d8b4..7e2395013399 100644 --- a/tests/dotnet/UnitTests/MauiTest.cs +++ b/tests/dotnet/UnitTests/MauiTest.cs @@ -51,20 +51,19 @@ void BuildMauiAppImpl (ApplePlatform platform, string runtimeIdentifiers, bool d var rv = DotNet.AssertBuild (project_path, properties); AssertThatLinkerExecuted (rv); var infoPlistPath = GetInfoPListPath (platform, appPath); - var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mymauiapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MyMauiApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("1", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("1.0", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + var infoPlist = PDictionary.OpenFile (infoPlistPath); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mymauiapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MyMauiApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("1"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("1.0"), "CFBundleShortVersionString"); + Assert.That (BinLog.TryFindPropertyValue (rv.BinLogPath, "TrimMode", out var trimModeValue), Is.True, "Could not find the property 'TrimMode' in the binlog."); + Assert.That (BinLog.TryFindPropertyValue (rv.BinLogPath, "_LinkMode", out var linkModeValue), Is.True, "Could not find the property '_LinkMode' in the binlog."); + Assert.That (BinLog.TryFindPropertyValue (rv.BinLogPath, "MtouchLink", out var mtouchLinkValue), Is.True, "Could not find the property 'MtouchLink' in the binlog."); - Assert.IsTrue (BinLog.TryFindPropertyValue (rv.BinLogPath, "TrimMode", out var trimModeValue), "Could not find the property 'TrimMode' in the binlog."); - Assert.IsTrue (BinLog.TryFindPropertyValue (rv.BinLogPath, "_LinkMode", out var linkModeValue), "Could not find the property '_LinkMode' in the binlog."); - Assert.IsTrue (BinLog.TryFindPropertyValue (rv.BinLogPath, "MtouchLink", out var mtouchLinkValue), "Could not find the property 'MtouchLink' in the binlog."); - - Assert.AreEqual ("copy", trimModeValue, "TrimMode"); - Assert.AreEqual ("None", linkModeValue, "LinkMode"); - Assert.AreEqual ("None", mtouchLinkValue, "MtouchLink"); + Assert.That (trimModeValue, Is.EqualTo ("copy"), "TrimMode"); + Assert.That (linkModeValue, Is.EqualTo ("None"), "LinkMode"); + Assert.That (mtouchLinkValue, Is.EqualTo ("None"), "MtouchLink"); } [TestCase (ApplePlatform.MacCatalyst, "maccatalyst-arm64")] diff --git a/tests/dotnet/UnitTests/MlaunchTest.cs b/tests/dotnet/UnitTests/MlaunchTest.cs index fb7c3b9ba8b5..0610eb3f4dd0 100644 --- a/tests/dotnet/UnitTests/MlaunchTest.cs +++ b/tests/dotnet/UnitTests/MlaunchTest.cs @@ -48,11 +48,11 @@ public void GetMlaunchInstallArguments (ApplePlatform platform, string runtimeId expectedArguments.Append ("--installdev "); expectedArguments.Append (appPath.Substring (Path.GetDirectoryName (project_path)!.Length + 1)).Append ('/'); expectedArguments.Append ($" --wait-for-exit:false"); - Assert.AreEqual (expectedArguments.ToString (), mlaunchInstallArguments); + Assert.That (mlaunchInstallArguments, Is.EqualTo (expectedArguments.ToString ())); var scriptContents = File.ReadAllText (outputPath).Trim ('\n'); var expectedScriptContents = mlaunchPath + " " + expectedArguments.ToString (); - Assert.AreEqual (expectedScriptContents, scriptContents, "Script contents"); + Assert.That (scriptContents, Is.EqualTo (expectedScriptContents), "Script contents"); } public static object [] GetMlaunchRunArgumentsTestCases () diff --git a/tests/dotnet/UnitTests/PackTest.cs b/tests/dotnet/UnitTests/PackTest.cs index a9882a16414a..c5992b43650a 100644 --- a/tests/dotnet/UnitTests/PackTest.cs +++ b/tests/dotnet/UnitTests/PackTest.cs @@ -62,8 +62,8 @@ void BindingOldStyleImpl (ApplePlatform platform, Dictionary? pr var rv = DotNet.AssertPackFailure (project_path, properties, msbuildParallelism: false); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Error count"); - Assert.AreEqual ($"Creating a NuGet package is not supported for projects that have ObjcBindingNativeLibrary items. Migrate to use NativeReference items instead.", errors [0].Message, "Error message"); + Assert.That (errors.Length, Is.EqualTo (1), "Error count"); + Assert.That (errors [0].Message, Is.EqualTo ($"Creating a NuGet package is not supported for projects that have ObjcBindingNativeLibrary items. Migrate to use NativeReference items instead."), "Error message"); } [Test] @@ -191,8 +191,8 @@ void BindingXcFrameworksProjectImpl (ApplePlatform platform, bool noBindingEmbed var assemblyName = "bindings-framework-test"; if (!noBindingEmbedding) { - Assert.IsFalse (platformSpecificXcframework, "Invalid test variation: platformSpecificXcframework"); - Assert.IsFalse (compressedXcframework, "Invalid test variation: compressedXcframework"); + Assert.That (platformSpecificXcframework, Is.False, "Invalid test variation: platformSpecificXcframework"); + Assert.That (compressedXcframework, Is.False, "Invalid test variation: compressedXcframework"); } if (!platformSpecificXcframework) { @@ -365,7 +365,7 @@ void BindingCompressedXcFrameworksProjectImpl (ApplePlatform platform, bool comp using var archive = ZipFile.OpenRead (nupkg); var files = archive.Entries.Select (v => v.FullName).ToHashSet (); var tfm = platform.ToFrameworkWithPlatformVersion (isExecutable: false); - Assert.AreEqual (compressed ? 6 : 9, archive.Entries.Count, $"nupkg file count - {nupkg}"); + Assert.That (archive.Entries.Count, Is.EqualTo (compressed ? 6 : 9), $"nupkg file count - {nupkg}"); Assert.That (files, Does.Contain (assemblyName + ".nuspec"), "nuspec"); Assert.That (files, Does.Contain ("_rels/.rels"), ".rels"); Assert.That (files, Does.Contain ("[Content_Types].xml"), "[Content_Types].xml"); @@ -382,7 +382,7 @@ void BindingCompressedXcFrameworksProjectImpl (ApplePlatform platform, bool comp "XStaticArTest.xcframework.zip", "XStaticObjectTest.xcframework.zip", }; - CollectionAssert.AreEqual (innerZipContents.OrderBy (v => v), innerZip.OrderBy (v => v), "Inner zip"); + Assert.That (innerZip.OrderBy (v => v), Is.EqualTo (innerZipContents.OrderBy (v => v)), "Inner zip"); manifest = ZipHelpers.GetInnerString (nupkg, resourcesZip, "manifest"); } else { Assert.That (files, Does.Contain ($"lib/{tfm}/{assemblyName}.resources/manifest"), $"manifest"); @@ -431,7 +431,7 @@ void BindingCompressedXcFrameworksProjectImpl (ApplePlatform platform, bool comp """; - Assert.AreEqual (expectedManifest, manifest, "manifest contents"); + Assert.That (manifest, Is.EqualTo (expectedManifest), "manifest contents"); } [Test] diff --git a/tests/dotnet/UnitTests/PartialAppManifestTest.cs b/tests/dotnet/UnitTests/PartialAppManifestTest.cs index 9d386fcbaea6..f0fb6536005c 100644 --- a/tests/dotnet/UnitTests/PartialAppManifestTest.cs +++ b/tests/dotnet/UnitTests/PartialAppManifestTest.cs @@ -17,12 +17,12 @@ public void Build (ApplePlatform platform, string runtimeIdentifiers) DotNet.AssertBuild (project_path, properties); var infoPlistPath = GetInfoPListPath (platform, appPath); - var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mypartialappmanifestapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MyPartialAppManifestApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); - Assert.AreEqual ("SomeValue", infoPlist.GetString ("Something").Value, "Something"); + var infoPlist = PDictionary.OpenFile (infoPlistPath); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mypartialappmanifestapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MyPartialAppManifestApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("3.14"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("3.14"), "CFBundleShortVersionString"); + Assert.That (infoPlist.GetString ("Something").Value, Is.EqualTo ("SomeValue"), "Something"); var partialAppManifestPath = Path.Combine (Path.GetDirectoryName (project_path)!, "..", "Partial.plist"); Configuration.Touch (partialAppManifestPath); @@ -55,14 +55,14 @@ public void AppWithLibraryWithResourcesReference (ApplePlatform platform, string DotNet.AssertBuild (project_path, properties); var infoPlistPath = GetInfoPListPath (platform, appPath); - var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("Here I am", infoPlist.GetString ("LibraryWithResources").Value, "LibraryWithResources 1"); + var infoPlist = PDictionary.OpenFile (infoPlistPath); + Assert.That (infoPlist.GetString ("LibraryWithResources").Value, Is.EqualTo ("Here I am"), "LibraryWithResources 1"); // build again, nothing should change DotNet.AssertBuild (project_path, properties); - infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("Here I am", infoPlist.GetString ("LibraryWithResources").Value, "LibraryWithResources 2"); + infoPlist = PDictionary.OpenFile (infoPlistPath); + Assert.That (infoPlist.GetString ("LibraryWithResources").Value, Is.EqualTo ("Here I am"), "LibraryWithResources 2"); } } } diff --git a/tests/dotnet/UnitTests/PostBuildTest.cs b/tests/dotnet/UnitTests/PostBuildTest.cs index 12f20d9901f2..3f8d8b76e8a6 100644 --- a/tests/dotnet/UnitTests/PostBuildTest.cs +++ b/tests/dotnet/UnitTests/PostBuildTest.cs @@ -222,14 +222,14 @@ public void PublishFailureTest (ApplePlatform platform, string runtimeIdentifier var rv = DotNet.AssertPublishFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Error Count"); + Assert.That (errors.Length, Is.EqualTo (1), "Error Count"); string expectedErrorMessage; if (runtimeIdentifiers.IndexOf (';') >= 0) { expectedErrorMessage = $"A runtime identifier for a device architecture must be specified in order to publish this project. '{runtimeIdentifiers}' are simulator architectures."; } else { expectedErrorMessage = $"A runtime identifier for a device architecture must be specified in order to publish this project. '{runtimeIdentifiers}' is a simulator architecture."; } - Assert.AreEqual (expectedErrorMessage, errors [0].Message, "Error Message"); + Assert.That (errors [0].Message, Is.EqualTo (expectedErrorMessage), "Error Message"); Assert.That (pkgPath, Does.Not.Exist, "ipa/pkg creation"); } diff --git a/tests/dotnet/UnitTests/ProjectTest.cs b/tests/dotnet/UnitTests/ProjectTest.cs index 3c3e639d6ca4..4fe2a5d3f241 100644 --- a/tests/dotnet/UnitTests/ProjectTest.cs +++ b/tests/dotnet/UnitTests/ProjectTest.cs @@ -25,11 +25,11 @@ public void BuildMySingleView (string runtimeIdentifier) AssertThatLinkerExecuted (result); AssertAppContents (platform, appPath); var infoPlistPath = Path.Combine (appPath, "Info.plist"); - var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mysingletitle", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MySingleTitle", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + var infoPlist = PDictionary.OpenFile (infoPlistPath); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mysingletitle"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MySingleTitle"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("3.14"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("3.14"), "CFBundleShortVersionString"); } [Test] @@ -83,11 +83,11 @@ public void BuildMyCatalystApp (string runtimeIdentifier) AssertThatLinkerExecuted (result); AssertAppContents (platform, appPath); var infoPlistPath = Path.Combine (appPath, "Contents", "Info.plist"); - var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mycatalystapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MyCatalystApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + var infoPlist = PDictionary.OpenFile (infoPlistPath); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mycatalystapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MyCatalystApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("3.14"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("3.14"), "CFBundleShortVersionString"); } [TestCase (ApplePlatform.iOS)] @@ -115,7 +115,7 @@ public void BuildMyClassLibrary (ApplePlatform platform) using var ad = AssemblyDefinition.ReadAssembly (dll, new ReaderParameters { ReadingMode = ReadingMode.Deferred }); var r = ad.MainModule.AssemblyReferences.Where (v => v.Name == $"Microsoft.{platform.AsString ()}").First (); var actualReferenceVersionString = $"{r.Version.Major}.{r.Version.Minor}"; - Assert.AreEqual (expectedReferenceVersionString, actualReferenceVersionString, $"Referenced version of Microsoft.{platform.AsString ()}.dll"); + Assert.That (actualReferenceVersionString, Is.EqualTo (expectedReferenceVersionString), $"Referenced version of Microsoft.{platform.AsString ()}.dll"); Assert.That (r.Version.Build, Is.EqualTo (0), "Build"); Assert.That (r.Version.Revision, Is.EqualTo (0), "Revision"); } @@ -397,11 +397,11 @@ public void BuildFatApp (ApplePlatform platform, string runtimeIdentifiers) AssertThatLinkerExecuted (result); var infoPlistPath = GetInfoPListPath (platform, appPath); Assert.That (infoPlistPath, Does.Exist, "Info.plist"); - var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mysimpleapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MySimpleApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + var infoPlist = PDictionary.OpenFile (infoPlistPath); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mysimpleapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MySimpleApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("3.14"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("3.14"), "CFBundleShortVersionString"); } [Test] @@ -428,9 +428,9 @@ public void BuildFatMonoTouchTest (ApplePlatform platform, string runtimeIdentif var appPath = Path.Combine (Path.GetDirectoryName (project_path)!, "bin", "Debug", platform.ToFramework (), "monotouchtest.app"); var infoPlistPath = GetInfoPListPath (platform, appPath); Assert.That (infoPlistPath, Does.Exist, "Info.plist"); - var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.monotouch-test", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MonoTouchTest", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); + var infoPlist = PDictionary.OpenFile (infoPlistPath); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.monotouch-test"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MonoTouchTest"), "CFBundleDisplayName"); } [Test] @@ -448,8 +448,8 @@ public void InvalidRuntimeIdentifiers (ApplePlatform platform, string runtimeIde var properties = GetDefaultProperties (runtimeIdentifiers); var rv = DotNet.AssertBuildFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Error count"); - Assert.AreEqual ($"Building for all the runtime identifiers '{runtimeIdentifiers}' at the same time isn't possible, because they represent different platform variations.", errors [0].Message, "Error message"); + Assert.That (errors.Length, Is.EqualTo (1), "Error count"); + Assert.That (errors [0].Message, Is.EqualTo ($"Building for all the runtime identifiers '{runtimeIdentifiers}' at the same time isn't possible, because they represent different platform variations."), "Error message"); } [Test] @@ -507,8 +507,8 @@ public void IsOverrideRuntimeIdentifier (ApplePlatform platform, string runtimeI properties ["cmdline:RuntimeIdentifier"] = "maccatalyst-x64"; var rv = DotNet.AssertBuild (project_path, properties); var warnings = BinLog.GetBuildLogWarnings (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, warnings.Length, "Warning Count"); - Assert.AreEqual ("RuntimeIdentifier was set on the command line, and will override the value for RuntimeIdentifiers set in the project file.", warnings [0].Message, "Warning message"); + Assert.That (warnings.Length, Is.EqualTo (1), "Warning Count"); + Assert.That (warnings [0].Message, Is.EqualTo ("RuntimeIdentifier was set on the command line, and will override the value for RuntimeIdentifiers set in the project file."), "Warning message"); } [Test] @@ -525,8 +525,8 @@ public void IsNotOverrideRuntimeIdentifier (ApplePlatform platform, string runti props ["RuntimeIdentifiers"] = "maccatalyst-arm64"; var rv = DotNet.AssertBuildFailure (projectPath, props); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual ("Both RuntimeIdentifier and RuntimeIdentifiers were passed on the command line, but only one of them can be set at a time.", errors [0].Message); - Assert.AreEqual (1, errors.Length, "Error count"); + Assert.That (errors [0].Message, Is.EqualTo ("Both RuntimeIdentifier and RuntimeIdentifiers were passed on the command line, but only one of them can be set at a time.")); + Assert.That (errors.Length, Is.EqualTo (1), "Error count"); } [Test] @@ -584,14 +584,14 @@ public void InvalidRuntimeIdentifier (ApplePlatform platform, string runtimeIden var rv = DotNet.AssertBuildFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); var uniqueErrors = errors.Select (v => v.Message).Distinct ().ToArray (); - Assert.AreEqual (1, uniqueErrors.Length, "Error count"); + Assert.That (uniqueErrors.Length, Is.EqualTo (1), "Error count"); string expectedError; if (notRecognized) { expectedError = $"The specified RuntimeIdentifier '{runtimeIdentifier}' is not recognized. See https://aka.ms/netsdk1083 for more information."; } else { expectedError = $"The RuntimeIdentifier '{runtimeIdentifier}' is invalid."; } - Assert.AreEqual (expectedError, uniqueErrors [0], "Error message"); + Assert.That (uniqueErrors [0], Is.EqualTo (expectedError), "Error message"); } [Test] @@ -611,7 +611,7 @@ public void InvalidRuntimeIdentifier_Restore (ApplePlatform platform, string run DotNet.AssertRestore (project_path, properties); } else { var rv = DotNet.Restore (project_path, properties); - Assert.AreNotEqual (0, rv.ExitCode, "Expected failure"); + Assert.That (rv.ExitCode, Is.Not.EqualTo (0), "Expected failure"); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); Assert.That (errors.Length, Is.GreaterThan (0), "Error count"); Assert.That (errors [0].Message, Does.Match (failureMessagePattern), "Message failure"); @@ -650,16 +650,16 @@ public void FilesInAppBundle (ApplePlatform platform, string runtimeIdentifiers) // Build again - this time it'll fail var rv = DotNet.Build (project_path, properties); var warnings = BinLog.GetBuildLogWarnings (rv.BinLogPath).ToArray (); - Assert.AreNotEqual (0, rv.ExitCode, "Unexpected success"); - Assert.AreEqual (1, warnings.Length, "Warning Count"); - Assert.AreEqual ($"Found files in the root directory of the app bundle. This will likely cause codesign to fail. Files:\nbin/Debug/{Configuration.DotNetTfm}-maccatalyst/maccatalyst-x64/MySimpleApp.app/otherfile.txt\nbin/Debug/{Configuration.DotNetTfm}-maccatalyst/maccatalyst-x64/MySimpleApp.app/otherdir\nbin/Debug/{Configuration.DotNetTfm}-maccatalyst/maccatalyst-x64/MySimpleApp.app/otherdir/otherfile.log", warnings [0].Message, "Warning"); + Assert.That (rv.ExitCode, Is.Not.EqualTo (0), "Unexpected success"); + Assert.That (warnings.Length, Is.EqualTo (1), "Warning Count"); + Assert.That (warnings [0].Message, Is.EqualTo ($"Found files in the root directory of the app bundle. This will likely cause codesign to fail. Files:\nbin/Debug/{Configuration.DotNetTfm}-maccatalyst/maccatalyst-x64/MySimpleApp.app/otherfile.txt\nbin/Debug/{Configuration.DotNetTfm}-maccatalyst/maccatalyst-x64/MySimpleApp.app/otherdir\nbin/Debug/{Configuration.DotNetTfm}-maccatalyst/maccatalyst-x64/MySimpleApp.app/otherdir/otherfile.log"), "Warning"); // Build again, asking for automatic removal of the extraneous files. var enableAutomaticCleanupProperties = new Dictionary (properties); enableAutomaticCleanupProperties ["EnableAutomaticAppBundleRootDirectoryCleanup"] = "true"; rv = DotNet.AssertBuild (project_path, enableAutomaticCleanupProperties); warnings = BinLog.GetBuildLogWarnings (rv.BinLogPath).ToArray (); - Assert.AreEqual (0, warnings.Length, "Warning Count"); + Assert.That (warnings.Length, Is.EqualTo (0), "Warning Count"); // Verify that the files were in fact removed. Assert.That (Path.Combine (appPath, "otherfile.txt"), Does.Not.Exist, "otherfile"); @@ -685,11 +685,11 @@ public void BuildCoreCLR (ApplePlatform platform, string runtimeIdentifiers) AssertThatLinkerExecuted (rv); var infoPlistPath = GetInfoPListPath (platform, appPath); Assert.That (infoPlistPath, Does.Exist, "Info.plist"); - var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mysimpleapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MySimpleApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + var infoPlist = PDictionary.OpenFile (infoPlistPath); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mysimpleapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MySimpleApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("3.14"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("3.14"), "CFBundleShortVersionString"); var appExecutable = GetNativeExecutable (platform, appPath); ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); @@ -760,9 +760,11 @@ public void BindingWithDefaultCompileInclude (ApplePlatform platform) // Verify that the MyNativeClass class exists in the assembly, and that it's actually a class. var ad = AssemblyDefinition.ReadAssembly (dllPath, new ReaderParameters { ReadingMode = ReadingMode.Deferred }); var myNativeClass = ad.MainModule.Types.FirstOrDefault (v => v.FullName == "MyApiDefinition.MyNativeClass"); - Assert.IsFalse (myNativeClass!.IsInterface, "IsInterface"); + Assert.That (myNativeClass, Is.Not.Null, "MyNativeClass"); + Assert.That (myNativeClass!.IsInterface, Is.False, "IsInterface"); var myStruct = ad.MainModule.Types.FirstOrDefault (v => v.FullName == "MyClassLibrary.MyStruct"); - Assert.IsTrue (myStruct!.IsValueType, "MyStruct"); + Assert.That (myStruct, Is.Not.Null, "MyStruct type"); + Assert.That (myStruct!.IsValueType, Is.True, "MyStruct"); var warnings = BinLog.GetBuildLogWarnings (rv.BinLogPath).Select (v => v.Message); Assert.That (warnings, Is.Empty, $"Build warnings:\n\t{string.Join ("\n\t", warnings)}"); @@ -800,19 +802,19 @@ public void AppWithResources (ApplePlatform platform, string runtimeIdentifiers) Assert.That (fontBFile, Does.Exist, "B.otf existence"); Assert.That (fontCFile, Does.Exist, "C.ttf existence"); - var plist = PDictionary.FromFile (GetInfoPListPath (platform, appPath))!; + var plist = PDictionary.OpenFile (GetInfoPListPath (platform, appPath)); switch (platform) { case ApplePlatform.iOS: case ApplePlatform.TVOS: case ApplePlatform.MacCatalyst: var uiAppFonts = plist.GetArray ("UIAppFonts"); - Assert.IsNotNull (uiAppFonts, "UIAppFonts"); - Assert.AreEqual (1, uiAppFonts.Count, "UIAppFonts.Count"); - Assert.AreEqual ("B.otf", ((PString) uiAppFonts [0]).Value, "UIAppFonts [0]"); + Assert.That (uiAppFonts, Is.Not.Null, "UIAppFonts"); + Assert.That (uiAppFonts.Count, Is.EqualTo (1), "UIAppFonts.Count"); + Assert.That (((PString) uiAppFonts [0]).Value, Is.EqualTo ("B.otf"), "UIAppFonts [0]"); break; case ApplePlatform.MacOSX: var applicationFontsPath = plist.GetString ("ATSApplicationFontsPath")?.Value; - Assert.AreEqual (".", applicationFontsPath, "ATSApplicationFontsPath"); + Assert.That (applicationFontsPath, Is.EqualTo ("."), "ATSApplicationFontsPath"); break; default: throw new ArgumentOutOfRangeException ($"Unknown platform: {platform}"); @@ -840,9 +842,9 @@ public void AppWithResources (ApplePlatform platform, string runtimeIdentifiers) var arm64txt = Path.Combine (resourcesDirectory, "arm64.txt"); var armtxt = Path.Combine (resourcesDirectory, "arm.txt"); var x64txt = Path.Combine (resourcesDirectory, "x64.txt"); - Assert.AreEqual (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-arm64")), File.Exists (arm64txt), "arm64.txt"); - Assert.AreEqual (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-arm")), File.Exists (armtxt), "arm.txt"); - Assert.AreEqual (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-x64")), File.Exists (x64txt), "x64.txt"); + Assert.That (File.Exists (arm64txt), Is.EqualTo (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-arm64"))), "arm64.txt"); + Assert.That (File.Exists (armtxt), Is.EqualTo (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-arm"))), "arm.txt"); + Assert.That (File.Exists (x64txt), Is.EqualTo (runtimeIdentifiers.Split (';').Any (v => v.EndsWith ("-x64"))), "x64.txt"); var b_otf = Path.Combine (Path.GetDirectoryName (project_path)!, "Resources", "B.otf"); Configuration.Touch (b_otf); @@ -1017,7 +1019,7 @@ public void LibraryWithResources (ApplePlatform platform, bool? bundleOriginalRe } else { expectedResources = new List (); } - CollectionAssert.AreEquivalent (expectedResources, actualResources, "Resources"); + Assert.That (actualResources, Is.EquivalentTo (expectedResources), "Resources"); var zeroLengthResources = actualAssemblyResources.Where (v => v.ResourceType == ResourceType.Embedded && ((EmbeddedResource) v).GetResourceData ().Length == 0).Select (v => v.Name).ToArray (); Assert.That (zeroLengthResources, Is.Empty, $"0-length resources"); @@ -1128,7 +1130,7 @@ void AppWithLibraryWithResourcesReferenceImpl (ApplePlatform platform, string ru if (bundleOriginalResources) { var infoPlist = appBundleInfo.GetFile (GetInfoPListPath (platform, "")); var appManifest = PDictionary.FromByteArray (infoPlist, out var _)!; - Assert.AreEqual ("Here I am", appManifest.GetString ("LibraryWithResources").Value, "Partial plist entry"); + Assert.That (appManifest.GetString ("LibraryWithResources").Value, Is.EqualTo ("Here I am"), "Partial plist entry"); } }); @@ -1869,6 +1871,19 @@ public void KillEverything () [TestCase (ApplePlatform.MacOSX, "osx-x64;osx-arm64", true)] // [TestCase ("MacCatalyst", "")] - No extension support yet public void BuildProjectsWithExtensions (ApplePlatform platform, string runtimeIdentifier, bool isNativeAot) + { + BuildProjectsWithExtensionsImpl (platform, runtimeIdentifier, isNativeAot); + } + + [TestCase (ApplePlatform.iOS, "ios-arm64", false)] + [Category ("RemoteWindows")] + public void BuildProjectsWithExtensionsOnRemoteWindows (ApplePlatform platform, string runtimeIdentifier, bool isNativeAot) + { + Configuration.IgnoreIfNotOnWindows (); + BuildProjectsWithExtensionsImpl (platform, runtimeIdentifier, isNativeAot, AddRemoteProperties ()); + } + + void BuildProjectsWithExtensionsImpl (ApplePlatform platform, string runtimeIdentifier, bool isNativeAot, Dictionary? properties = null) { Configuration.IgnoreIfIgnoredPlatform (platform); var consumingProjectDir = GetProjectPath ("ExtensionConsumer", runtimeIdentifier, platform, out var appPath); @@ -1877,7 +1892,7 @@ public void BuildProjectsWithExtensions (ApplePlatform platform, string runtimeI Clean (extensionProjectDir); Clean (consumingProjectDir); - var properties = GetDefaultProperties (runtimeIdentifier); + properties = GetDefaultProperties (runtimeIdentifier, extraProperties: properties); if (isNativeAot) { properties ["PublishAot"] = "true"; @@ -1891,7 +1906,7 @@ public void BuildProjectsWithExtensions (ApplePlatform platform, string runtimeI var pathToSearch = Path.Combine (Path.GetDirectoryName (consumingProjectDir)!, "bin", "Debug"); string [] configFiles = Directory.GetFiles (pathToSearch, "*.runtimeconfig.*", SearchOption.AllDirectories); - Assert.AreNotEqual (0, configFiles.Length, "runtimeconfig.json file does not exist"); + Assert.That (configFiles.Length, Is.Not.EqualTo (0), "runtimeconfig.json file does not exist"); } [TestCase (ApplePlatform.iOS, "iossimulator-x64", false)] @@ -1924,11 +1939,11 @@ public void BuildProjectsWithExtensionsAndFrameworks (ApplePlatform platform, st var extensionPath = Path.Combine (appPath, GetPlugInsRelativePath (platform), "ExtensionProjectWithFrameworks.appex"); Assert.That (Directory.Exists (extensionPath), $"App extension directory does not exist: {extensionPath}"); var extensionFrameworksPath = Path.Combine (extensionPath, GetFrameworksRelativePath (platform)); - Assert.IsFalse (Directory.Exists (extensionFrameworksPath), $"App extension framework directory exists when it shouldn't: {extensionFrameworksPath}"); + Assert.That (Directory.Exists (extensionFrameworksPath), Is.False, $"App extension framework directory exists when it shouldn't: {extensionFrameworksPath}"); var pathToSearch = Path.Combine (Path.GetDirectoryName (consumingProjectDir)!, "bin", "Debug"); var configFiles = Directory.GetFiles (pathToSearch, "*.runtimeconfig.*", SearchOption.AllDirectories); - Assert.AreNotEqual (0, configFiles.Length, "runtimeconfig.json file does not exist"); + Assert.That (configFiles.Length, Is.Not.EqualTo (0), "runtimeconfig.json file does not exist"); var appFrameworksPath = Path.Combine (appPath, GetFrameworksRelativePath (platform)); Assert.That (Directory.Exists (appFrameworksPath), $"App Frameworks directory does not exist: {appFrameworksPath}"); @@ -1997,22 +2012,6 @@ public void AppWithGenericLibraryReference (ApplePlatform platform, string runti ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); } - // This test can be removed in .NET 7 - [TestCase (ApplePlatform.iOS)] - [TestCase (ApplePlatform.TVOS)] - [TestCase (ApplePlatform.MacCatalyst)] - [TestCase (ApplePlatform.MacOSX)] - public void CentralPackageVersionsApp (ApplePlatform platform) - { - var project = "CentralPackageVersionsApp"; - Configuration.IgnoreIfIgnoredPlatform (platform); - - var project_path = GetProjectPath (project, platform: platform); - Clean (project_path); - var properties = GetDefaultProperties (); - DotNet.AssertBuild (project_path, properties); - } - [TestCase (ApplePlatform.MacCatalyst, "maccatalyst-x64", false)] [TestCase (ApplePlatform.iOS, "iossimulator-x64", true)] [TestCase (ApplePlatform.TVOS, "tvossimulator-x64", true)] @@ -2029,8 +2028,8 @@ public void CatalystAppOptimizedForMacOS (ApplePlatform platform, string runtime if (failureExpected) { var rv = DotNet.AssertBuildFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Error count"); - Assert.AreEqual ($"The UIDeviceFamily value '6' is not valid for this platform. It's only valid for Mac Catalyst.", errors [0].Message, "Error message"); + Assert.That (errors.Length, Is.EqualTo (1), "Error count"); + Assert.That (errors [0].Message, Is.EqualTo ($"The UIDeviceFamily value '6' is not valid for this platform. It's only valid for Mac Catalyst."), "Error message"); } else { DotNet.AssertBuild (project_path, properties); } @@ -2149,11 +2148,11 @@ void BuildSupportedNetVersionApp (ApplePlatform platform, string runtimeIdentifi AssertThatLinkerExecuted (result); var infoPlistPath = GetInfoPListPath (platform, appPath); Assert.That (infoPlistPath, Does.Exist, "Info.plist"); - var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.mysimpleapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MySimpleApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual (netVersion, infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual (netVersion, infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + var infoPlist = PDictionary.OpenFile (infoPlistPath); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mysimpleapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MySimpleApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo (netVersion), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo (netVersion), "CFBundleShortVersionString"); var appExecutable = GetNativeExecutable (platform, appPath); ExecuteWithMagicWordAndAssert (platform, runtimeIdentifiers, appExecutable); @@ -2300,7 +2299,7 @@ public void CustomizedCodeSigning (ApplePlatform platform, string runtimeIdentif foreach (var dylib in signedDylibs) { var path = Path.Combine (appPath, dylib); Assert.That (path, Does.Exist, "dylib exists"); - Assert.IsTrue (IsDylibSigned (path), $"Signed: {path}"); + Assert.That (IsDylibSigned (path), Is.True, $"Signed: {path}"); } appBundleContents.ExceptWith (signedDylibs); // And that there are unsigned dylibs, but not the system ones @@ -2310,9 +2309,9 @@ public void CustomizedCodeSigning (ApplePlatform platform, string runtimeIdentif foreach (var unsignedDylib in remainingDylibs) { var path = Path.Combine (appPath, unsignedDylib); Assert.That (path, Does.Exist, "unsigned dylib existence"); - Assert.IsFalse (IsDylibSigned (path), $"Unsigned: {path}"); + Assert.That (IsDylibSigned (path), Is.False, $"Unsigned: {path}"); } - Assert.AreEqual (2, remainingDylibs.Length, "Unsigned count"); + Assert.That (remainingDylibs.Length, Is.EqualTo (2), "Unsigned count"); // Verify that a Resources subdirectory causes the build to fail. switch (platform) { @@ -2382,11 +2381,11 @@ public void AutoAllowJitEntitlements (ApplePlatform platform, string runtimeIden var executable = GetNativeExecutable (platform, appPath); var foundEntitlements = TryGetEntitlements (executable, out var entitlements); if (configuration == "Release") { - Assert.IsTrue (foundEntitlements, "Found in Release"); - Assert.IsTrue (entitlements!.Get ("com.apple.security.cs.allow-jit")?.Value, "Jit Allowed"); + Assert.That (foundEntitlements, Is.True, "Found in Release"); + Assert.That (entitlements!.Get ("com.apple.security.cs.allow-jit")?.Value, Is.True, "Jit Allowed"); } else { var jitNotAllowed = !foundEntitlements || !entitlements!.ContainsKey ("com.apple.security.cs.allow-jit"); - Assert.True (jitNotAllowed, "Jit Not Allowed"); + Assert.That (jitNotAllowed, Is.True, "Jit Not Allowed"); } } @@ -2494,8 +2493,8 @@ public void BuildAndExecuteAppWithWinExeOutputType (ApplePlatform platform, stri var rv = DotNet.AssertBuildFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Error count"); - Assert.AreEqual ($"WinExe is not a valid output type for macOS", errors [0].Message, "Error message"); + Assert.That (errors.Length, Is.EqualTo (1), "Error count"); + Assert.That (errors [0].Message, Is.EqualTo ($"WinExe is not a valid output type for macOS"), "Error message"); } [Test] @@ -2538,9 +2537,9 @@ public void BuildMyNativeAotAppWithTrimAnalysisWarning (ApplePlatform platform, warnings = warnings.Where (w => w.Message?.Trim () != "Supported iPhone orientations have not been set").ToArray (); } - Assert.AreEqual (1, warnings.Length, "Warning count"); - Assert.AreEqual (warnings [0].Code, "IL2075", "Warning code"); - Assert.AreEqual (warnings [0].Message, "'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicProperties' in call to 'System.Type.GetProperties()'. The return value of method 'System.Object.GetType()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to."); + Assert.That (warnings.Length, Is.EqualTo (1), "Warning count"); + Assert.That (warnings [0].Code, Is.EqualTo ("IL2075"), "Warning code"); + Assert.That (warnings [0].Message, Is.EqualTo ("'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicProperties' in call to 'System.Type.GetProperties()'. The return value of method 'System.Object.GetType()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.")); } [Test] @@ -2574,7 +2573,7 @@ public void PublishAot (ApplePlatform platform, string runtimeIdentifiers, strin properties ["TrimmerSingleWarn"] = "false"; // don't be shy, we want to know what the problem is var rv = DotNet.AssertBuild (project_path, properties); - Assert.True (Directory.Exists (appPath), $"App file expected at: {appPath}"); + Assert.That (Directory.Exists (appPath), Is.True, $"App file expected at: {appPath}"); // Verify that we have no warnings, but unfortunately we still have some we haven't fixed yet. // Ignore those, and fail the test if we stop getting them (so that we can update the test to not ignore them anymore). @@ -2586,6 +2585,54 @@ public void PublishAot (ApplePlatform platform, string runtimeIdentifiers, strin }); } + [Test] + [TestCase (ApplePlatform.iOS, "iossimulator-arm64")] + [TestCase (ApplePlatform.MacCatalyst, "maccatalyst-arm64")] + [TestCase (ApplePlatform.TVOS, "tvossimulator-arm64")] + [TestCase (ApplePlatform.MacOSX, "osx-arm64")] + public void PublishAotMonoTouchTest_NoIL2009 (ApplePlatform platform, string runtimeIdentifiers) + { + Configuration.IgnoreIfIgnoredPlatform (platform); + Configuration.AssertRuntimeIdentifiersAvailable (platform, runtimeIdentifiers); + + var project_path = Path.Combine (Configuration.SourceRoot, "tests", "monotouch-test", "dotnet", platform.AsString (), "monotouch-test.csproj"); + Clean (project_path); + var properties = GetDefaultProperties (runtimeIdentifiers); + properties ["PublishAot"] = "true"; + properties ["_IsPublishing"] = "true"; + properties ["TrimmerSingleWarn"] = "false"; + var rv = DotNet.AssertBuild (project_path, properties); + + var config = "Debug"; + var runtimeIdentifierInfix = $"/{runtimeIdentifiers}/"; + var warnings = BinLog.GetBuildLogWarnings (rv.BinLogPath) + .Where (evt => { + if (platform == ApplePlatform.iOS && evt.Message?.Trim () == "Supported iPhone orientations have not been set") + return false; + return true; + }); + var expectedWarnings = new ExpectedBuildMessage [] { + new ExpectedBuildMessage ($"ILLINK", $"It's not safe to remove the dynamic registrar, because monotouchtest references 'ObjCRuntime.Runtime.ConnectMethod (System.Reflection.MethodInfo, ObjCRuntime.Selector)'."), + new ExpectedBuildMessage ($"ILLINK", $"It's not safe to remove the dynamic registrar, because monotouchtest references 'ObjCRuntime.Runtime.ConnectMethod (System.Type, System.Reflection.MethodInfo, Foundation.ExportAttribute)'."), + new ExpectedBuildMessage ($"ILLINK", $"It's not safe to remove the dynamic registrar, because monotouchtest references 'ObjCRuntime.Runtime.ConnectMethod (System.Type, System.Reflection.MethodInfo, ObjCRuntime.Selector)'."), + new ExpectedBuildMessage ($"ILLINK", $"It's not safe to remove the dynamic registrar, because monotouchtest references 'ObjCRuntime.Runtime.RegisterAssembly (System.Reflection.Assembly)'."), + new ExpectedBuildMessage ($"tests/bindings-test/RegistrarBindingTest.cs", $"Unable to locate the block to delegate conversion method for the method System.Void Xamarin.BindingTests.RegistrarBindingTest/FakePropertyBlock::set_MyOptionalProperty(Bindings.Test.SimpleCallback)'s parameter #1."), + new ExpectedBuildMessage ($"tests/bindings-test/RegistrarBindingTest.cs", $"Unable to locate the block to delegate conversion method for the method System.Void Xamarin.BindingTests.RegistrarBindingTest/FakePropertyBlock::set_MyOptionalStaticProperty(Bindings.Test.SimpleCallback)'s parameter #1."), + new ExpectedBuildMessage ($"tests/bindings-test/RegistrarBindingTest.cs", $"Unable to locate the block to delegate conversion method for the method System.Void Xamarin.BindingTests.RegistrarBindingTest/FakePropertyBlock::set_MyRequiredProperty(Bindings.Test.SimpleCallback)'s parameter #1."), + new ExpectedBuildMessage ($"tests/bindings-test/RegistrarBindingTest.cs", $"Unable to locate the block to delegate conversion method for the method System.Void Xamarin.BindingTests.RegistrarBindingTest/FakePropertyBlock::set_MyRequiredStaticProperty(Bindings.Test.SimpleCallback)'s parameter #1."), + new ExpectedBuildMessage ($"tests/bindings-test/RegistrarBindingTest.cs", $"Unable to locate the delegate to block conversion type for the return value of the method Bindings.Test.SimpleCallback Xamarin.BindingTests.RegistrarBindingTest/FakePropertyBlock::get_MyOptionalProperty()."), + new ExpectedBuildMessage ($"tests/bindings-test/RegistrarBindingTest.cs", $"Unable to locate the delegate to block conversion type for the return value of the method Bindings.Test.SimpleCallback Xamarin.BindingTests.RegistrarBindingTest/FakePropertyBlock::get_MyOptionalStaticProperty()."), + new ExpectedBuildMessage ($"tests/bindings-test/RegistrarBindingTest.cs", $"Unable to locate the delegate to block conversion type for the return value of the method Bindings.Test.SimpleCallback Xamarin.BindingTests.RegistrarBindingTest/FakePropertyBlock::get_MyRequiredProperty()."), + new ExpectedBuildMessage ($"tests/bindings-test/RegistrarBindingTest.cs", $"Unable to locate the delegate to block conversion type for the return value of the method Bindings.Test.SimpleCallback Xamarin.BindingTests.RegistrarBindingTest/FakePropertyBlock::get_MyRequiredStaticProperty()."), + new ExpectedBuildMessage ($"tests/monotouch-test/dotnet/{platform.AsString ()}/obj/{config}/{Configuration.DotNetTfm}-{platform.AsString ().ToLower ()}{runtimeIdentifierInfix}linked/nunit.framework.dll", $"Assembly 'nunit.framework' produced AOT analysis warnings."), + new ExpectedBuildMessage ($"tests/monotouch-test/ObjCRuntime/ClassTest.cs", $"MonoTouchFixtures.ObjCRuntime.ClassTest.GetHandle(): Using member 'System.Type.MakeArrayType()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The code for an array of the specified type might not be available."), + new ExpectedBuildMessage ($"tests/monotouch-test/ObjCRuntime/RegistrarTest.cs", $"Unable to locate the block to delegate conversion method for the method System.Void MonoTouchFixtures.ObjCRuntime.GHIssue7733::DoWork(System.String,MonoTouchFixtures.ObjCRuntime.ACompletionHandler)'s parameter #2."), + new ExpectedBuildMessage ($"tests/monotouch-test/ObjCRuntime/RegistrarTest.cs", $"Unable to locate the block to delegate conversion method for the method System.Void MonoTouchFixtures.ObjCRuntime.RegistrarTest/ClosedGenericParameter::Foo(System.Action`1)'s parameter #1."), + new ExpectedBuildMessage ($"tests/monotouch-test/ObjCRuntime/RegistrarTest.cs", $"Unable to locate the block to delegate conversion method for the method System.Void MonoTouchFixtures.ObjCRuntime.RegistrarTest/RegistrarTestClass::TestNSAction(System.Action)'s parameter #1."), + }; + warnings.AssertWarnings (expectedWarnings); + } + void AssertThatDylibExistsAndIsReidentified (string appPath, string dylibRelPath) { var dylibPath = Path.Join (appPath, "Contents", "MonoBundle", dylibRelPath); @@ -2808,14 +2855,14 @@ public void SourcelinkTest (ApplePlatform platform, string runtimeIdentifiers, s .GetFiles (Path.GetDirectoryName (project_path)!, $"Microsoft.{platformName}.pdb", SearchOption.AllDirectories) .FirstOrDefault (); - Assert.NotNull (pdbFile, "No PDB file found"); + Assert.That (pdbFile, Is.Not.Null, "No PDB file found"); var tool = "sourcelink"; var toolPath = Directory.GetCurrentDirectory (); DotNet.InstallTool (tool, toolPath); var test = DotNet.RunTool (Path.Combine (toolPath, tool), "test", pdbFile!); - Assert.AreEqual ($"sourcelink test passed: {pdbFile}", test.StandardOutput.ToString ().TrimEnd ('\n')); + Assert.That (test.StandardOutput.ToString ().TrimEnd ('\n'), Is.EqualTo ($"sourcelink test passed: {pdbFile}")); } @@ -2877,7 +2924,7 @@ public void DedupEnabledTest (ApplePlatform platform, string runtimeIdentifiers, DotNet.AssertBuild (project_path, properties); var objDir = GetObjDir (project_path, platform, runtimeIdentifiers); - Assert.True (FindAOTedAssemblyFile (objDir, "aot-instances.dll"), $"Dedup optimization should be enabled for AOT compilation on: {platform} with RID: {runtimeIdentifiers}"); + Assert.That (FindAOTedAssemblyFile (objDir, "aot-instances.dll"), Is.True, $"Dedup optimization should be enabled for AOT compilation on: {platform} with RID: {runtimeIdentifiers}"); } [Test] @@ -2901,7 +2948,7 @@ public void DedupDisabledTest (ApplePlatform platform, string runtimeIdentifiers DotNet.AssertBuild (project_path, properties); var objDir = GetObjDir (project_path, platform, runtimeIdentifiers); - Assert.False (FindAOTedAssemblyFile (objDir, "aot-instances.dll"), $"Dedup optimization should not be enabled for AOT compilation on: {platform} with RID: {runtimeIdentifiers}"); + Assert.That (FindAOTedAssemblyFile (objDir, "aot-instances.dll"), Is.False, $"Dedup optimization should not be enabled for AOT compilation on: {platform} with RID: {runtimeIdentifiers}"); } [Test] @@ -2923,10 +2970,10 @@ public void DedupUniversalAppTest (ApplePlatform platform, string runtimeIdentif var objDir = GetObjDir (project_path, platform, runtimeIdentifiers); var objDirMacCatalystArm64 = Path.Combine (objDir, "maccatalyst-arm64"); - Assert.True (FindAOTedAssemblyFile (objDirMacCatalystArm64, "aot-instances.dll"), $"Dedup optimization should be enabled for AOT compilation on: {platform} with RID: maccatalyst-arm64"); + Assert.That (FindAOTedAssemblyFile (objDirMacCatalystArm64, "aot-instances.dll"), Is.True, $"Dedup optimization should be enabled for AOT compilation on: {platform} with RID: maccatalyst-arm64"); var objDirMacCatalystx64 = Path.Combine (objDir, "maccatalyst-x64"); - Assert.False (FindAOTedAssemblyFile (objDirMacCatalystx64, "aot-instances.dll"), $"Dedup optimization should not be enabled for AOT compilation on: {platform} with RID: maccatalyst-x64"); + Assert.That (FindAOTedAssemblyFile (objDirMacCatalystx64, "aot-instances.dll"), Is.False, $"Dedup optimization should not be enabled for AOT compilation on: {platform} with RID: maccatalyst-x64"); var appExecutable = GetNativeExecutable (platform, appPath); @@ -3706,9 +3753,9 @@ public void LinkedWithNativeLibraries (ApplePlatform platform, string runtimeIde var appExecutable = GetNativeExecutable (platform, appPath); var actualFrameworks = GetLinkedWithFrameworks (appExecutable); - CollectionAssert.AreEquivalent ( - expectedFrameworks.OrderBy (v => v).ToArray (), + Assert.That ( actualFrameworks.OrderBy (v => v).ToArray (), + Is.EquivalentTo (expectedFrameworks.OrderBy (v => v).ToArray ()), "Frameworks"); } @@ -3746,9 +3793,9 @@ public void SpacedAppTitle (ApplePlatform platform, string runtimeIdentifiers) var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); var infoPlistPath = GetInfoPListPath (platform, appPath); - var infoPlist = PDictionary.FromFile (infoPlistPath)!; - Assert.AreEqual ("com.xamarin.spacedapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("Spaced App Title", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); + var infoPlist = PDictionary.OpenFile (infoPlistPath); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.spacedapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("Spaced App Title"), "CFBundleDisplayName"); var appName = Path.GetFileNameWithoutExtension (appPath); switch (platform) { diff --git a/tests/dotnet/UnitTests/PublishTrimmedTest.cs b/tests/dotnet/UnitTests/PublishTrimmedTest.cs index f7675e066d2f..8e6a1296ebf0 100644 --- a/tests/dotnet/UnitTests/PublishTrimmedTest.cs +++ b/tests/dotnet/UnitTests/PublishTrimmedTest.cs @@ -21,9 +21,9 @@ public void DisableLinker (ApplePlatform platform, string runtimeIdentifiers) var rv = DotNet.AssertBuildFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Error count"); + Assert.That (errors.Length, Is.EqualTo (1), "Error count"); var linkModeName = platform == ApplePlatform.MacOSX ? "LinkMode" : "MtouchLink"; - Assert.AreEqual ($"{platform.AsString ()} projects must build with PublishTrimmed=true. Current value: false. Set '{linkModeName}=None' instead to disable trimming for all assemblies.", errors [0].Message, "Error message"); + Assert.That (errors [0].Message, Is.EqualTo ($"{platform.AsString ()} projects must build with PublishTrimmed=true. Current value: false. Set '{linkModeName}=None' instead to disable trimming for all assemblies."), "Error message"); } } } diff --git a/tests/dotnet/UnitTests/RegistrarTest.cs b/tests/dotnet/UnitTests/RegistrarTest.cs index 767e5bda46e6..f7aad07cb565 100644 --- a/tests/dotnet/UnitTests/RegistrarTest.cs +++ b/tests/dotnet/UnitTests/RegistrarTest.cs @@ -48,7 +48,7 @@ public void InvalidStaticRegistrarValidation (ApplePlatform platform, string? ru ExecuteProjectWithMagicWordAndAssert (projectPath, platform, runtimeIdentifiers); } else if (CanExecute (platform, runtimeIdentifiers)) { var rv = base.Execute (GetNativeExecutable (platform, appDir), out var output, out _); - Assert.AreEqual (1, rv.ExitCode, "Expected no validation"); + Assert.That (rv.ExitCode, Is.EqualTo (1), "Expected no validation"); } } finally { Environment.SetEnvironmentVariable ("XAMARIN_VALIDATE_STATIC_REGISTRAR_CODE", null); @@ -76,6 +76,7 @@ public void ClassRewriterTest (ApplePlatform platform, bool rewriteHandles) // enable the linker (so that the main assembly is modified) properties ["LinkMode"] = "full"; properties ["MtouchLink"] = "full"; + properties ["InlineClassGetHandle"] = "disabled"; if (rewriteHandles) properties ["MtouchExtraArgs"] = "--optimize=redirect-class-handles"; @@ -89,7 +90,7 @@ public void ClassRewriterTest (ApplePlatform platform, bool rewriteHandles) Assert.That (File.Exists (platformDll), "No platform dll."); var module = ModuleDefinition.ReadModule (platformDll); var classHandlesMaybe = AllTypes (module).FirstOrDefault (t => t.FullName == "ObjCRuntime.Runtime/ClassHandles"); - Assert.NotNull (classHandlesMaybe, "Couldn't find ClassHandles type."); + Assert.That (classHandlesMaybe, Is.Not.Null, "Couldn't find ClassHandles type."); var classHandles = classHandlesMaybe!; if (!rewriteHandles) { // NB: there is always at least one field named "unused" @@ -103,7 +104,7 @@ public void ClassRewriterTest (ApplePlatform platform, bool rewriteHandles) // NB: there is always at least one field named "unused" Assert.That (classHandles.HasFields && classHandles.Fields.Count () > 1, "There are no fields in ClassHandles - rewriter did nothing."); var field = classHandles.Fields.FirstOrDefault (f => f.Name.Contains ("SomeObj")); - Assert.IsNotNull (field, "Didn't find a field for 'SomeObj'"); + Assert.That (field, Is.Not.Null, "Didn't find a field for 'SomeObj'"); } } diff --git a/tests/dotnet/UnitTests/ResourcePrefixTest.cs b/tests/dotnet/UnitTests/ResourcePrefixTest.cs index f4860ff1489e..60836d12716d 100644 --- a/tests/dotnet/UnitTests/ResourcePrefixTest.cs +++ b/tests/dotnet/UnitTests/ResourcePrefixTest.cs @@ -17,7 +17,7 @@ public void ResourcePrefix_DefaultValues () foreach (var platform in platforms) { // Act & Assert var defaultValue = GetResourcePrefix (platform.AsString ().ToLower ()); - Assert.AreEqual ("Resources", defaultValue, $"Default value for {platform} should be 'Resources'"); + Assert.That (defaultValue, Is.EqualTo ("Resources"), $"Default value for {platform} should be 'Resources'"); } } @@ -33,7 +33,7 @@ public void ResourcePrefix_AppBundleResourcePrefix () var value = GetResourcePrefix (platform.AsString ().ToLower (), ("AppBundleResourcePrefix", customPrefix)); // Assert - Assert.AreEqual (customPrefix, value, $"{platform}: AppBundleResourcePrefix should be used"); + Assert.That (value, Is.EqualTo (customPrefix), $"{platform}: AppBundleResourcePrefix should be used"); } } @@ -48,27 +48,27 @@ public void ResourcePrefix_PlatformSpecific () // iOS and tvOS use IPhoneResourcePrefix if (Configuration.include_ios) { var iOSValue = GetResourcePrefix ("ios", ("IPhoneResourcePrefix", customPrefix)); - Assert.AreEqual (customPrefix, iOSValue, "iOS should use IPhoneResourcePrefix"); + Assert.That (iOSValue, Is.EqualTo (customPrefix), "iOS should use IPhoneResourcePrefix"); } if (Configuration.include_tvos) { var tvOSValue = GetResourcePrefix ("tvos", ("IPhoneResourcePrefix", customPrefix)); - Assert.AreEqual (customPrefix, tvOSValue, "tvOS should use IPhoneResourcePrefix"); + Assert.That (tvOSValue, Is.EqualTo (customPrefix), "tvOS should use IPhoneResourcePrefix"); } // Mac Catalyst uses IPhoneResourcePrefix if (Configuration.include_maccatalyst) { var macCatalystValue = GetResourcePrefix ("maccatalyst", ("IPhoneResourcePrefix", customPrefix)); - Assert.AreEqual (customPrefix, macCatalystValue, "Mac Catalyst should use IPhoneResourcePrefix"); + Assert.That (macCatalystValue, Is.EqualTo (customPrefix), "Mac Catalyst should use IPhoneResourcePrefix"); } // macOS can use either XamMacResourcePrefix or MonoMacResourcePrefix if (Configuration.include_mac) { var macOSXamValue = GetResourcePrefix ("macos", ("XamMacResourcePrefix", customPrefix)); - Assert.AreEqual (customPrefix, macOSXamValue, "macOS should use XamMacResourcePrefix"); + Assert.That (macOSXamValue, Is.EqualTo (customPrefix), "macOS should use XamMacResourcePrefix"); var macOSMonoValue = GetResourcePrefix ("macos", ("MonoMacResourcePrefix", customPrefix)); - Assert.AreEqual (customPrefix, macOSMonoValue, "macOS should use MonoMacResourcePrefix"); + Assert.That (macOSMonoValue, Is.EqualTo (customPrefix), "macOS should use MonoMacResourcePrefix"); } } @@ -86,7 +86,7 @@ public void ResourcePrefix_Precedence () var iOSValue = GetResourcePrefix ("ios", ("AppBundleResourcePrefix", appBundlePrefix), ("IPhoneResourcePrefix", platformPrefix)); - Assert.AreEqual (appBundlePrefix, iOSValue, "iOS should prioritize AppBundleResourcePrefix over IPhoneResourcePrefix"); + Assert.That (iOSValue, Is.EqualTo (appBundlePrefix), "iOS should prioritize AppBundleResourcePrefix over IPhoneResourcePrefix"); } // tvOS - AppBundleResourcePrefix should take precedence over IPhoneResourcePrefix @@ -94,7 +94,7 @@ public void ResourcePrefix_Precedence () var tvOSValue = GetResourcePrefix ("tvos", ("AppBundleResourcePrefix", appBundlePrefix), ("IPhoneResourcePrefix", platformPrefix)); - Assert.AreEqual (appBundlePrefix, tvOSValue, "tvOS should prioritize AppBundleResourcePrefix over IPhoneResourcePrefix"); + Assert.That (tvOSValue, Is.EqualTo (appBundlePrefix), "tvOS should prioritize AppBundleResourcePrefix over IPhoneResourcePrefix"); } // Mac Catalyst - AppBundleResourcePrefix should take precedence over IPhoneResourcePrefix @@ -102,7 +102,7 @@ public void ResourcePrefix_Precedence () var macCatalystValue = GetResourcePrefix ("maccatalyst", ("AppBundleResourcePrefix", appBundlePrefix), ("IPhoneResourcePrefix", platformPrefix)); - Assert.AreEqual (appBundlePrefix, macCatalystValue, "Mac Catalyst should prioritize AppBundleResourcePrefix over IPhoneResourcePrefix"); + Assert.That (macCatalystValue, Is.EqualTo (appBundlePrefix), "Mac Catalyst should prioritize AppBundleResourcePrefix over IPhoneResourcePrefix"); } // macOS - AppBundleResourcePrefix should take precedence over XamMacResourcePrefix @@ -110,13 +110,13 @@ public void ResourcePrefix_Precedence () var macOSXamValue = GetResourcePrefix ("macos", ("AppBundleResourcePrefix", appBundlePrefix), ("XamMacResourcePrefix", platformPrefix)); - Assert.AreEqual (appBundlePrefix, macOSXamValue, "macOS should prioritize AppBundleResourcePrefix over XamMacResourcePrefix"); + Assert.That (macOSXamValue, Is.EqualTo (appBundlePrefix), "macOS should prioritize AppBundleResourcePrefix over XamMacResourcePrefix"); // macOS - AppBundleResourcePrefix should take precedence over MonoMacResourcePrefix var macOSMonoValue = GetResourcePrefix ("macos", ("AppBundleResourcePrefix", appBundlePrefix), ("MonoMacResourcePrefix", platformPrefix)); - Assert.AreEqual (appBundlePrefix, macOSMonoValue, "macOS should prioritize AppBundleResourcePrefix over MonoMacResourcePrefix"); + Assert.That (macOSMonoValue, Is.EqualTo (appBundlePrefix), "macOS should prioritize AppBundleResourcePrefix over MonoMacResourcePrefix"); } } diff --git a/tests/dotnet/UnitTests/TemplateProjectTest.cs b/tests/dotnet/UnitTests/TemplateProjectTest.cs index ea4318b9294f..dfa469bbd044 100644 --- a/tests/dotnet/UnitTests/TemplateProjectTest.cs +++ b/tests/dotnet/UnitTests/TemplateProjectTest.cs @@ -177,8 +177,8 @@ public void NoBundleIdentifierError (ApplePlatform platform) var properties = GetDefaultProperties (); var result = DotNet.AssertBuildFailure (project_path, properties); var errors = BinLog.GetBuildLogErrors (result.BinLogPath).ToArray (); - Assert.AreEqual (1, errors.Length, "Errors"); - Assert.AreEqual ("A bundle identifier is required. Either add an 'ApplicationId' property in the project file, or add a 'CFBundleIdentifier' entry in the project's Info.plist file.", errors [0].Message); + Assert.That (errors.Length, Is.EqualTo (1), "Errors"); + Assert.That (errors [0].Message, Is.EqualTo ("A bundle identifier is required. Either add an 'ApplicationId' property in the project file, or add a 'CFBundleIdentifier' entry in the project's Info.plist file.")); } } } diff --git a/tests/dotnet/UnitTests/TemplateTest.cs b/tests/dotnet/UnitTests/TemplateTest.cs index 11da53ac3e5a..24c9e1d54dca 100644 --- a/tests/dotnet/UnitTests/TemplateTest.cs +++ b/tests/dotnet/UnitTests/TemplateTest.cs @@ -227,7 +227,7 @@ public void CreateAndBuildProjectTemplate (TemplateInfo info) var platform = info.Platform; var runtimeIdentifiers = GetDefaultRuntimeIdentifier (platform); - Assert.IsTrue (CanExecute (info.Platform, runtimeIdentifiers), "Must be executable to execute!"); + Assert.That (CanExecute (info.Platform, runtimeIdentifiers), Is.True, "Must be executable to execute!"); // First add some code to exit the template if it launches successfully. InsertCodeToExitAppAfterLaunch (language, outputDir); @@ -286,7 +286,7 @@ bool IsMatching (TemplateLanguage lang, TemplateLanguage? value) if (info.Execute) { var runtimeIdentifiers = GetDefaultRuntimeIdentifier (platform); - Assert.IsTrue (CanExecute (info.Platform, runtimeIdentifiers), "Must be executable to execute!"); + Assert.That (CanExecute (info.Platform, runtimeIdentifiers), Is.True, "Must be executable to execute!"); // First add some code to exit the template if it launches successfully. InsertCodeToExitAppAfterLaunch (language, outputDir); @@ -333,7 +333,7 @@ static void InsertCSharpCodeToExitAppAfterLaunch (string outputDir) var modifiedMainContents = mainContents.Replace ("// This is the main entry point of the application.", exitSampleWithSuccess); - Assert.AreNotEqual (modifiedMainContents, mainContents, "Failed to modify the main content"); + Assert.That (mainContents, Is.Not.EqualTo (modifiedMainContents), "Failed to modify the main content"); File.WriteAllText (mainFile, modifiedMainContents); } @@ -349,7 +349,7 @@ static void InsertFSharpCodeToExitAppAfterLaunch (string outputDir) var modifiedMainContents = mainContents.Replace ("// This is the main entry point of the application.", exitSampleWithSuccess); - Assert.AreNotEqual (modifiedMainContents, mainContents, "Failed to modify the main content"); + Assert.That (mainContents, Is.Not.EqualTo (modifiedMainContents), "Failed to modify the main content"); File.WriteAllText (mainFile, modifiedMainContents); } @@ -367,7 +367,7 @@ End Sub var modifiedMainContents = mainContents.Replace ("' This is the main entry point of the application.", exitSampleWithSuccess); - Assert.AreNotEqual (modifiedMainContents, mainContents, "Failed to modify the main content"); + Assert.That (mainContents, Is.Not.EqualTo (modifiedMainContents), "Failed to modify the main content"); File.WriteAllText (mainFile, modifiedMainContents); } } diff --git a/tests/dotnet/UnitTests/TestBaseClass.cs b/tests/dotnet/UnitTests/TestBaseClass.cs index 19e3511ada80..e421218252eb 100644 --- a/tests/dotnet/UnitTests/TestBaseClass.cs +++ b/tests/dotnet/UnitTests/TestBaseClass.cs @@ -492,7 +492,7 @@ public static StringBuilder AssertExecute (string executable, string [] argument Console.WriteLine ($"'{executable} {StringUtils.FormatArguments (arguments)}' exited with exit code {rv}:"); Console.WriteLine ("\t" + output.ToString ().Replace ("\n", "\n\t").TrimEnd (new char [] { '\n', '\t' })); } - Assert.AreEqual (0, rv, $"Unable to execute '{executable} {StringUtils.FormatArguments (arguments)}': exit code {rv}"); + Assert.That (rv, Is.EqualTo (0), $"Unable to execute '{executable} {StringUtils.FormatArguments (arguments)}': exit code {rv}"); return output; } @@ -528,9 +528,9 @@ protected bool TryGetEntitlements (string nativeExecutable, [NotNullWhen (true)] nativeExecutable }; var rv = ExecutionHelper.Execute ("codesign", args, out var codesignOutput, TimeSpan.FromSeconds (15)); - Assert.AreEqual (0, rv, $"'codesign {string.Join (" ", args)}' failed:\n{codesignOutput}"); + Assert.That (rv, Is.EqualTo (0), $"'codesign {string.Join (" ", args)}' failed:\n{codesignOutput}"); if (File.Exists (entitlementsPath)) { - entitlements = PDictionary.FromFile (entitlementsPath); + entitlements = PDictionary.OpenFile (entitlementsPath); return entitlements is not null; } entitlements = null; diff --git a/tests/dotnet/UnitTests/WindowsTest.cs b/tests/dotnet/UnitTests/WindowsTest.cs index d546af38e4a9..a3fe051dbd38 100644 --- a/tests/dotnet/UnitTests/WindowsTest.cs +++ b/tests/dotnet/UnitTests/WindowsTest.cs @@ -376,21 +376,21 @@ public void RemoteTest (ApplePlatform platform, string runtimeIdentifiers) // Open the zipped app bundle and get the Info.plist using var zip = ZipFile.OpenRead (zippedAppBundlePath); ZipHelpers.DumpZipFile (zip, zippedAppBundlePath); - var infoPlistEntry = zip.Entries.SingleOrDefault (v => v.Name == "Info.plist")!; - Assert.NotNull (infoPlistEntry, "Info.plist"); + var infoPlistEntry = zip.Entries.SingleOrDefault (v => v.Name == "Info.plist"); + Assert.That (infoPlistEntry, Is.Not.Null, "Info.plist"); // Parse the Info.plist // PDictionary.FromStream requires a seekable stream, but the zip stream isn't seekable, so copy to a // MemoryStream and use that. Info.plist files aren't big, so this shouldn't become a memory consumption problem. - using var memoryStream = new MemoryStream ((int) infoPlistEntry.Length); + using var memoryStream = new MemoryStream ((int) infoPlistEntry!.Length); using var plistStream = infoPlistEntry.Open (); plistStream.CopyTo (memoryStream); var infoPlist = (PDictionary) PDictionary.FromStream (memoryStream)!; - Assert.AreEqual ("com.xamarin.mysimpleapp", infoPlist.GetString ("CFBundleIdentifier").Value, "CFBundleIdentifier"); - Assert.AreEqual ("MySimpleApp", infoPlist.GetString ("CFBundleDisplayName").Value, "CFBundleDisplayName"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleVersion").Value, "CFBundleVersion"); - Assert.AreEqual ("3.14", infoPlist.GetString ("CFBundleShortVersionString").Value, "CFBundleShortVersionString"); + Assert.That (infoPlist.GetString ("CFBundleIdentifier").Value, Is.EqualTo ("com.xamarin.mysimpleapp"), "CFBundleIdentifier"); + Assert.That (infoPlist.GetString ("CFBundleDisplayName").Value, Is.EqualTo ("MySimpleApp"), "CFBundleDisplayName"); + Assert.That (infoPlist.GetString ("CFBundleVersion").Value, Is.EqualTo ("3.14"), "CFBundleVersion"); + Assert.That (infoPlist.GetString ("CFBundleShortVersionString").Value, Is.EqualTo ("3.14"), "CFBundleShortVersionString"); //Validate that the output assemblies report file with the list of local assemblies, lengths and MVIDs has been created var outputAssembliesReportFileName = "OutputAssembliesReport.txt"; @@ -427,7 +427,7 @@ public void RemoteTest (ApplePlatform platform, string runtimeIdentifiers) Guid mvid = metadataReader.GetGuid (metadataReader.GetModuleDefinition ().Mvid); var fileWasUpdated = fileInfo.Length != localInfo.length || mvid != localInfo.mvid; - Assert.IsTrue (fileWasUpdated, $"The file '{fileName}' is identical to the one present in the output assemblies report file '{outputAssembliesReportFile}'"); + Assert.That (fileWasUpdated, Is.True, $"The file '{fileName}' is identical to the one present in the output assemblies report file '{outputAssembliesReportFile}'"); } } } diff --git a/tests/dotnet/UnitTests/XcodeProjectTests.cs b/tests/dotnet/UnitTests/XcodeProjectTests.cs index 2d213de9203f..aab50fe70c93 100644 --- a/tests/dotnet/UnitTests/XcodeProjectTests.cs +++ b/tests/dotnet/UnitTests/XcodeProjectTests.cs @@ -32,8 +32,7 @@ void AssertXcFrameworkOutput (ApplePlatform platform, string testDir, string xco Assert.That (expectedXcodeFxOutput, Does.Exist, $"Expected xcframework output '{expectedXcodeFxOutput}' did not exist."); } else { var resourcesZip = Path.Combine (testDir, "bin", config, platform.ToFramework (), $"{TestName}.resources.zip"); - Assert.Contains ($"{xcodeProjName}{platform.AsString ()}.xcframework/Info.plist", ZipHelpers.List (resourcesZip), - $"Expected xcframework output was not found in '{resourcesZip}'."); + Assert.That (ZipHelpers.List (resourcesZip), Does.Contain ($"{xcodeProjName}{platform.AsString ()}.xcframework/Info.plist"), $"Expected xcframework output was not found in '{resourcesZip}'."); } } @@ -66,7 +65,7 @@ public void BuildAppiOS (string projConfig, string rid) Assert.That (appDir, Does.Exist, $"Expected app dir '{appDir}' did not exist."); var appContent = Directory.GetFiles (appDir, "*", SearchOption.AllDirectories); var expectedAppOutput = Path.Combine (testDir, "bin", projConfig, platform.ToFramework (), rid, $"{TestName}.app", "Frameworks", $"{xcodeProjName}.framework", "Info.plist"); - Assert.Contains (expectedAppOutput, appContent, $"Expected framework output '{expectedAppOutput}' did not exist."); + Assert.That (appContent, Does.Contain (expectedAppOutput), $"Expected framework output '{expectedAppOutput}' did not exist."); } @@ -189,7 +188,7 @@ public void PackBinding (ApplePlatform platform) zipContent = ZipHelpers.ListInnerZip (expectedNupkgOutput, $"lib/{tfm}/{TestName}.resources.zip"); expectedFxPath = $"{xcodeProjName}{platform.AsString ()}.xcframework/Info.plist"; } - Assert.Contains (expectedFxPath, zipContent, $"Expected xcframework output was not found in '{expectedNupkgOutput}'."); + Assert.That (zipContent, Does.Contain (expectedFxPath), $"Expected xcframework output was not found in '{expectedNupkgOutput}'."); } [Test] @@ -241,7 +240,7 @@ public void BuildIncremental (ApplePlatform platform) AssertTargetExecuted (allTargets, "_BuildXcodeProjects", "Third _BuildXcodeProjects"); Assert.That (expectedXcodeFxOutput, Does.Exist, $"Expected xcframework output '{expectedXcodeFxOutput}' did not exist."); var outputFxThirdWriteTime = File.GetLastWriteTime (expectedXcodeFxOutput); - Assert.IsTrue (outputFxThirdWriteTime > outputFxFirstWriteTime, $"Expected '{outputFxThirdWriteTime}' write time of '{outputFxThirdWriteTime}' to be greater than first write '{outputFxFirstWriteTime}'"); + Assert.That (outputFxThirdWriteTime, Is.GreaterThan (outputFxFirstWriteTime), $"Expected '{expectedXcodeFxOutput}' third write time '{outputFxThirdWriteTime}' to be greater than first write '{outputFxFirstWriteTime}'"); } [Test] @@ -323,7 +322,7 @@ public void BuildMultiTargeting () var existingProjContent = File.ReadAllText (proj); var newProjContent = existingProjContent.Replace ($"{templatePlatform.ToFramework ()}", tfxs); File.WriteAllText (proj, newProjContent); - StringAssert.Contains (tfxs, File.ReadAllText (proj)); + Assert.That (File.ReadAllText (proj), Does.Contain (tfxs)); var xcodeProjName = "TemplateFx"; var xcodeProjDirSrc = Path.Combine (XCodeTestProjectDir, xcodeProjName); diff --git a/tests/dotnet/UnitTests/XcodeVersionTest.cs b/tests/dotnet/UnitTests/XcodeVersionTest.cs index a365af92f75e..301eb5e57fe0 100644 --- a/tests/dotnet/UnitTests/XcodeVersionTest.cs +++ b/tests/dotnet/UnitTests/XcodeVersionTest.cs @@ -35,16 +35,11 @@ public void Test (ApplePlatform platform, string xcodePath, Version xcodeVersion Clean (project_path); var properties = GetDefaultProperties (runtimeIdentifiers); properties ["BundleOriginalResources"] = "true"; // this prevents a different and unrelated error message from failing to build library projects + properties ["XcodeLocation"] = xcodePath; - var existingDeveloperDir = Environment.GetEnvironmentVariable ("MD_APPLE_SDK_ROOT"); - try { - Environment.SetEnvironmentVariable ("MD_APPLE_SDK_ROOT", Path.GetDirectoryName (Path.GetDirectoryName (xcodePath))); - var rv = DotNet.AssertBuildFailure (project_path, properties); - var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); - AssertErrorMessages (errors, $"This version of .NET for {platform.AsString ()} ({Configuration.GetNuGetVersionNoMetadata (platform)}) requires Xcode {Configuration.XcodeVersion}. The current version of Xcode is {xcodeVersion}. Either install Xcode {Configuration.XcodeVersion}, or use a different version of .NET for {platform.AsString ()}. See https://aka.ms/xcode-requirement for more information."); - } finally { - Environment.SetEnvironmentVariable ("MD_APPLE_SDK_ROOT", existingDeveloperDir); - } + var rv = DotNet.AssertBuildFailure (project_path, properties); + var errors = BinLog.GetBuildLogErrors (rv.BinLogPath).ToArray (); + AssertErrorMessages (errors, $"This version of .NET for {platform.AsString ()} ({Configuration.GetNuGetVersionNoMetadata (platform)}) requires Xcode {Configuration.XcodeVersion}. The current version of Xcode is {xcodeVersion}. Either install Xcode {Configuration.XcodeVersion}, or use a different version of .NET for {platform.AsString ()}. See https://aka.ms/xcode-requirement for more information."); } } } diff --git a/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-interpreter-preservedapis.txt b/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-interpreter-preservedapis.txt index 52362f2102f1..7342f8307492 100644 --- a/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-interpreter-preservedapis.txt +++ b/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-interpreter-preservedapis.txt @@ -121,7 +121,6 @@ Microsoft.MacCatalyst.dll:Foundation.NSObject..ctor() Microsoft.MacCatalyst.dll:Foundation.NSObject..ctor(Foundation.NSObjectFlag) Microsoft.MacCatalyst.dll:Foundation.NSObject..ctor(ObjCRuntime.NativeHandle, System.Boolean) Microsoft.MacCatalyst.dll:Foundation.NSObject..ctor(ObjCRuntime.NativeHandle) -Microsoft.MacCatalyst.dll:Foundation.NSObject.AllocateData() Microsoft.MacCatalyst.dll:Foundation.NSObject.AllocIfNeeded() Microsoft.MacCatalyst.dll:Foundation.NSObject.ClearHandle() Microsoft.MacCatalyst.dll:Foundation.NSObject.ConformsToProtocol(ObjCRuntime.NativeHandle) @@ -148,11 +147,9 @@ Microsoft.MacCatalyst.dll:Foundation.NSObject.get_Handle() Microsoft.MacCatalyst.dll:Foundation.NSObject.get_InFinalizerQueue() Microsoft.MacCatalyst.dll:Foundation.NSObject.get_IsDirectBinding() Microsoft.MacCatalyst.dll:Foundation.NSObject.get_IsRegisteredToggleRef() -Microsoft.MacCatalyst.dll:Foundation.NSObject.get_SuperHandle() Microsoft.MacCatalyst.dll:Foundation.NSObject.GetData() Microsoft.MacCatalyst.dll:Foundation.NSObject.GetHashCode() Microsoft.MacCatalyst.dll:Foundation.NSObject.GetNativeHash() -Microsoft.MacCatalyst.dll:Foundation.NSObject.GetSuper() Microsoft.MacCatalyst.dll:Foundation.NSObject.Initialize() Microsoft.MacCatalyst.dll:Foundation.NSObject.InitializeHandle(ObjCRuntime.NativeHandle, System.String, System.Boolean) Microsoft.MacCatalyst.dll:Foundation.NSObject.InitializeHandle(ObjCRuntime.NativeHandle, System.String) @@ -160,7 +157,6 @@ Microsoft.MacCatalyst.dll:Foundation.NSObject.InitializeObject(System.Boolean) Microsoft.MacCatalyst.dll:Foundation.NSObject.InvokeConformsToProtocol(ObjCRuntime.NativeHandle) Microsoft.MacCatalyst.dll:Foundation.NSObject.IsEqual(Foundation.NSObject) Microsoft.MacCatalyst.dll:Foundation.NSObject.IsProtocol(System.Type, System.IntPtr) -Microsoft.MacCatalyst.dll:Foundation.NSObject.RecreateDataHandle() Microsoft.MacCatalyst.dll:Foundation.NSObject.ReleaseManagedRef() Microsoft.MacCatalyst.dll:Foundation.NSObject.set_disposed(System.Boolean) Microsoft.MacCatalyst.dll:Foundation.NSObject.set_flags(Foundation.NSObject/Flags) @@ -199,16 +195,10 @@ Microsoft.MacCatalyst.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NS Microsoft.MacCatalyst.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/XamarinGCHandleFlags::InitialSet Microsoft.MacCatalyst.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/XamarinGCHandleFlags::None Microsoft.MacCatalyst.dll:Foundation.NSObjectData -Microsoft.MacCatalyst.dll:Foundation.NSObjectData* Foundation.NSObject::__data_for_mono Microsoft.MacCatalyst.dll:Foundation.NSObjectData* Foundation.NSObjectDataHandle::Data() Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle -Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle Foundation.NSObject::data_handle Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle..ctor() -Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle..ctor(System.IntPtr) Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle.get_Data() -Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle.get_IsInvalid() -Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle.Invalidate() -Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle.ReleaseHandle() Microsoft.MacCatalyst.dll:Foundation.NSObjectFlag Microsoft.MacCatalyst.dll:Foundation.NSObjectFlag Foundation.NSObjectFlag::Empty Microsoft.MacCatalyst.dll:Foundation.NSString @@ -259,6 +249,12 @@ Microsoft.MacCatalyst.dll:Foundation.RegisterAttribute.get_IsStubClass() Microsoft.MacCatalyst.dll:Foundation.RegisterAttribute.get_IsWrapper() Microsoft.MacCatalyst.dll:Foundation.RegisterAttribute.get_Name() Microsoft.MacCatalyst.dll:Foundation.RegisterAttribute.get_SkipRegistration() +Microsoft.MacCatalyst.dll:Foundation.TrackedMemory +Microsoft.MacCatalyst.dll:Foundation.TrackedMemory..ctor(System.UIntPtr) +Microsoft.MacCatalyst.dll:Foundation.TrackedMemory.CreateHandle(Foundation.NSObject) +Microsoft.MacCatalyst.dll:Foundation.TrackedMemory.Finalize() +Microsoft.MacCatalyst.dll:Foundation.TrackedMemory.get_Value() +Microsoft.MacCatalyst.dll:Foundation.TrackedMemory.set_Value(System.IntPtr) Microsoft.MacCatalyst.dll:Foundation.You_Should_Not_Call_base_In_This_Method Microsoft.MacCatalyst.dll:Foundation.You_Should_Not_Call_base_In_This_Method..ctor() Microsoft.MacCatalyst.dll:ObjCRuntime.__Registrar__ @@ -445,29 +441,29 @@ Microsoft.MacCatalyst.dll:ObjCRuntime.MarshalObjectiveCExceptionMode ObjCRuntime Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.bool_objc_msgSend_IntPtr(System.IntPtr, System.IntPtr, System.IntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.bool_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_IntPtr(System.IntPtr, System.IntPtr, System.IntPtr) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_IntPtr(ObjCRuntime.ObjCSuper*, System.IntPtr, System.IntPtr) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.CGRect_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.CGRect_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.CGRect_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend_CGRect(System.IntPtr, System.IntPtr, CoreGraphics.CGRect) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper_CGRect(System.IntPtr, System.IntPtr, CoreGraphics.CGRect) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper_CGRect(ObjCRuntime.ObjCSuper*, System.IntPtr, CoreGraphics.CGRect) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, ObjCRuntime.NativeHandle, System.Byte) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_UIntPtr(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, System.UIntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle_UIntPtr(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, System.UIntPtr) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle_UIntPtr(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle, System.UIntPtr) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Method Microsoft.MacCatalyst.dll:ObjCRuntime.Method.get_ConstructorTrampoline() Microsoft.MacCatalyst.dll:ObjCRuntime.Method.get_DoubleTrampoline() @@ -502,8 +498,6 @@ Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObject::class_pt Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObject::ClassHandle() Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObject::handle() Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObject::Handle() -Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObject::SuperHandle() -Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObjectData::classHandle Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObjectData::handle Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSString::class_ptr Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSString::ClassHandle() @@ -513,6 +507,8 @@ Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.DisposableObject: Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.DisposableObject::Handle() Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.INativeObject::Handle() Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.NativeHandle::Zero +Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.ObjCSuper::classHandle +Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.ObjCSuper::receiver Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.Protocol::handle Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.Protocol::Handle() Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.Runtime/ClassHandles::unused @@ -558,6 +554,8 @@ Microsoft.MacCatalyst.dll:ObjCRuntime.ObjCException.get_Name() Microsoft.MacCatalyst.dll:ObjCRuntime.ObjCException.get_NSException() Microsoft.MacCatalyst.dll:ObjCRuntime.ObjCException.get_Reason() Microsoft.MacCatalyst.dll:ObjCRuntime.ObjCException.ToString() +Microsoft.MacCatalyst.dll:ObjCRuntime.ObjCSuper +Microsoft.MacCatalyst.dll:ObjCRuntime.ObjCSuper..ctor(Foundation.NSObject) Microsoft.MacCatalyst.dll:ObjCRuntime.Protocol Microsoft.MacCatalyst.dll:ObjCRuntime.Protocol._Xamarin_ConstructINativeObject(ObjCRuntime.NativeHandle, System.Boolean) Microsoft.MacCatalyst.dll:ObjCRuntime.Protocol..cctor() @@ -1215,8 +1213,6 @@ Microsoft.MacCatalyst.dll:System.Boolean Foundation.NSObject::IsDirectBinding() Microsoft.MacCatalyst.dll:System.Boolean Foundation.NSObject::IsRegisteredToggleRef() Microsoft.MacCatalyst.dll:System.Boolean Foundation.NSObject::RemoveFromObjectMap() Microsoft.MacCatalyst.dll:System.Boolean Foundation.NSObject/NSObject_Disposer::draining -Microsoft.MacCatalyst.dll:System.Boolean Foundation.NSObjectDataHandle::invalidated -Microsoft.MacCatalyst.dll:System.Boolean Foundation.NSObjectDataHandle::IsInvalid() Microsoft.MacCatalyst.dll:System.Boolean Foundation.ProtocolAttribute::k__BackingField Microsoft.MacCatalyst.dll:System.Boolean Foundation.ProtocolAttribute::k__BackingField Microsoft.MacCatalyst.dll:System.Boolean Foundation.ProtocolAttribute::IsInformal() @@ -1337,7 +1333,10 @@ Microsoft.MacCatalyst.dll:System.Int64 Foundation.NSComparisonResult::value__ Microsoft.MacCatalyst.dll:System.IntPtr CoreFoundation.CFArray::_CFNullHandle() Microsoft.MacCatalyst.dll:System.IntPtr CoreFoundation.CFRange::len Microsoft.MacCatalyst.dll:System.IntPtr CoreFoundation.CFRange::loc +Microsoft.MacCatalyst.dll:System.IntPtr Foundation.NSObject::__data Microsoft.MacCatalyst.dll:System.IntPtr Foundation.NSObject/NSObject_Disposer::class_ptr +Microsoft.MacCatalyst.dll:System.IntPtr Foundation.TrackedMemory::k__BackingField +Microsoft.MacCatalyst.dll:System.IntPtr Foundation.TrackedMemory::Value() Microsoft.MacCatalyst.dll:System.IntPtr ObjCRuntime.AdoptsAttribute::ProtocolHandle() Microsoft.MacCatalyst.dll:System.IntPtr ObjCRuntime.BlockCollector::block Microsoft.MacCatalyst.dll:System.IntPtr ObjCRuntime.Libraries/CoreFoundation::Handle @@ -1500,8 +1499,11 @@ Microsoft.MacCatalyst.dll:System.Reflection.MethodBase Registrar.Registrar::invo Microsoft.MacCatalyst.dll:System.Reflection.MethodBase Registrar.Registrar/ObjCMethod::Method Microsoft.MacCatalyst.dll:System.Reflection.PropertyInfo Registrar.Registrar/ObjCProperty::Property Microsoft.MacCatalyst.dll:System.Reflection.TypeFilter Registrar.SharedDynamic/<>c::<>9__0_0 +Microsoft.MacCatalyst.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 Foundation.NSObject::data_table +Microsoft.MacCatalyst.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 Foundation.NSObject::super_map Microsoft.MacCatalyst.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 ObjCRuntime.Runtime::block_lifetime_table Microsoft.MacCatalyst.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 ObjCRuntime.Class::assembly_to_name +Microsoft.MacCatalyst.dll:System.Runtime.InteropServices.GCHandle Foundation.TrackedMemory::handle Microsoft.MacCatalyst.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::height Microsoft.MacCatalyst.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::width Microsoft.MacCatalyst.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::x @@ -2724,14 +2726,12 @@ System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.Runtim System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.RuntimeFeature::IsDynamicCodeCompiled() System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.RuntimeFeature::IsDynamicCodeSupported() System.Private.CoreLib.dll:System.Boolean System.Runtime.DependentHandle::IsAllocated() -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::_isClosed -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::IsClosed() -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::IsInvalid() System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::BestFitMapping System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::ExactSpelling System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::PreserveSig System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::SetLastError System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::ThrowOnUnmappableChar +System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.GCHandle::IsAllocated() System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.SafeHandleMarshaller`1/ManagedToUnmanagedIn::_addRefd System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.SafeHandleMarshaller`1/ManagedToUnmanagedOut::_initialized System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.Utf8StringMarshaller/ManagedToUnmanagedIn::_allocated @@ -6949,7 +6949,6 @@ System.Private.CoreLib.dll:System.IntPtr System.Reflection.RuntimePropertyInfo:: System.Private.CoreLib.dll:System.IntPtr System.Reflection.RuntimePropertyInfo::prop System.Private.CoreLib.dll:System.IntPtr System.Runtime.CompilerServices.QCallAssembly::_assembly System.Private.CoreLib.dll:System.IntPtr System.Runtime.CompilerServices.QCallTypeHandle::_handle -System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.CriticalHandle::handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.GCHandle::_handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.SafeHandle::handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.WeakGCHandle`1::_handle @@ -10849,15 +10848,6 @@ System.Private.CoreLib.dll:System.Runtime.InteropServices.CollectionsMarshal System.Private.CoreLib.dll:System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault`2(System.Collections.Generic.Dictionary`2, TKey, out System.Boolean&) System.Private.CoreLib.dll:System.Runtime.InteropServices.ComImportAttribute System.Private.CoreLib.dll:System.Runtime.InteropServices.ComImportAttribute..ctor() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle..ctor(System.IntPtr) -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Cleanup() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Dispose() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Dispose(System.Boolean) -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Finalize() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.get_IsClosed() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.get_IsInvalid() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.ReleaseHandle() System.Private.CoreLib.dll:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute System.Private.CoreLib.dll:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute..ctor(System.Runtime.InteropServices.DllImportSearchPath) System.Private.CoreLib.dll:System.Runtime.InteropServices.DllImportAttribute @@ -10886,6 +10876,7 @@ System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Equals(System System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Equals(System.Runtime.InteropServices.GCHandle) System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Free() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.FromIntPtr(System.IntPtr) +System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.get_IsAllocated() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.get_Target() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.GetHandleValue(System.IntPtr) System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.GetHashCode() diff --git a/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-interpreter-size.txt b/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-interpreter-size.txt index c0eceeb55daf..23bdbd58a4b5 100644 --- a/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-interpreter-size.txt +++ b/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-interpreter-size.txt @@ -1,12 +1,12 @@ -AppBundleSize: 5,791,876 bytes (5,656.1 KB = 5.5 MB) +AppBundleSize: 5,789,578 bytes (5,653.9 KB = 5.5 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: Contents/_CodeSignature/CodeResources: 3,310 bytes (3.2 KB = 0.0 MB) -Contents/Info.plist: 1,105 bytes (1.1 KB = 0.0 MB) -Contents/MacOS/SizeTestApp: 4,567,200 bytes (4,460.2 KB = 4.4 MB) -Contents/MonoBundle/Microsoft.MacCatalyst.dll: 158,208 bytes (154.5 KB = 0.2 MB) +Contents/Info.plist: 1,119 bytes (1.1 KB = 0.0 MB) +Contents/MacOS/SizeTestApp: 4,565,424 bytes (4,458.4 KB = 4.4 MB) +Contents/MonoBundle/Microsoft.MacCatalyst.dll: 157,696 bytes (154.0 KB = 0.2 MB) Contents/MonoBundle/runtimeconfig.bin: 1,405 bytes (1.4 KB = 0.0 MB) Contents/MonoBundle/SizeTestApp.dll: 7,680 bytes (7.5 KB = 0.0 MB) -Contents/MonoBundle/System.Private.CoreLib.aotdata.arm64: 41,248 bytes (40.3 KB = 0.0 MB) +Contents/MonoBundle/System.Private.CoreLib.aotdata.arm64: 41,224 bytes (40.3 KB = 0.0 MB) Contents/MonoBundle/System.Private.CoreLib.dll: 998,400 bytes (975.0 KB = 1.0 MB) Contents/MonoBundle/System.Runtime.dll: 5,120 bytes (5.0 KB = 0.0 MB) Contents/MonoBundle/System.Runtime.InteropServices.dll: 8,192 bytes (8.0 KB = 0.0 MB) diff --git a/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-preservedapis.txt b/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-preservedapis.txt index 09e20015e7f9..d9b210cc8000 100644 --- a/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-preservedapis.txt +++ b/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-preservedapis.txt @@ -107,7 +107,6 @@ Microsoft.MacCatalyst.dll:Foundation.NSObject..ctor() Microsoft.MacCatalyst.dll:Foundation.NSObject..ctor(Foundation.NSObjectFlag) Microsoft.MacCatalyst.dll:Foundation.NSObject..ctor(ObjCRuntime.NativeHandle, System.Boolean) Microsoft.MacCatalyst.dll:Foundation.NSObject..ctor(ObjCRuntime.NativeHandle) -Microsoft.MacCatalyst.dll:Foundation.NSObject.AllocateData() Microsoft.MacCatalyst.dll:Foundation.NSObject.AllocIfNeeded() Microsoft.MacCatalyst.dll:Foundation.NSObject.ClearHandle() Microsoft.MacCatalyst.dll:Foundation.NSObject.ConformsToProtocol(ObjCRuntime.NativeHandle) @@ -133,18 +132,15 @@ Microsoft.MacCatalyst.dll:Foundation.NSObject.get_Handle() Microsoft.MacCatalyst.dll:Foundation.NSObject.get_InFinalizerQueue() Microsoft.MacCatalyst.dll:Foundation.NSObject.get_IsDirectBinding() Microsoft.MacCatalyst.dll:Foundation.NSObject.get_IsRegisteredToggleRef() -Microsoft.MacCatalyst.dll:Foundation.NSObject.get_SuperHandle() Microsoft.MacCatalyst.dll:Foundation.NSObject.GetData() Microsoft.MacCatalyst.dll:Foundation.NSObject.GetHashCode() Microsoft.MacCatalyst.dll:Foundation.NSObject.GetNativeHash() -Microsoft.MacCatalyst.dll:Foundation.NSObject.GetSuper() Microsoft.MacCatalyst.dll:Foundation.NSObject.Initialize() Microsoft.MacCatalyst.dll:Foundation.NSObject.InitializeHandle(ObjCRuntime.NativeHandle, System.String, System.Boolean) Microsoft.MacCatalyst.dll:Foundation.NSObject.InitializeHandle(ObjCRuntime.NativeHandle, System.String) Microsoft.MacCatalyst.dll:Foundation.NSObject.InitializeObject(System.Boolean) Microsoft.MacCatalyst.dll:Foundation.NSObject.InvokeConformsToProtocol(ObjCRuntime.NativeHandle) Microsoft.MacCatalyst.dll:Foundation.NSObject.IsEqual(Foundation.NSObject) -Microsoft.MacCatalyst.dll:Foundation.NSObject.RecreateDataHandle() Microsoft.MacCatalyst.dll:Foundation.NSObject.ReleaseManagedRef() Microsoft.MacCatalyst.dll:Foundation.NSObject.set_disposed(System.Boolean) Microsoft.MacCatalyst.dll:Foundation.NSObject.set_flags(Foundation.NSObject/Flags) @@ -182,16 +178,10 @@ Microsoft.MacCatalyst.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NS Microsoft.MacCatalyst.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/XamarinGCHandleFlags::InitialSet Microsoft.MacCatalyst.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/XamarinGCHandleFlags::None Microsoft.MacCatalyst.dll:Foundation.NSObjectData -Microsoft.MacCatalyst.dll:Foundation.NSObjectData* Foundation.NSObject::__data_for_mono Microsoft.MacCatalyst.dll:Foundation.NSObjectData* Foundation.NSObjectDataHandle::Data() Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle -Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle Foundation.NSObject::data_handle Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle..ctor() -Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle..ctor(System.IntPtr) Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle.get_Data() -Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle.get_IsInvalid() -Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle.Invalidate() -Microsoft.MacCatalyst.dll:Foundation.NSObjectDataHandle.ReleaseHandle() Microsoft.MacCatalyst.dll:Foundation.NSObjectFlag Microsoft.MacCatalyst.dll:Foundation.NSObjectFlag Foundation.NSObjectFlag::Empty Microsoft.MacCatalyst.dll:Foundation.ProtocolAttribute @@ -201,6 +191,12 @@ Microsoft.MacCatalyst.dll:Foundation.RegisterAttribute Microsoft.MacCatalyst.dll:Foundation.RegisterAttribute..ctor(System.String, System.Boolean) Microsoft.MacCatalyst.dll:Foundation.RegisterAttribute..ctor(System.String) Microsoft.MacCatalyst.dll:Foundation.RegisterAttribute.get_IsWrapper() +Microsoft.MacCatalyst.dll:Foundation.TrackedMemory +Microsoft.MacCatalyst.dll:Foundation.TrackedMemory..ctor(System.UIntPtr) +Microsoft.MacCatalyst.dll:Foundation.TrackedMemory.CreateHandle(Foundation.NSObject) +Microsoft.MacCatalyst.dll:Foundation.TrackedMemory.Finalize() +Microsoft.MacCatalyst.dll:Foundation.TrackedMemory.get_Value() +Microsoft.MacCatalyst.dll:Foundation.TrackedMemory.set_Value(System.IntPtr) Microsoft.MacCatalyst.dll:Foundation.You_Should_Not_Call_base_In_This_Method Microsoft.MacCatalyst.dll:Foundation.You_Should_Not_Call_base_In_This_Method..ctor() Microsoft.MacCatalyst.dll:ObjCRuntime.__Registrar__ @@ -353,17 +349,17 @@ Microsoft.MacCatalyst.dll:ObjCRuntime.MarshalObjectiveCExceptionMode ObjCRuntime Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.bool_objc_msgSend_IntPtr(System.IntPtr, System.IntPtr, System.IntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.bool_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_IntPtr(System.IntPtr, System.IntPtr, System.IntPtr) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_IntPtr(ObjCRuntime.ObjCSuper*, System.IntPtr, System.IntPtr) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.CGRect_objc_msgSend(System.IntPtr, System.IntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend_CGRect(System.IntPtr, System.IntPtr, CoreGraphics.CGRect) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, ObjCRuntime.NativeHandle, System.Byte) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_UIntPtr(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, System.UIntPtr) Microsoft.MacCatalyst.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) @@ -382,8 +378,6 @@ Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObject::class_pt Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObject::ClassHandle() Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObject::handle() Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObject::Handle() -Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObject::SuperHandle() -Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObjectData::classHandle Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle Foundation.NSObjectData::handle Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.Class::handle Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.Class::Handle() @@ -391,6 +385,8 @@ Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.DisposableObject: Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.DisposableObject::Handle() Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.INativeObject::Handle() Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.NativeHandle::Zero +Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.ObjCSuper::classHandle +Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.ObjCSuper::receiver Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.Runtime/ClassHandles::unused Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.Selector::handle Microsoft.MacCatalyst.dll:ObjCRuntime.NativeHandle ObjCRuntime.Selector::Handle() @@ -433,6 +429,8 @@ Microsoft.MacCatalyst.dll:ObjCRuntime.ObjCException.get_Name() Microsoft.MacCatalyst.dll:ObjCRuntime.ObjCException.get_NSException() Microsoft.MacCatalyst.dll:ObjCRuntime.ObjCException.get_Reason() Microsoft.MacCatalyst.dll:ObjCRuntime.ObjCException.ToString() +Microsoft.MacCatalyst.dll:ObjCRuntime.ObjCSuper +Microsoft.MacCatalyst.dll:ObjCRuntime.ObjCSuper..ctor(Foundation.NSObject) Microsoft.MacCatalyst.dll:ObjCRuntime.RegistrarHelper Microsoft.MacCatalyst.dll:ObjCRuntime.RegistrarHelper.ConstructINativeObject`1(System.Type, ObjCRuntime.NativeHandle, System.Boolean) Microsoft.MacCatalyst.dll:ObjCRuntime.RegistrarHelper.ConstructNSObject`1(System.Type, ObjCRuntime.NativeHandle) @@ -667,8 +665,6 @@ Microsoft.MacCatalyst.dll:System.Boolean Foundation.NSObject::InFinalizerQueue() Microsoft.MacCatalyst.dll:System.Boolean Foundation.NSObject::IsDirectBinding() Microsoft.MacCatalyst.dll:System.Boolean Foundation.NSObject::IsRegisteredToggleRef() Microsoft.MacCatalyst.dll:System.Boolean Foundation.NSObject/NSObject_Disposer::draining -Microsoft.MacCatalyst.dll:System.Boolean Foundation.NSObjectDataHandle::invalidated -Microsoft.MacCatalyst.dll:System.Boolean Foundation.NSObjectDataHandle::IsInvalid() Microsoft.MacCatalyst.dll:System.Boolean Foundation.ProtocolAttribute::k__BackingField Microsoft.MacCatalyst.dll:System.Boolean Foundation.RegisterAttribute::is_wrapper Microsoft.MacCatalyst.dll:System.Boolean Foundation.RegisterAttribute::IsWrapper() @@ -724,7 +720,10 @@ Microsoft.MacCatalyst.dll:System.Int32 ObjCRuntime.TransientString/Encoding::val Microsoft.MacCatalyst.dll:System.IntPtr CoreFoundation.CFArray::_CFNullHandle() Microsoft.MacCatalyst.dll:System.IntPtr CoreFoundation.CFRange::len Microsoft.MacCatalyst.dll:System.IntPtr CoreFoundation.CFRange::loc +Microsoft.MacCatalyst.dll:System.IntPtr Foundation.NSObject::__data Microsoft.MacCatalyst.dll:System.IntPtr Foundation.NSObject/NSObject_Disposer::class_ptr +Microsoft.MacCatalyst.dll:System.IntPtr Foundation.TrackedMemory::k__BackingField +Microsoft.MacCatalyst.dll:System.IntPtr Foundation.TrackedMemory::Value() Microsoft.MacCatalyst.dll:System.IntPtr ObjCRuntime.BlockCollector::block Microsoft.MacCatalyst.dll:System.IntPtr ObjCRuntime.Libraries/CoreFoundation::Handle Microsoft.MacCatalyst.dll:System.IntPtr ObjCRuntime.NativeHandle::handle @@ -855,8 +854,11 @@ Microsoft.MacCatalyst.dll:System.Object Foundation.NSObject/NSObject_Disposer::l Microsoft.MacCatalyst.dll:System.Object ObjCRuntime.Class::verification_lock Microsoft.MacCatalyst.dll:System.Object ObjCRuntime.Runtime::lock_obj Microsoft.MacCatalyst.dll:System.Reflection.Assembly Foundation.NSObject::PlatformAssembly +Microsoft.MacCatalyst.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 Foundation.NSObject::data_table +Microsoft.MacCatalyst.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 Foundation.NSObject::super_map Microsoft.MacCatalyst.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 ObjCRuntime.Runtime::block_lifetime_table Microsoft.MacCatalyst.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 ObjCRuntime.Class::assembly_to_name +Microsoft.MacCatalyst.dll:System.Runtime.InteropServices.GCHandle Foundation.TrackedMemory::handle Microsoft.MacCatalyst.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::height Microsoft.MacCatalyst.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::width Microsoft.MacCatalyst.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::x @@ -1951,14 +1953,12 @@ System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.Nullab System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::k__BackingField System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::WrapNonExceptionThrows() System.Private.CoreLib.dll:System.Boolean System.Runtime.DependentHandle::IsAllocated() -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::_isClosed -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::IsClosed() -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::IsInvalid() System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::BestFitMapping System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::ExactSpelling System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::PreserveSig System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::SetLastError System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::ThrowOnUnmappableChar +System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.GCHandle::IsAllocated() System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.SafeHandleMarshaller`1/ManagedToUnmanagedIn::_addRefd System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.SafeHandleMarshaller`1/ManagedToUnmanagedOut::_initialized System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.Utf8StringMarshaller/ManagedToUnmanagedIn::_allocated @@ -6024,7 +6024,6 @@ System.Private.CoreLib.dll:System.IntPtr System.Reflection.RuntimePropertyInfo:: System.Private.CoreLib.dll:System.IntPtr System.Reflection.RuntimePropertyInfo::prop System.Private.CoreLib.dll:System.IntPtr System.Runtime.CompilerServices.QCallAssembly::_assembly System.Private.CoreLib.dll:System.IntPtr System.Runtime.CompilerServices.QCallTypeHandle::_handle -System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.CriticalHandle::handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.GCHandle::_handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.SafeHandle::handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.WeakGCHandle`1::_handle @@ -8550,15 +8549,6 @@ System.Private.CoreLib.dll:System.Runtime.InteropServices.CollectionsMarshal System.Private.CoreLib.dll:System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault`2(System.Collections.Generic.Dictionary`2, TKey, out System.Boolean&) System.Private.CoreLib.dll:System.Runtime.InteropServices.ComImportAttribute System.Private.CoreLib.dll:System.Runtime.InteropServices.ComImportAttribute..ctor() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle..ctor(System.IntPtr) -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Cleanup() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Dispose() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Dispose(System.Boolean) -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Finalize() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.get_IsClosed() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.get_IsInvalid() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.ReleaseHandle() System.Private.CoreLib.dll:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute System.Private.CoreLib.dll:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute..ctor(System.Runtime.InteropServices.DllImportSearchPath) System.Private.CoreLib.dll:System.Runtime.InteropServices.DllImportAttribute @@ -8586,6 +8576,7 @@ System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Equals(System System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Equals(System.Runtime.InteropServices.GCHandle) System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Free() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.FromIntPtr(System.IntPtr) +System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.get_IsAllocated() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.get_Target() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.GetHandleValue(System.IntPtr) System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.GetHashCode() diff --git a/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-size.txt b/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-size.txt index 30e271a333ce..b2abcecdbae4 100644 --- a/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-size.txt +++ b/tests/dotnet/UnitTests/expected/MacCatalyst-MonoVM-size.txt @@ -1,15 +1,15 @@ -AppBundleSize: 16,327,064 bytes (15,944.4 KB = 15.6 MB) +AppBundleSize: 16,321,420 bytes (15,938.9 KB = 15.6 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: Contents/_CodeSignature/CodeResources: 4,134 bytes (4.0 KB = 0.0 MB) -Contents/Info.plist: 1,105 bytes (1.1 KB = 0.0 MB) -Contents/MacOS/SizeTestApp: 13,816,208 bytes (13,492.4 KB = 13.2 MB) +Contents/Info.plist: 1,085 bytes (1.1 KB = 0.0 MB) +Contents/MacOS/SizeTestApp: 13,810,240 bytes (13,486.6 KB = 13.2 MB) Contents/MonoBundle/aot-instances.aotdata.arm64: 1,045,032 bytes (1,020.5 KB = 1.0 MB) -Contents/MonoBundle/Microsoft.MacCatalyst.aotdata.arm64: 36,048 bytes (35.2 KB = 0.0 MB) -Contents/MonoBundle/Microsoft.MacCatalyst.dll: 51,200 bytes (50.0 KB = 0.0 MB) +Contents/MonoBundle/Microsoft.MacCatalyst.aotdata.arm64: 36,368 bytes (35.5 KB = 0.0 MB) +Contents/MonoBundle/Microsoft.MacCatalyst.dll: 50,688 bytes (49.5 KB = 0.0 MB) Contents/MonoBundle/runtimeconfig.bin: 1,481 bytes (1.4 KB = 0.0 MB) Contents/MonoBundle/SizeTestApp.aotdata.arm64: 1,552 bytes (1.5 KB = 0.0 MB) -Contents/MonoBundle/SizeTestApp.dll: 7,168 bytes (7.0 KB = 0.0 MB) -Contents/MonoBundle/System.Private.CoreLib.aotdata.arm64: 814,328 bytes (795.2 KB = 0.8 MB) +Contents/MonoBundle/SizeTestApp.dll: 7,680 bytes (7.5 KB = 0.0 MB) +Contents/MonoBundle/System.Private.CoreLib.aotdata.arm64: 814,352 bytes (795.3 KB = 0.8 MB) Contents/MonoBundle/System.Private.CoreLib.dll: 534,528 bytes (522.0 KB = 0.5 MB) Contents/MonoBundle/System.Runtime.aotdata.arm64: 472 bytes (0.5 KB = 0.0 MB) Contents/MonoBundle/System.Runtime.dll: 5,120 bytes (5.0 KB = 0.0 MB) diff --git a/tests/dotnet/UnitTests/expected/MacCatalyst-NativeAOT-TrimmableStatic-size.txt b/tests/dotnet/UnitTests/expected/MacCatalyst-NativeAOT-TrimmableStatic-size.txt index 1f4b876d0ab6..ac4c45f624c1 100644 --- a/tests/dotnet/UnitTests/expected/MacCatalyst-NativeAOT-TrimmableStatic-size.txt +++ b/tests/dotnet/UnitTests/expected/MacCatalyst-NativeAOT-TrimmableStatic-size.txt @@ -1,7 +1,7 @@ -AppBundleSize: 8,759,335 bytes (8,554.0 KB = 8.4 MB) +AppBundleSize: 8,808,853 bytes (8,602.4 KB = 8.4 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: Contents/_CodeSignature/CodeResources: 2,358 bytes (2.3 KB = 0.0 MB) -Contents/Info.plist: 1,105 bytes (1.1 KB = 0.0 MB) -Contents/MacOS/SizeTestApp: 8,753,968 bytes (8,548.8 KB = 8.3 MB) +Contents/Info.plist: 1,119 bytes (1.1 KB = 0.0 MB) +Contents/MacOS/SizeTestApp: 8,803,472 bytes (8,597.1 KB = 8.4 MB) Contents/MonoBundle/runtimeconfig.bin: 1,896 bytes (1.9 KB = 0.0 MB) Contents/PkgInfo: 8 bytes (0.0 KB = 0.0 MB) diff --git a/tests/dotnet/UnitTests/expected/MacCatalyst-NativeAOT-size.txt b/tests/dotnet/UnitTests/expected/MacCatalyst-NativeAOT-size.txt index 1f96717a8196..f35ae9613d96 100644 --- a/tests/dotnet/UnitTests/expected/MacCatalyst-NativeAOT-size.txt +++ b/tests/dotnet/UnitTests/expected/MacCatalyst-NativeAOT-size.txt @@ -1,7 +1,7 @@ -AppBundleSize: 2,781,135 bytes (2,716.0 KB = 2.7 MB) +AppBundleSize: 2,781,149 bytes (2,716.0 KB = 2.7 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: Contents/_CodeSignature/CodeResources: 2,358 bytes (2.3 KB = 0.0 MB) -Contents/Info.plist: 1,105 bytes (1.1 KB = 0.0 MB) +Contents/Info.plist: 1,119 bytes (1.1 KB = 0.0 MB) Contents/MacOS/SizeTestApp: 2,775,856 bytes (2,710.8 KB = 2.6 MB) Contents/MonoBundle/runtimeconfig.bin: 1,808 bytes (1.8 KB = 0.0 MB) Contents/PkgInfo: 8 bytes (0.0 KB = 0.0 MB) diff --git a/tests/dotnet/UnitTests/expected/MacOSX-CoreCLR-Interpreter-TrimmableStatic-size.txt b/tests/dotnet/UnitTests/expected/MacOSX-CoreCLR-Interpreter-TrimmableStatic-size.txt index 79bce275d232..e639fde89acf 100644 --- a/tests/dotnet/UnitTests/expected/MacOSX-CoreCLR-Interpreter-TrimmableStatic-size.txt +++ b/tests/dotnet/UnitTests/expected/MacOSX-CoreCLR-Interpreter-TrimmableStatic-size.txt @@ -1,12 +1,12 @@ -AppBundleSize: 259,373,212 bytes (253,294.2 KB = 247.4 MB) +AppBundleSize: 260,129,862 bytes (254,033.1 KB = 248.1 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: Contents/_CodeSignature/CodeResources: 67,868 bytes (66.3 KB = 0.1 MB) -Contents/Info.plist: 738 bytes (0.7 KB = 0.0 MB) -Contents/MacOS/SizeTestApp: 7,430,864 bytes (7,256.7 KB = 7.1 MB) +Contents/Info.plist: 716 bytes (0.7 KB = 0.0 MB) +Contents/MacOS/SizeTestApp: 7,430,800 bytes (7,256.6 KB = 7.1 MB) Contents/MonoBundle/.xamarin/osx-arm64/_Microsoft.macOS.TypeMap.dll: 4,847,616 bytes (4,734.0 KB = 4.6 MB) Contents/MonoBundle/.xamarin/osx-arm64/_SizeTestApp.TypeMap.dll: 3,072 bytes (3.0 KB = 0.0 MB) Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.CSharp.dll: 893,192 bytes (872.3 KB = 0.9 MB) -Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.macOS.dll: 38,145,536 bytes (37,251.5 KB = 36.4 MB) +Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.macOS.dll: 38,523,904 bytes (37,621.0 KB = 36.7 MB) Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.VisualBasic.Core.dll: 1,335,096 bytes (1,303.8 KB = 1.3 MB) Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.VisualBasic.dll: 17,680 bytes (17.3 KB = 0.0 MB) Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.Win32.Primitives.dll: 16,144 bytes (15.8 KB = 0.0 MB) @@ -182,7 +182,7 @@ Contents/MonoBundle/.xamarin/osx-arm64/WindowsBase.dll: 16,688 bytes (16.3 KB = Contents/MonoBundle/.xamarin/osx-x64/_Microsoft.macOS.TypeMap.dll: 4,847,616 bytes (4,734.0 KB = 4.6 MB) Contents/MonoBundle/.xamarin/osx-x64/_SizeTestApp.TypeMap.dll: 3,072 bytes (3.0 KB = 0.0 MB) Contents/MonoBundle/.xamarin/osx-x64/Microsoft.CSharp.dll: 796,432 bytes (777.8 KB = 0.8 MB) -Contents/MonoBundle/.xamarin/osx-x64/Microsoft.macOS.dll: 38,145,536 bytes (37,251.5 KB = 36.4 MB) +Contents/MonoBundle/.xamarin/osx-x64/Microsoft.macOS.dll: 38,523,904 bytes (37,621.0 KB = 36.7 MB) Contents/MonoBundle/.xamarin/osx-x64/Microsoft.VisualBasic.Core.dll: 1,166,648 bytes (1,139.3 KB = 1.1 MB) Contents/MonoBundle/.xamarin/osx-x64/Microsoft.VisualBasic.dll: 17,680 bytes (17.3 KB = 0.0 MB) Contents/MonoBundle/.xamarin/osx-x64/Microsoft.Win32.Primitives.dll: 16,176 bytes (15.8 KB = 0.0 MB) diff --git a/tests/dotnet/UnitTests/expected/MacOSX-CoreCLR-Interpreter-size.txt b/tests/dotnet/UnitTests/expected/MacOSX-CoreCLR-Interpreter-size.txt index 70b2fa7905e5..c7f0715b7541 100644 --- a/tests/dotnet/UnitTests/expected/MacOSX-CoreCLR-Interpreter-size.txt +++ b/tests/dotnet/UnitTests/expected/MacOSX-CoreCLR-Interpreter-size.txt @@ -1,10 +1,10 @@ -AppBundleSize: 247,534,854 bytes (241,733.3 KB = 236.1 MB) +AppBundleSize: 248,293,554 bytes (242,474.2 KB = 236.8 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: Contents/_CodeSignature/CodeResources: 67,160 bytes (65.6 KB = 0.1 MB) -Contents/Info.plist: 738 bytes (0.7 KB = 0.0 MB) -Contents/MacOS/SizeTestApp: 8,087,120 bytes (7,897.6 KB = 7.7 MB) +Contents/Info.plist: 750 bytes (0.7 KB = 0.0 MB) +Contents/MacOS/SizeTestApp: 8,088,048 bytes (7,898.5 KB = 7.7 MB) Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.CSharp.dll: 893,192 bytes (872.3 KB = 0.9 MB) -Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.macOS.dll: 36,748,800 bytes (35,887.5 KB = 35.0 MB) +Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.macOS.dll: 37,127,680 bytes (36,257.5 KB = 35.4 MB) Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.VisualBasic.Core.dll: 1,335,096 bytes (1,303.8 KB = 1.3 MB) Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.VisualBasic.dll: 17,680 bytes (17.3 KB = 0.0 MB) Contents/MonoBundle/.xamarin/osx-arm64/Microsoft.Win32.Primitives.dll: 16,144 bytes (15.8 KB = 0.0 MB) @@ -178,7 +178,7 @@ Contents/MonoBundle/.xamarin/osx-arm64/System.Xml.XPath.dll: 16,144 bytes (15.8 Contents/MonoBundle/.xamarin/osx-arm64/System.Xml.XPath.XDocument.dll: 17,672 bytes (17.3 KB = 0.0 MB) Contents/MonoBundle/.xamarin/osx-arm64/WindowsBase.dll: 16,688 bytes (16.3 KB = 0.0 MB) Contents/MonoBundle/.xamarin/osx-x64/Microsoft.CSharp.dll: 796,432 bytes (777.8 KB = 0.8 MB) -Contents/MonoBundle/.xamarin/osx-x64/Microsoft.macOS.dll: 36,748,800 bytes (35,887.5 KB = 35.0 MB) +Contents/MonoBundle/.xamarin/osx-x64/Microsoft.macOS.dll: 37,127,680 bytes (36,257.5 KB = 35.4 MB) Contents/MonoBundle/.xamarin/osx-x64/Microsoft.VisualBasic.Core.dll: 1,166,648 bytes (1,139.3 KB = 1.1 MB) Contents/MonoBundle/.xamarin/osx-x64/Microsoft.VisualBasic.dll: 17,680 bytes (17.3 KB = 0.0 MB) Contents/MonoBundle/.xamarin/osx-x64/Microsoft.Win32.Primitives.dll: 16,176 bytes (15.8 KB = 0.0 MB) diff --git a/tests/dotnet/UnitTests/expected/MacOSX-NativeAOT-TrimmableStatic-size.txt b/tests/dotnet/UnitTests/expected/MacOSX-NativeAOT-TrimmableStatic-size.txt index b4ab89c40241..03086f1a3700 100644 --- a/tests/dotnet/UnitTests/expected/MacOSX-NativeAOT-TrimmableStatic-size.txt +++ b/tests/dotnet/UnitTests/expected/MacOSX-NativeAOT-TrimmableStatic-size.txt @@ -1,8 +1,8 @@ -AppBundleSize: 21,482,500 bytes (20,979.0 KB = 20.5 MB) +AppBundleSize: 21,531,696 bytes (21,027.0 KB = 20.5 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: Contents/_CodeSignature/CodeResources: 3,489 bytes (3.4 KB = 0.0 MB) -Contents/Info.plist: 738 bytes (0.7 KB = 0.0 MB) -Contents/MacOS/SizeTestApp: 18,488,832 bytes (18,055.5 KB = 17.6 MB) +Contents/Info.plist: 750 bytes (0.7 KB = 0.0 MB) +Contents/MacOS/SizeTestApp: 18,538,016 bytes (18,103.5 KB = 17.7 MB) Contents/MonoBundle/libSystem.Globalization.Native.dylib: 252,176 bytes (246.3 KB = 0.2 MB) Contents/MonoBundle/libSystem.IO.Compression.Native.dylib: 2,005,440 bytes (1,958.4 KB = 1.9 MB) Contents/MonoBundle/libSystem.Native.dylib: 292,176 bytes (285.3 KB = 0.3 MB) diff --git a/tests/dotnet/UnitTests/expected/MacOSX-NativeAOT-size.txt b/tests/dotnet/UnitTests/expected/MacOSX-NativeAOT-size.txt index dcc45c318ac1..73e9feab2def 100644 --- a/tests/dotnet/UnitTests/expected/MacOSX-NativeAOT-size.txt +++ b/tests/dotnet/UnitTests/expected/MacOSX-NativeAOT-size.txt @@ -1,8 +1,8 @@ -AppBundleSize: 8,818,816 bytes (8,612.1 KB = 8.4 MB) +AppBundleSize: 8,835,214 bytes (8,628.1 KB = 8.4 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: Contents/_CodeSignature/CodeResources: 3,489 bytes (3.4 KB = 0.0 MB) -Contents/Info.plist: 736 bytes (0.7 KB = 0.0 MB) -Contents/MacOS/SizeTestApp: 5,825,232 bytes (5,688.7 KB = 5.6 MB) +Contents/Info.plist: 750 bytes (0.7 KB = 0.0 MB) +Contents/MacOS/SizeTestApp: 5,841,616 bytes (5,704.7 KB = 5.6 MB) Contents/MonoBundle/libSystem.Globalization.Native.dylib: 252,176 bytes (246.3 KB = 0.2 MB) Contents/MonoBundle/libSystem.IO.Compression.Native.dylib: 2,005,440 bytes (1,958.4 KB = 1.9 MB) Contents/MonoBundle/libSystem.Native.dylib: 292,176 bytes (285.3 KB = 0.3 MB) diff --git a/tests/dotnet/UnitTests/expected/TVOS-MonoVM-interpreter-preservedapis.txt b/tests/dotnet/UnitTests/expected/TVOS-MonoVM-interpreter-preservedapis.txt index 57d50d17b7d0..5dc7ee998d0d 100644 --- a/tests/dotnet/UnitTests/expected/TVOS-MonoVM-interpreter-preservedapis.txt +++ b/tests/dotnet/UnitTests/expected/TVOS-MonoVM-interpreter-preservedapis.txt @@ -113,7 +113,6 @@ Microsoft.tvOS.dll:Foundation.NSObject..ctor() Microsoft.tvOS.dll:Foundation.NSObject..ctor(Foundation.NSObjectFlag) Microsoft.tvOS.dll:Foundation.NSObject..ctor(ObjCRuntime.NativeHandle, System.Boolean) Microsoft.tvOS.dll:Foundation.NSObject..ctor(ObjCRuntime.NativeHandle) -Microsoft.tvOS.dll:Foundation.NSObject.AllocateData() Microsoft.tvOS.dll:Foundation.NSObject.AllocIfNeeded() Microsoft.tvOS.dll:Foundation.NSObject.ClearHandle() Microsoft.tvOS.dll:Foundation.NSObject.ConformsToProtocol(ObjCRuntime.NativeHandle) @@ -140,11 +139,9 @@ Microsoft.tvOS.dll:Foundation.NSObject.get_Handle() Microsoft.tvOS.dll:Foundation.NSObject.get_InFinalizerQueue() Microsoft.tvOS.dll:Foundation.NSObject.get_IsDirectBinding() Microsoft.tvOS.dll:Foundation.NSObject.get_IsRegisteredToggleRef() -Microsoft.tvOS.dll:Foundation.NSObject.get_SuperHandle() Microsoft.tvOS.dll:Foundation.NSObject.GetData() Microsoft.tvOS.dll:Foundation.NSObject.GetHashCode() Microsoft.tvOS.dll:Foundation.NSObject.GetNativeHash() -Microsoft.tvOS.dll:Foundation.NSObject.GetSuper() Microsoft.tvOS.dll:Foundation.NSObject.Initialize() Microsoft.tvOS.dll:Foundation.NSObject.InitializeHandle(ObjCRuntime.NativeHandle, System.String, System.Boolean) Microsoft.tvOS.dll:Foundation.NSObject.InitializeHandle(ObjCRuntime.NativeHandle, System.String) @@ -152,7 +149,6 @@ Microsoft.tvOS.dll:Foundation.NSObject.InitializeObject(System.Boolean) Microsoft.tvOS.dll:Foundation.NSObject.InvokeConformsToProtocol(ObjCRuntime.NativeHandle) Microsoft.tvOS.dll:Foundation.NSObject.IsEqual(Foundation.NSObject) Microsoft.tvOS.dll:Foundation.NSObject.IsProtocol(System.Type, System.IntPtr) -Microsoft.tvOS.dll:Foundation.NSObject.RecreateDataHandle() Microsoft.tvOS.dll:Foundation.NSObject.ReleaseManagedRef() Microsoft.tvOS.dll:Foundation.NSObject.set_disposed(System.Boolean) Microsoft.tvOS.dll:Foundation.NSObject.set_flags(Foundation.NSObject/Flags) @@ -191,16 +187,10 @@ Microsoft.tvOS.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/ Microsoft.tvOS.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/XamarinGCHandleFlags::InitialSet Microsoft.tvOS.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/XamarinGCHandleFlags::None Microsoft.tvOS.dll:Foundation.NSObjectData -Microsoft.tvOS.dll:Foundation.NSObjectData* Foundation.NSObject::__data_for_mono Microsoft.tvOS.dll:Foundation.NSObjectData* Foundation.NSObjectDataHandle::Data() Microsoft.tvOS.dll:Foundation.NSObjectDataHandle -Microsoft.tvOS.dll:Foundation.NSObjectDataHandle Foundation.NSObject::data_handle Microsoft.tvOS.dll:Foundation.NSObjectDataHandle..ctor() -Microsoft.tvOS.dll:Foundation.NSObjectDataHandle..ctor(System.IntPtr) Microsoft.tvOS.dll:Foundation.NSObjectDataHandle.get_Data() -Microsoft.tvOS.dll:Foundation.NSObjectDataHandle.get_IsInvalid() -Microsoft.tvOS.dll:Foundation.NSObjectDataHandle.Invalidate() -Microsoft.tvOS.dll:Foundation.NSObjectDataHandle.ReleaseHandle() Microsoft.tvOS.dll:Foundation.NSObjectFlag Microsoft.tvOS.dll:Foundation.NSObjectFlag Foundation.NSObjectFlag::Empty Microsoft.tvOS.dll:Foundation.NSString @@ -251,6 +241,12 @@ Microsoft.tvOS.dll:Foundation.RegisterAttribute.get_IsStubClass() Microsoft.tvOS.dll:Foundation.RegisterAttribute.get_IsWrapper() Microsoft.tvOS.dll:Foundation.RegisterAttribute.get_Name() Microsoft.tvOS.dll:Foundation.RegisterAttribute.get_SkipRegistration() +Microsoft.tvOS.dll:Foundation.TrackedMemory +Microsoft.tvOS.dll:Foundation.TrackedMemory..ctor(System.UIntPtr) +Microsoft.tvOS.dll:Foundation.TrackedMemory.CreateHandle(Foundation.NSObject) +Microsoft.tvOS.dll:Foundation.TrackedMemory.Finalize() +Microsoft.tvOS.dll:Foundation.TrackedMemory.get_Value() +Microsoft.tvOS.dll:Foundation.TrackedMemory.set_Value(System.IntPtr) Microsoft.tvOS.dll:Foundation.You_Should_Not_Call_base_In_This_Method Microsoft.tvOS.dll:Foundation.You_Should_Not_Call_base_In_This_Method..ctor() Microsoft.tvOS.dll:ObjCRuntime.__Registrar__ @@ -440,29 +436,29 @@ Microsoft.tvOS.dll:ObjCRuntime.MarshalObjectiveCExceptionMode ObjCRuntime.Runtim Microsoft.tvOS.dll:ObjCRuntime.Messaging Microsoft.tvOS.dll:ObjCRuntime.Messaging.bool_objc_msgSend_IntPtr(System.IntPtr, System.IntPtr, System.IntPtr) Microsoft.tvOS.dll:ObjCRuntime.Messaging.bool_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_IntPtr(System.IntPtr, System.IntPtr, System.IntPtr) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_IntPtr(ObjCRuntime.ObjCSuper*, System.IntPtr, System.IntPtr) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.tvOS.dll:ObjCRuntime.Messaging.CGRect_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.CGRect_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.CGRect_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.tvOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.tvOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend_CGRect(System.IntPtr, System.IntPtr, CoreGraphics.CGRect) Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper_CGRect(System.IntPtr, System.IntPtr, CoreGraphics.CGRect) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper_CGRect(ObjCRuntime.ObjCSuper*, System.IntPtr, CoreGraphics.CGRect) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.tvOS.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, ObjCRuntime.NativeHandle, System.Byte) Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_UIntPtr(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, System.UIntPtr) Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle_UIntPtr(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, System.UIntPtr) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle_UIntPtr(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle, System.UIntPtr) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.tvOS.dll:ObjCRuntime.Method Microsoft.tvOS.dll:ObjCRuntime.Method.get_ConstructorTrampoline() Microsoft.tvOS.dll:ObjCRuntime.Method.get_DoubleTrampoline() @@ -497,8 +493,6 @@ Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::class_ptr Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::ClassHandle() Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::handle() Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::Handle() -Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::SuperHandle() -Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObjectData::classHandle Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObjectData::handle Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSString::class_ptr Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSString::ClassHandle() @@ -508,6 +502,8 @@ Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.DisposableObject::handle Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.DisposableObject::Handle() Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.INativeObject::Handle() Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.NativeHandle::Zero +Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.ObjCSuper::classHandle +Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.ObjCSuper::receiver Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Protocol::handle Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Protocol::Handle() Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Runtime/ClassHandles::unused @@ -553,6 +549,8 @@ Microsoft.tvOS.dll:ObjCRuntime.ObjCException.get_Name() Microsoft.tvOS.dll:ObjCRuntime.ObjCException.get_NSException() Microsoft.tvOS.dll:ObjCRuntime.ObjCException.get_Reason() Microsoft.tvOS.dll:ObjCRuntime.ObjCException.ToString() +Microsoft.tvOS.dll:ObjCRuntime.ObjCSuper +Microsoft.tvOS.dll:ObjCRuntime.ObjCSuper..ctor(Foundation.NSObject) Microsoft.tvOS.dll:ObjCRuntime.Protocol Microsoft.tvOS.dll:ObjCRuntime.Protocol._Xamarin_ConstructINativeObject(ObjCRuntime.NativeHandle, System.Boolean) Microsoft.tvOS.dll:ObjCRuntime.Protocol..cctor() @@ -1207,8 +1205,6 @@ Microsoft.tvOS.dll:System.Boolean Foundation.NSObject::IsDirectBinding() Microsoft.tvOS.dll:System.Boolean Foundation.NSObject::IsRegisteredToggleRef() Microsoft.tvOS.dll:System.Boolean Foundation.NSObject::RemoveFromObjectMap() Microsoft.tvOS.dll:System.Boolean Foundation.NSObject/NSObject_Disposer::draining -Microsoft.tvOS.dll:System.Boolean Foundation.NSObjectDataHandle::invalidated -Microsoft.tvOS.dll:System.Boolean Foundation.NSObjectDataHandle::IsInvalid() Microsoft.tvOS.dll:System.Boolean Foundation.ProtocolAttribute::k__BackingField Microsoft.tvOS.dll:System.Boolean Foundation.ProtocolAttribute::k__BackingField Microsoft.tvOS.dll:System.Boolean Foundation.ProtocolAttribute::IsInformal() @@ -1327,7 +1323,10 @@ Microsoft.tvOS.dll:System.Int64 Foundation.NSComparisonResult::value__ Microsoft.tvOS.dll:System.IntPtr CoreFoundation.CFArray::_CFNullHandle() Microsoft.tvOS.dll:System.IntPtr CoreFoundation.CFRange::len Microsoft.tvOS.dll:System.IntPtr CoreFoundation.CFRange::loc +Microsoft.tvOS.dll:System.IntPtr Foundation.NSObject::__data Microsoft.tvOS.dll:System.IntPtr Foundation.NSObject/NSObject_Disposer::class_ptr +Microsoft.tvOS.dll:System.IntPtr Foundation.TrackedMemory::k__BackingField +Microsoft.tvOS.dll:System.IntPtr Foundation.TrackedMemory::Value() Microsoft.tvOS.dll:System.IntPtr ObjCRuntime.AdoptsAttribute::ProtocolHandle() Microsoft.tvOS.dll:System.IntPtr ObjCRuntime.BlockCollector::block Microsoft.tvOS.dll:System.IntPtr ObjCRuntime.Libraries/CoreFoundation::Handle @@ -1488,8 +1487,11 @@ Microsoft.tvOS.dll:System.Reflection.MethodBase Registrar.Registrar::invoke_conf Microsoft.tvOS.dll:System.Reflection.MethodBase Registrar.Registrar/ObjCMethod::Method Microsoft.tvOS.dll:System.Reflection.PropertyInfo Registrar.Registrar/ObjCProperty::Property Microsoft.tvOS.dll:System.Reflection.TypeFilter Registrar.SharedDynamic/<>c::<>9__0_0 +Microsoft.tvOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 Foundation.NSObject::data_table +Microsoft.tvOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 Foundation.NSObject::super_map Microsoft.tvOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 ObjCRuntime.Runtime::block_lifetime_table Microsoft.tvOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 ObjCRuntime.Class::assembly_to_name +Microsoft.tvOS.dll:System.Runtime.InteropServices.GCHandle Foundation.TrackedMemory::handle Microsoft.tvOS.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::height Microsoft.tvOS.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::width Microsoft.tvOS.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::x @@ -2710,14 +2712,12 @@ System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.Runtim System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.RuntimeFeature::k__BackingField System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.RuntimeFeature::IsDynamicCodeSupported() System.Private.CoreLib.dll:System.Boolean System.Runtime.DependentHandle::IsAllocated() -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::_isClosed -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::IsClosed() -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::IsInvalid() System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::BestFitMapping System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::ExactSpelling System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::PreserveSig System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::SetLastError System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::ThrowOnUnmappableChar +System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.GCHandle::IsAllocated() System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.SafeHandleMarshaller`1/ManagedToUnmanagedIn::_addRefd System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.SafeHandleMarshaller`1/ManagedToUnmanagedOut::_initialized System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.Utf8StringMarshaller/ManagedToUnmanagedIn::_allocated @@ -6888,7 +6888,6 @@ System.Private.CoreLib.dll:System.IntPtr System.Reflection.RuntimePropertyInfo:: System.Private.CoreLib.dll:System.IntPtr System.Reflection.RuntimePropertyInfo::prop System.Private.CoreLib.dll:System.IntPtr System.Runtime.CompilerServices.QCallAssembly::_assembly System.Private.CoreLib.dll:System.IntPtr System.Runtime.CompilerServices.QCallTypeHandle::_handle -System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.CriticalHandle::handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.GCHandle::_handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.SafeHandle::handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.WeakGCHandle`1::_handle @@ -10773,15 +10772,6 @@ System.Private.CoreLib.dll:System.Runtime.InteropServices.CollectionsMarshal System.Private.CoreLib.dll:System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault`2(System.Collections.Generic.Dictionary`2, TKey, out System.Boolean&) System.Private.CoreLib.dll:System.Runtime.InteropServices.ComImportAttribute System.Private.CoreLib.dll:System.Runtime.InteropServices.ComImportAttribute..ctor() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle..ctor(System.IntPtr) -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Cleanup() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Dispose() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Dispose(System.Boolean) -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Finalize() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.get_IsClosed() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.get_IsInvalid() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.ReleaseHandle() System.Private.CoreLib.dll:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute System.Private.CoreLib.dll:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute..ctor(System.Runtime.InteropServices.DllImportSearchPath) System.Private.CoreLib.dll:System.Runtime.InteropServices.DllImportAttribute @@ -10810,6 +10800,7 @@ System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Equals(System System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Equals(System.Runtime.InteropServices.GCHandle) System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Free() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.FromIntPtr(System.IntPtr) +System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.get_IsAllocated() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.get_Target() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.GetHandleValue(System.IntPtr) System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.GetHashCode() diff --git a/tests/dotnet/UnitTests/expected/TVOS-MonoVM-interpreter-size.txt b/tests/dotnet/UnitTests/expected/TVOS-MonoVM-interpreter-size.txt index a8840dd6a070..4a3f73193711 100644 --- a/tests/dotnet/UnitTests/expected/TVOS-MonoVM-interpreter-size.txt +++ b/tests/dotnet/UnitTests/expected/TVOS-MonoVM-interpreter-size.txt @@ -1,14 +1,14 @@ -AppBundleSize: 3,617,471 bytes (3,532.7 KB = 3.4 MB) +AppBundleSize: 3,616,596 bytes (3,531.8 KB = 3.4 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: _CodeSignature/CodeResources: 3,999 bytes (3.9 KB = 0.0 MB) archived-expanded-entitlements.xcent: 384 bytes (0.4 KB = 0.0 MB) -Info.plist: 1,123 bytes (1.1 KB = 0.0 MB) -Microsoft.tvOS.dll: 155,136 bytes (151.5 KB = 0.1 MB) +Info.plist: 1,104 bytes (1.1 KB = 0.0 MB) +Microsoft.tvOS.dll: 154,624 bytes (151.0 KB = 0.1 MB) PkgInfo: 8 bytes (0.0 KB = 0.0 MB) runtimeconfig.bin: 1,405 bytes (1.4 KB = 0.0 MB) -SizeTestApp: 2,404,416 bytes (2,348.1 KB = 2.3 MB) +SizeTestApp: 2,404,608 bytes (2,348.2 KB = 2.3 MB) SizeTestApp.dll: 7,680 bytes (7.5 KB = 0.0 MB) -System.Private.CoreLib.aotdata.arm64: 41,336 bytes (40.4 KB = 0.0 MB) -System.Private.CoreLib.dll: 988,672 bytes (965.5 KB = 0.9 MB) +System.Private.CoreLib.aotdata.arm64: 41,312 bytes (40.3 KB = 0.0 MB) +System.Private.CoreLib.dll: 988,160 bytes (965.0 KB = 0.9 MB) System.Runtime.dll: 5,120 bytes (5.0 KB = 0.0 MB) System.Runtime.InteropServices.dll: 8,192 bytes (8.0 KB = 0.0 MB) diff --git a/tests/dotnet/UnitTests/expected/TVOS-MonoVM-preservedapis.txt b/tests/dotnet/UnitTests/expected/TVOS-MonoVM-preservedapis.txt index a003cb6ee979..fef21b016f75 100644 --- a/tests/dotnet/UnitTests/expected/TVOS-MonoVM-preservedapis.txt +++ b/tests/dotnet/UnitTests/expected/TVOS-MonoVM-preservedapis.txt @@ -99,7 +99,6 @@ Microsoft.tvOS.dll:Foundation.NSObject..ctor() Microsoft.tvOS.dll:Foundation.NSObject..ctor(Foundation.NSObjectFlag) Microsoft.tvOS.dll:Foundation.NSObject..ctor(ObjCRuntime.NativeHandle, System.Boolean) Microsoft.tvOS.dll:Foundation.NSObject..ctor(ObjCRuntime.NativeHandle) -Microsoft.tvOS.dll:Foundation.NSObject.AllocateData() Microsoft.tvOS.dll:Foundation.NSObject.AllocIfNeeded() Microsoft.tvOS.dll:Foundation.NSObject.ClearHandle() Microsoft.tvOS.dll:Foundation.NSObject.ConformsToProtocol(ObjCRuntime.NativeHandle) @@ -125,18 +124,15 @@ Microsoft.tvOS.dll:Foundation.NSObject.get_Handle() Microsoft.tvOS.dll:Foundation.NSObject.get_InFinalizerQueue() Microsoft.tvOS.dll:Foundation.NSObject.get_IsDirectBinding() Microsoft.tvOS.dll:Foundation.NSObject.get_IsRegisteredToggleRef() -Microsoft.tvOS.dll:Foundation.NSObject.get_SuperHandle() Microsoft.tvOS.dll:Foundation.NSObject.GetData() Microsoft.tvOS.dll:Foundation.NSObject.GetHashCode() Microsoft.tvOS.dll:Foundation.NSObject.GetNativeHash() -Microsoft.tvOS.dll:Foundation.NSObject.GetSuper() Microsoft.tvOS.dll:Foundation.NSObject.Initialize() Microsoft.tvOS.dll:Foundation.NSObject.InitializeHandle(ObjCRuntime.NativeHandle, System.String, System.Boolean) Microsoft.tvOS.dll:Foundation.NSObject.InitializeHandle(ObjCRuntime.NativeHandle, System.String) Microsoft.tvOS.dll:Foundation.NSObject.InitializeObject(System.Boolean) Microsoft.tvOS.dll:Foundation.NSObject.InvokeConformsToProtocol(ObjCRuntime.NativeHandle) Microsoft.tvOS.dll:Foundation.NSObject.IsEqual(Foundation.NSObject) -Microsoft.tvOS.dll:Foundation.NSObject.RecreateDataHandle() Microsoft.tvOS.dll:Foundation.NSObject.ReleaseManagedRef() Microsoft.tvOS.dll:Foundation.NSObject.set_disposed(System.Boolean) Microsoft.tvOS.dll:Foundation.NSObject.set_flags(Foundation.NSObject/Flags) @@ -174,16 +170,10 @@ Microsoft.tvOS.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/ Microsoft.tvOS.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/XamarinGCHandleFlags::InitialSet Microsoft.tvOS.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/XamarinGCHandleFlags::None Microsoft.tvOS.dll:Foundation.NSObjectData -Microsoft.tvOS.dll:Foundation.NSObjectData* Foundation.NSObject::__data_for_mono Microsoft.tvOS.dll:Foundation.NSObjectData* Foundation.NSObjectDataHandle::Data() Microsoft.tvOS.dll:Foundation.NSObjectDataHandle -Microsoft.tvOS.dll:Foundation.NSObjectDataHandle Foundation.NSObject::data_handle Microsoft.tvOS.dll:Foundation.NSObjectDataHandle..ctor() -Microsoft.tvOS.dll:Foundation.NSObjectDataHandle..ctor(System.IntPtr) Microsoft.tvOS.dll:Foundation.NSObjectDataHandle.get_Data() -Microsoft.tvOS.dll:Foundation.NSObjectDataHandle.get_IsInvalid() -Microsoft.tvOS.dll:Foundation.NSObjectDataHandle.Invalidate() -Microsoft.tvOS.dll:Foundation.NSObjectDataHandle.ReleaseHandle() Microsoft.tvOS.dll:Foundation.NSObjectFlag Microsoft.tvOS.dll:Foundation.NSObjectFlag Foundation.NSObjectFlag::Empty Microsoft.tvOS.dll:Foundation.ProtocolAttribute @@ -193,6 +183,12 @@ Microsoft.tvOS.dll:Foundation.RegisterAttribute Microsoft.tvOS.dll:Foundation.RegisterAttribute..ctor(System.String, System.Boolean) Microsoft.tvOS.dll:Foundation.RegisterAttribute..ctor(System.String) Microsoft.tvOS.dll:Foundation.RegisterAttribute.get_IsWrapper() +Microsoft.tvOS.dll:Foundation.TrackedMemory +Microsoft.tvOS.dll:Foundation.TrackedMemory..ctor(System.UIntPtr) +Microsoft.tvOS.dll:Foundation.TrackedMemory.CreateHandle(Foundation.NSObject) +Microsoft.tvOS.dll:Foundation.TrackedMemory.Finalize() +Microsoft.tvOS.dll:Foundation.TrackedMemory.get_Value() +Microsoft.tvOS.dll:Foundation.TrackedMemory.set_Value(System.IntPtr) Microsoft.tvOS.dll:Foundation.You_Should_Not_Call_base_In_This_Method Microsoft.tvOS.dll:Foundation.You_Should_Not_Call_base_In_This_Method..ctor() Microsoft.tvOS.dll:ObjCRuntime.__Registrar__ @@ -348,17 +344,17 @@ Microsoft.tvOS.dll:ObjCRuntime.MarshalObjectiveCExceptionMode ObjCRuntime.Runtim Microsoft.tvOS.dll:ObjCRuntime.Messaging Microsoft.tvOS.dll:ObjCRuntime.Messaging.bool_objc_msgSend_IntPtr(System.IntPtr, System.IntPtr, System.IntPtr) Microsoft.tvOS.dll:ObjCRuntime.Messaging.bool_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_IntPtr(System.IntPtr, System.IntPtr, System.IntPtr) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_IntPtr(ObjCRuntime.ObjCSuper*, System.IntPtr, System.IntPtr) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.tvOS.dll:ObjCRuntime.Messaging.CGRect_objc_msgSend(System.IntPtr, System.IntPtr) Microsoft.tvOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend_CGRect(System.IntPtr, System.IntPtr, CoreGraphics.CGRect) Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.tvOS.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.tvOS.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.tvOS.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, ObjCRuntime.NativeHandle, System.Byte) Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_UIntPtr(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, System.UIntPtr) Microsoft.tvOS.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) @@ -377,8 +373,6 @@ Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::class_ptr Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::ClassHandle() Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::handle() Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::Handle() -Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::SuperHandle() -Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObjectData::classHandle Microsoft.tvOS.dll:ObjCRuntime.NativeHandle Foundation.NSObjectData::handle Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Class::handle Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Class::Handle() @@ -386,6 +380,8 @@ Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.DisposableObject::handle Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.DisposableObject::Handle() Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.INativeObject::Handle() Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.NativeHandle::Zero +Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.ObjCSuper::classHandle +Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.ObjCSuper::receiver Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Runtime/ClassHandles::unused Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Selector::handle Microsoft.tvOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Selector::Handle() @@ -428,6 +424,8 @@ Microsoft.tvOS.dll:ObjCRuntime.ObjCException.get_Name() Microsoft.tvOS.dll:ObjCRuntime.ObjCException.get_NSException() Microsoft.tvOS.dll:ObjCRuntime.ObjCException.get_Reason() Microsoft.tvOS.dll:ObjCRuntime.ObjCException.ToString() +Microsoft.tvOS.dll:ObjCRuntime.ObjCSuper +Microsoft.tvOS.dll:ObjCRuntime.ObjCSuper..ctor(Foundation.NSObject) Microsoft.tvOS.dll:ObjCRuntime.RegistrarHelper Microsoft.tvOS.dll:ObjCRuntime.RegistrarHelper.ConstructINativeObject`1(System.Type, ObjCRuntime.NativeHandle, System.Boolean) Microsoft.tvOS.dll:ObjCRuntime.RegistrarHelper.ConstructNSObject`1(System.Type, ObjCRuntime.NativeHandle) @@ -662,8 +660,6 @@ Microsoft.tvOS.dll:System.Boolean Foundation.NSObject::InFinalizerQueue() Microsoft.tvOS.dll:System.Boolean Foundation.NSObject::IsDirectBinding() Microsoft.tvOS.dll:System.Boolean Foundation.NSObject::IsRegisteredToggleRef() Microsoft.tvOS.dll:System.Boolean Foundation.NSObject/NSObject_Disposer::draining -Microsoft.tvOS.dll:System.Boolean Foundation.NSObjectDataHandle::invalidated -Microsoft.tvOS.dll:System.Boolean Foundation.NSObjectDataHandle::IsInvalid() Microsoft.tvOS.dll:System.Boolean Foundation.ProtocolAttribute::k__BackingField Microsoft.tvOS.dll:System.Boolean Foundation.RegisterAttribute::is_wrapper Microsoft.tvOS.dll:System.Boolean Foundation.RegisterAttribute::IsWrapper() @@ -719,7 +715,10 @@ Microsoft.tvOS.dll:System.Int32 ObjCRuntime.TransientString/Encoding::value__ Microsoft.tvOS.dll:System.IntPtr CoreFoundation.CFArray::_CFNullHandle() Microsoft.tvOS.dll:System.IntPtr CoreFoundation.CFRange::len Microsoft.tvOS.dll:System.IntPtr CoreFoundation.CFRange::loc +Microsoft.tvOS.dll:System.IntPtr Foundation.NSObject::__data Microsoft.tvOS.dll:System.IntPtr Foundation.NSObject/NSObject_Disposer::class_ptr +Microsoft.tvOS.dll:System.IntPtr Foundation.TrackedMemory::k__BackingField +Microsoft.tvOS.dll:System.IntPtr Foundation.TrackedMemory::Value() Microsoft.tvOS.dll:System.IntPtr ObjCRuntime.BlockCollector::block Microsoft.tvOS.dll:System.IntPtr ObjCRuntime.Libraries/CoreFoundation::Handle Microsoft.tvOS.dll:System.IntPtr ObjCRuntime.NativeHandle::handle @@ -848,8 +847,11 @@ Microsoft.tvOS.dll:System.IntPtr* ObjCRuntime.Runtime/MTRegistrationMap::classHa Microsoft.tvOS.dll:System.Object Foundation.NSObject/NSObject_Disposer::lock_obj Microsoft.tvOS.dll:System.Object ObjCRuntime.Runtime::lock_obj Microsoft.tvOS.dll:System.Reflection.Assembly Foundation.NSObject::PlatformAssembly +Microsoft.tvOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 Foundation.NSObject::data_table +Microsoft.tvOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 Foundation.NSObject::super_map Microsoft.tvOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 ObjCRuntime.Runtime::block_lifetime_table Microsoft.tvOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 ObjCRuntime.Class::assembly_to_name +Microsoft.tvOS.dll:System.Runtime.InteropServices.GCHandle Foundation.TrackedMemory::handle Microsoft.tvOS.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::height Microsoft.tvOS.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::width Microsoft.tvOS.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::x @@ -1943,14 +1945,12 @@ System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.Nullab System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::k__BackingField System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::WrapNonExceptionThrows() System.Private.CoreLib.dll:System.Boolean System.Runtime.DependentHandle::IsAllocated() -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::_isClosed -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::IsClosed() -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::IsInvalid() System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::BestFitMapping System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::ExactSpelling System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::PreserveSig System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::SetLastError System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::ThrowOnUnmappableChar +System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.GCHandle::IsAllocated() System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.SafeHandleMarshaller`1/ManagedToUnmanagedIn::_addRefd System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.SafeHandleMarshaller`1/ManagedToUnmanagedOut::_initialized System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.Utf8StringMarshaller/ManagedToUnmanagedIn::_allocated @@ -5969,7 +5969,6 @@ System.Private.CoreLib.dll:System.IntPtr System.Reflection.RuntimePropertyInfo:: System.Private.CoreLib.dll:System.IntPtr System.Reflection.RuntimePropertyInfo::prop System.Private.CoreLib.dll:System.IntPtr System.Runtime.CompilerServices.QCallAssembly::_assembly System.Private.CoreLib.dll:System.IntPtr System.Runtime.CompilerServices.QCallTypeHandle::_handle -System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.CriticalHandle::handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.GCHandle::_handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.SafeHandle::handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.WeakGCHandle`1::_handle @@ -8485,15 +8484,6 @@ System.Private.CoreLib.dll:System.Runtime.InteropServices.CollectionsMarshal System.Private.CoreLib.dll:System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault`2(System.Collections.Generic.Dictionary`2, TKey, out System.Boolean&) System.Private.CoreLib.dll:System.Runtime.InteropServices.ComImportAttribute System.Private.CoreLib.dll:System.Runtime.InteropServices.ComImportAttribute..ctor() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle..ctor(System.IntPtr) -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Cleanup() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Dispose() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Dispose(System.Boolean) -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Finalize() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.get_IsClosed() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.get_IsInvalid() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.ReleaseHandle() System.Private.CoreLib.dll:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute System.Private.CoreLib.dll:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute..ctor(System.Runtime.InteropServices.DllImportSearchPath) System.Private.CoreLib.dll:System.Runtime.InteropServices.DllImportAttribute @@ -8521,6 +8511,7 @@ System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Equals(System System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Equals(System.Runtime.InteropServices.GCHandle) System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Free() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.FromIntPtr(System.IntPtr) +System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.get_IsAllocated() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.get_Target() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.GetHandleValue(System.IntPtr) System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.GetHashCode() diff --git a/tests/dotnet/UnitTests/expected/TVOS-MonoVM-size.txt b/tests/dotnet/UnitTests/expected/TVOS-MonoVM-size.txt index ac016e47913f..35b977aeb175 100644 --- a/tests/dotnet/UnitTests/expected/TVOS-MonoVM-size.txt +++ b/tests/dotnet/UnitTests/expected/TVOS-MonoVM-size.txt @@ -1,17 +1,17 @@ -AppBundleSize: 9,364,029 bytes (9,144.6 KB = 8.9 MB) +AppBundleSize: 9,364,148 bytes (9,144.7 KB = 8.9 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: _CodeSignature/CodeResources: 5,233 bytes (5.1 KB = 0.0 MB) aot-instances.aotdata.arm64: 827,592 bytes (808.2 KB = 0.8 MB) archived-expanded-entitlements.xcent: 384 bytes (0.4 KB = 0.0 MB) -Info.plist: 1,123 bytes (1.1 KB = 0.0 MB) -Microsoft.tvOS.aotdata.arm64: 22,640 bytes (22.1 KB = 0.0 MB) -Microsoft.tvOS.dll: 49,152 bytes (48.0 KB = 0.0 MB) +Info.plist: 1,138 bytes (1.1 KB = 0.0 MB) +Microsoft.tvOS.aotdata.arm64: 22,880 bytes (22.3 KB = 0.0 MB) +Microsoft.tvOS.dll: 48,640 bytes (47.5 KB = 0.0 MB) PkgInfo: 8 bytes (0.0 KB = 0.0 MB) runtimeconfig.bin: 1,481 bytes (1.4 KB = 0.0 MB) SizeTestApp: 7,261,152 bytes (7,091.0 KB = 6.9 MB) SizeTestApp.aotdata.arm64: 1,464 bytes (1.4 KB = 0.0 MB) -SizeTestApp.dll: 7,168 bytes (7.0 KB = 0.0 MB) -System.Private.CoreLib.aotdata.arm64: 640,792 bytes (625.8 KB = 0.6 MB) +SizeTestApp.dll: 7,680 bytes (7.5 KB = 0.0 MB) +System.Private.CoreLib.aotdata.arm64: 640,656 bytes (625.6 KB = 0.6 MB) System.Private.CoreLib.dll: 530,944 bytes (518.5 KB = 0.5 MB) System.Runtime.aotdata.arm64: 784 bytes (0.8 KB = 0.0 MB) System.Runtime.dll: 5,120 bytes (5.0 KB = 0.0 MB) diff --git a/tests/dotnet/UnitTests/expected/TVOS-NativeAOT-TrimmableStatic-size.txt b/tests/dotnet/UnitTests/expected/TVOS-NativeAOT-TrimmableStatic-size.txt index e91793096976..e01435700c48 100644 --- a/tests/dotnet/UnitTests/expected/TVOS-NativeAOT-TrimmableStatic-size.txt +++ b/tests/dotnet/UnitTests/expected/TVOS-NativeAOT-TrimmableStatic-size.txt @@ -1,8 +1,8 @@ -AppBundleSize: 7,905,353 bytes (7,720.1 KB = 7.5 MB) +AppBundleSize: 7,922,198 bytes (7,736.5 KB = 7.6 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: _CodeSignature/CodeResources: 2,589 bytes (2.5 KB = 0.0 MB) archived-expanded-entitlements.xcent: 384 bytes (0.4 KB = 0.0 MB) -Info.plist: 1,123 bytes (1.1 KB = 0.0 MB) +Info.plist: 1,104 bytes (1.1 KB = 0.0 MB) PkgInfo: 8 bytes (0.0 KB = 0.0 MB) runtimeconfig.bin: 1,889 bytes (1.8 KB = 0.0 MB) -SizeTestApp: 7,899,360 bytes (7,714.2 KB = 7.5 MB) +SizeTestApp: 7,916,224 bytes (7,730.7 KB = 7.5 MB) diff --git a/tests/dotnet/UnitTests/expected/TVOS-NativeAOT-size.txt b/tests/dotnet/UnitTests/expected/TVOS-NativeAOT-size.txt index 56adae8012cd..15f36c7f55eb 100644 --- a/tests/dotnet/UnitTests/expected/TVOS-NativeAOT-size.txt +++ b/tests/dotnet/UnitTests/expected/TVOS-NativeAOT-size.txt @@ -1,8 +1,8 @@ -AppBundleSize: 2,783,144 bytes (2,717.9 KB = 2.7 MB) +AppBundleSize: 2,783,159 bytes (2,717.9 KB = 2.7 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: _CodeSignature/CodeResources: 2,589 bytes (2.5 KB = 0.0 MB) archived-expanded-entitlements.xcent: 384 bytes (0.4 KB = 0.0 MB) -Info.plist: 1,123 bytes (1.1 KB = 0.0 MB) +Info.plist: 1,138 bytes (1.1 KB = 0.0 MB) PkgInfo: 8 bytes (0.0 KB = 0.0 MB) runtimeconfig.bin: 1,808 bytes (1.8 KB = 0.0 MB) SizeTestApp: 2,777,232 bytes (2,712.1 KB = 2.6 MB) diff --git a/tests/dotnet/UnitTests/expected/iOS-MonoVM-interpreter-preservedapis.txt b/tests/dotnet/UnitTests/expected/iOS-MonoVM-interpreter-preservedapis.txt index 31c45a23253c..0178f1e5c2e3 100644 --- a/tests/dotnet/UnitTests/expected/iOS-MonoVM-interpreter-preservedapis.txt +++ b/tests/dotnet/UnitTests/expected/iOS-MonoVM-interpreter-preservedapis.txt @@ -113,7 +113,6 @@ Microsoft.iOS.dll:Foundation.NSObject..ctor() Microsoft.iOS.dll:Foundation.NSObject..ctor(Foundation.NSObjectFlag) Microsoft.iOS.dll:Foundation.NSObject..ctor(ObjCRuntime.NativeHandle, System.Boolean) Microsoft.iOS.dll:Foundation.NSObject..ctor(ObjCRuntime.NativeHandle) -Microsoft.iOS.dll:Foundation.NSObject.AllocateData() Microsoft.iOS.dll:Foundation.NSObject.AllocIfNeeded() Microsoft.iOS.dll:Foundation.NSObject.ClearHandle() Microsoft.iOS.dll:Foundation.NSObject.ConformsToProtocol(ObjCRuntime.NativeHandle) @@ -140,11 +139,9 @@ Microsoft.iOS.dll:Foundation.NSObject.get_Handle() Microsoft.iOS.dll:Foundation.NSObject.get_InFinalizerQueue() Microsoft.iOS.dll:Foundation.NSObject.get_IsDirectBinding() Microsoft.iOS.dll:Foundation.NSObject.get_IsRegisteredToggleRef() -Microsoft.iOS.dll:Foundation.NSObject.get_SuperHandle() Microsoft.iOS.dll:Foundation.NSObject.GetData() Microsoft.iOS.dll:Foundation.NSObject.GetHashCode() Microsoft.iOS.dll:Foundation.NSObject.GetNativeHash() -Microsoft.iOS.dll:Foundation.NSObject.GetSuper() Microsoft.iOS.dll:Foundation.NSObject.Initialize() Microsoft.iOS.dll:Foundation.NSObject.InitializeHandle(ObjCRuntime.NativeHandle, System.String, System.Boolean) Microsoft.iOS.dll:Foundation.NSObject.InitializeHandle(ObjCRuntime.NativeHandle, System.String) @@ -152,7 +149,6 @@ Microsoft.iOS.dll:Foundation.NSObject.InitializeObject(System.Boolean) Microsoft.iOS.dll:Foundation.NSObject.InvokeConformsToProtocol(ObjCRuntime.NativeHandle) Microsoft.iOS.dll:Foundation.NSObject.IsEqual(Foundation.NSObject) Microsoft.iOS.dll:Foundation.NSObject.IsProtocol(System.Type, System.IntPtr) -Microsoft.iOS.dll:Foundation.NSObject.RecreateDataHandle() Microsoft.iOS.dll:Foundation.NSObject.ReleaseManagedRef() Microsoft.iOS.dll:Foundation.NSObject.set_disposed(System.Boolean) Microsoft.iOS.dll:Foundation.NSObject.set_flags(Foundation.NSObject/Flags) @@ -191,16 +187,10 @@ Microsoft.iOS.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/X Microsoft.iOS.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/XamarinGCHandleFlags::InitialSet Microsoft.iOS.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/XamarinGCHandleFlags::None Microsoft.iOS.dll:Foundation.NSObjectData -Microsoft.iOS.dll:Foundation.NSObjectData* Foundation.NSObject::__data_for_mono Microsoft.iOS.dll:Foundation.NSObjectData* Foundation.NSObjectDataHandle::Data() Microsoft.iOS.dll:Foundation.NSObjectDataHandle -Microsoft.iOS.dll:Foundation.NSObjectDataHandle Foundation.NSObject::data_handle Microsoft.iOS.dll:Foundation.NSObjectDataHandle..ctor() -Microsoft.iOS.dll:Foundation.NSObjectDataHandle..ctor(System.IntPtr) Microsoft.iOS.dll:Foundation.NSObjectDataHandle.get_Data() -Microsoft.iOS.dll:Foundation.NSObjectDataHandle.get_IsInvalid() -Microsoft.iOS.dll:Foundation.NSObjectDataHandle.Invalidate() -Microsoft.iOS.dll:Foundation.NSObjectDataHandle.ReleaseHandle() Microsoft.iOS.dll:Foundation.NSObjectFlag Microsoft.iOS.dll:Foundation.NSObjectFlag Foundation.NSObjectFlag::Empty Microsoft.iOS.dll:Foundation.NSString @@ -251,6 +241,12 @@ Microsoft.iOS.dll:Foundation.RegisterAttribute.get_IsStubClass() Microsoft.iOS.dll:Foundation.RegisterAttribute.get_IsWrapper() Microsoft.iOS.dll:Foundation.RegisterAttribute.get_Name() Microsoft.iOS.dll:Foundation.RegisterAttribute.get_SkipRegistration() +Microsoft.iOS.dll:Foundation.TrackedMemory +Microsoft.iOS.dll:Foundation.TrackedMemory..ctor(System.UIntPtr) +Microsoft.iOS.dll:Foundation.TrackedMemory.CreateHandle(Foundation.NSObject) +Microsoft.iOS.dll:Foundation.TrackedMemory.Finalize() +Microsoft.iOS.dll:Foundation.TrackedMemory.get_Value() +Microsoft.iOS.dll:Foundation.TrackedMemory.set_Value(System.IntPtr) Microsoft.iOS.dll:Foundation.You_Should_Not_Call_base_In_This_Method Microsoft.iOS.dll:Foundation.You_Should_Not_Call_base_In_This_Method..ctor() Microsoft.iOS.dll:ObjCRuntime.__Registrar__ @@ -440,29 +436,29 @@ Microsoft.iOS.dll:ObjCRuntime.MarshalObjectiveCExceptionMode ObjCRuntime.Runtime Microsoft.iOS.dll:ObjCRuntime.Messaging Microsoft.iOS.dll:ObjCRuntime.Messaging.bool_objc_msgSend_IntPtr(System.IntPtr, System.IntPtr, System.IntPtr) Microsoft.iOS.dll:ObjCRuntime.Messaging.bool_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.iOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_IntPtr(System.IntPtr, System.IntPtr, System.IntPtr) -Microsoft.iOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.iOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_IntPtr(ObjCRuntime.ObjCSuper*, System.IntPtr, System.IntPtr) +Microsoft.iOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.iOS.dll:ObjCRuntime.Messaging.CGRect_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.iOS.dll:ObjCRuntime.Messaging.CGRect_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.iOS.dll:ObjCRuntime.Messaging.CGRect_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.iOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.iOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.iOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.iOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.iOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.iOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend_CGRect(System.IntPtr, System.IntPtr, CoreGraphics.CGRect) Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper_CGRect(System.IntPtr, System.IntPtr, CoreGraphics.CGRect) -Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper_CGRect(ObjCRuntime.ObjCSuper*, System.IntPtr, CoreGraphics.CGRect) +Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.iOS.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.iOS.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.iOS.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, ObjCRuntime.NativeHandle, System.Byte) Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_UIntPtr(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, System.UIntPtr) Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle_UIntPtr(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, System.UIntPtr) -Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle_UIntPtr(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle, System.UIntPtr) +Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.iOS.dll:ObjCRuntime.Method Microsoft.iOS.dll:ObjCRuntime.Method.get_ConstructorTrampoline() Microsoft.iOS.dll:ObjCRuntime.Method.get_DoubleTrampoline() @@ -497,8 +493,6 @@ Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::class_ptr Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::ClassHandle() Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::handle() Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::Handle() -Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::SuperHandle() -Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObjectData::classHandle Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObjectData::handle Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSString::class_ptr Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSString::ClassHandle() @@ -508,6 +502,8 @@ Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.DisposableObject::handle Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.DisposableObject::Handle() Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.INativeObject::Handle() Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.NativeHandle::Zero +Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.ObjCSuper::classHandle +Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.ObjCSuper::receiver Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Protocol::handle Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Protocol::Handle() Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Runtime/ClassHandles::unused @@ -553,6 +549,8 @@ Microsoft.iOS.dll:ObjCRuntime.ObjCException.get_Name() Microsoft.iOS.dll:ObjCRuntime.ObjCException.get_NSException() Microsoft.iOS.dll:ObjCRuntime.ObjCException.get_Reason() Microsoft.iOS.dll:ObjCRuntime.ObjCException.ToString() +Microsoft.iOS.dll:ObjCRuntime.ObjCSuper +Microsoft.iOS.dll:ObjCRuntime.ObjCSuper..ctor(Foundation.NSObject) Microsoft.iOS.dll:ObjCRuntime.Protocol Microsoft.iOS.dll:ObjCRuntime.Protocol._Xamarin_ConstructINativeObject(ObjCRuntime.NativeHandle, System.Boolean) Microsoft.iOS.dll:ObjCRuntime.Protocol..cctor() @@ -1207,8 +1205,6 @@ Microsoft.iOS.dll:System.Boolean Foundation.NSObject::IsDirectBinding() Microsoft.iOS.dll:System.Boolean Foundation.NSObject::IsRegisteredToggleRef() Microsoft.iOS.dll:System.Boolean Foundation.NSObject::RemoveFromObjectMap() Microsoft.iOS.dll:System.Boolean Foundation.NSObject/NSObject_Disposer::draining -Microsoft.iOS.dll:System.Boolean Foundation.NSObjectDataHandle::invalidated -Microsoft.iOS.dll:System.Boolean Foundation.NSObjectDataHandle::IsInvalid() Microsoft.iOS.dll:System.Boolean Foundation.ProtocolAttribute::k__BackingField Microsoft.iOS.dll:System.Boolean Foundation.ProtocolAttribute::k__BackingField Microsoft.iOS.dll:System.Boolean Foundation.ProtocolAttribute::IsInformal() @@ -1327,7 +1323,10 @@ Microsoft.iOS.dll:System.Int64 Foundation.NSComparisonResult::value__ Microsoft.iOS.dll:System.IntPtr CoreFoundation.CFArray::_CFNullHandle() Microsoft.iOS.dll:System.IntPtr CoreFoundation.CFRange::len Microsoft.iOS.dll:System.IntPtr CoreFoundation.CFRange::loc +Microsoft.iOS.dll:System.IntPtr Foundation.NSObject::__data Microsoft.iOS.dll:System.IntPtr Foundation.NSObject/NSObject_Disposer::class_ptr +Microsoft.iOS.dll:System.IntPtr Foundation.TrackedMemory::k__BackingField +Microsoft.iOS.dll:System.IntPtr Foundation.TrackedMemory::Value() Microsoft.iOS.dll:System.IntPtr ObjCRuntime.AdoptsAttribute::ProtocolHandle() Microsoft.iOS.dll:System.IntPtr ObjCRuntime.BlockCollector::block Microsoft.iOS.dll:System.IntPtr ObjCRuntime.Libraries/CoreFoundation::Handle @@ -1488,8 +1487,11 @@ Microsoft.iOS.dll:System.Reflection.MethodBase Registrar.Registrar::invoke_confo Microsoft.iOS.dll:System.Reflection.MethodBase Registrar.Registrar/ObjCMethod::Method Microsoft.iOS.dll:System.Reflection.PropertyInfo Registrar.Registrar/ObjCProperty::Property Microsoft.iOS.dll:System.Reflection.TypeFilter Registrar.SharedDynamic/<>c::<>9__0_0 +Microsoft.iOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 Foundation.NSObject::data_table +Microsoft.iOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 Foundation.NSObject::super_map Microsoft.iOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 ObjCRuntime.Runtime::block_lifetime_table Microsoft.iOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 ObjCRuntime.Class::assembly_to_name +Microsoft.iOS.dll:System.Runtime.InteropServices.GCHandle Foundation.TrackedMemory::handle Microsoft.iOS.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::height Microsoft.iOS.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::width Microsoft.iOS.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::x @@ -2710,14 +2712,12 @@ System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.Runtim System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.RuntimeFeature::k__BackingField System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.RuntimeFeature::IsDynamicCodeSupported() System.Private.CoreLib.dll:System.Boolean System.Runtime.DependentHandle::IsAllocated() -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::_isClosed -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::IsClosed() -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::IsInvalid() System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::BestFitMapping System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::ExactSpelling System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::PreserveSig System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::SetLastError System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::ThrowOnUnmappableChar +System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.GCHandle::IsAllocated() System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.SafeHandleMarshaller`1/ManagedToUnmanagedIn::_addRefd System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.SafeHandleMarshaller`1/ManagedToUnmanagedOut::_initialized System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.Utf8StringMarshaller/ManagedToUnmanagedIn::_allocated @@ -6888,7 +6888,6 @@ System.Private.CoreLib.dll:System.IntPtr System.Reflection.RuntimePropertyInfo:: System.Private.CoreLib.dll:System.IntPtr System.Reflection.RuntimePropertyInfo::prop System.Private.CoreLib.dll:System.IntPtr System.Runtime.CompilerServices.QCallAssembly::_assembly System.Private.CoreLib.dll:System.IntPtr System.Runtime.CompilerServices.QCallTypeHandle::_handle -System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.CriticalHandle::handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.GCHandle::_handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.SafeHandle::handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.WeakGCHandle`1::_handle @@ -10773,15 +10772,6 @@ System.Private.CoreLib.dll:System.Runtime.InteropServices.CollectionsMarshal System.Private.CoreLib.dll:System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault`2(System.Collections.Generic.Dictionary`2, TKey, out System.Boolean&) System.Private.CoreLib.dll:System.Runtime.InteropServices.ComImportAttribute System.Private.CoreLib.dll:System.Runtime.InteropServices.ComImportAttribute..ctor() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle..ctor(System.IntPtr) -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Cleanup() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Dispose() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Dispose(System.Boolean) -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Finalize() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.get_IsClosed() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.get_IsInvalid() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.ReleaseHandle() System.Private.CoreLib.dll:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute System.Private.CoreLib.dll:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute..ctor(System.Runtime.InteropServices.DllImportSearchPath) System.Private.CoreLib.dll:System.Runtime.InteropServices.DllImportAttribute @@ -10810,6 +10800,7 @@ System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Equals(System System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Equals(System.Runtime.InteropServices.GCHandle) System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Free() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.FromIntPtr(System.IntPtr) +System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.get_IsAllocated() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.get_Target() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.GetHandleValue(System.IntPtr) System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.GetHashCode() diff --git a/tests/dotnet/UnitTests/expected/iOS-MonoVM-interpreter-size.txt b/tests/dotnet/UnitTests/expected/iOS-MonoVM-interpreter-size.txt index ff794b9d49c7..93230234dc12 100644 --- a/tests/dotnet/UnitTests/expected/iOS-MonoVM-interpreter-size.txt +++ b/tests/dotnet/UnitTests/expected/iOS-MonoVM-interpreter-size.txt @@ -1,14 +1,14 @@ -AppBundleSize: 3,603,925 bytes (3,519.5 KB = 3.4 MB) +AppBundleSize: 3,603,385 bytes (3,518.9 KB = 3.4 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: _CodeSignature/CodeResources: 3,997 bytes (3.9 KB = 0.0 MB) archived-expanded-entitlements.xcent: 384 bytes (0.4 KB = 0.0 MB) -Info.plist: 1,147 bytes (1.1 KB = 0.0 MB) -Microsoft.iOS.dll: 155,136 bytes (151.5 KB = 0.1 MB) +Info.plist: 1,127 bytes (1.1 KB = 0.0 MB) +Microsoft.iOS.dll: 154,624 bytes (151.0 KB = 0.1 MB) PkgInfo: 8 bytes (0.0 KB = 0.0 MB) runtimeconfig.bin: 1,405 bytes (1.4 KB = 0.0 MB) -SizeTestApp: 2,390,848 bytes (2,334.8 KB = 2.3 MB) +SizeTestApp: 2,391,376 bytes (2,335.3 KB = 2.3 MB) SizeTestApp.dll: 7,680 bytes (7.5 KB = 0.0 MB) -System.Private.CoreLib.aotdata.arm64: 41,336 bytes (40.4 KB = 0.0 MB) -System.Private.CoreLib.dll: 988,672 bytes (965.5 KB = 0.9 MB) +System.Private.CoreLib.aotdata.arm64: 41,312 bytes (40.3 KB = 0.0 MB) +System.Private.CoreLib.dll: 988,160 bytes (965.0 KB = 0.9 MB) System.Runtime.dll: 5,120 bytes (5.0 KB = 0.0 MB) System.Runtime.InteropServices.dll: 8,192 bytes (8.0 KB = 0.0 MB) diff --git a/tests/dotnet/UnitTests/expected/iOS-MonoVM-preservedapis.txt b/tests/dotnet/UnitTests/expected/iOS-MonoVM-preservedapis.txt index b10321267993..5971b208e5d3 100644 --- a/tests/dotnet/UnitTests/expected/iOS-MonoVM-preservedapis.txt +++ b/tests/dotnet/UnitTests/expected/iOS-MonoVM-preservedapis.txt @@ -99,7 +99,6 @@ Microsoft.iOS.dll:Foundation.NSObject..ctor() Microsoft.iOS.dll:Foundation.NSObject..ctor(Foundation.NSObjectFlag) Microsoft.iOS.dll:Foundation.NSObject..ctor(ObjCRuntime.NativeHandle, System.Boolean) Microsoft.iOS.dll:Foundation.NSObject..ctor(ObjCRuntime.NativeHandle) -Microsoft.iOS.dll:Foundation.NSObject.AllocateData() Microsoft.iOS.dll:Foundation.NSObject.AllocIfNeeded() Microsoft.iOS.dll:Foundation.NSObject.ClearHandle() Microsoft.iOS.dll:Foundation.NSObject.ConformsToProtocol(ObjCRuntime.NativeHandle) @@ -125,18 +124,15 @@ Microsoft.iOS.dll:Foundation.NSObject.get_Handle() Microsoft.iOS.dll:Foundation.NSObject.get_InFinalizerQueue() Microsoft.iOS.dll:Foundation.NSObject.get_IsDirectBinding() Microsoft.iOS.dll:Foundation.NSObject.get_IsRegisteredToggleRef() -Microsoft.iOS.dll:Foundation.NSObject.get_SuperHandle() Microsoft.iOS.dll:Foundation.NSObject.GetData() Microsoft.iOS.dll:Foundation.NSObject.GetHashCode() Microsoft.iOS.dll:Foundation.NSObject.GetNativeHash() -Microsoft.iOS.dll:Foundation.NSObject.GetSuper() Microsoft.iOS.dll:Foundation.NSObject.Initialize() Microsoft.iOS.dll:Foundation.NSObject.InitializeHandle(ObjCRuntime.NativeHandle, System.String, System.Boolean) Microsoft.iOS.dll:Foundation.NSObject.InitializeHandle(ObjCRuntime.NativeHandle, System.String) Microsoft.iOS.dll:Foundation.NSObject.InitializeObject(System.Boolean) Microsoft.iOS.dll:Foundation.NSObject.InvokeConformsToProtocol(ObjCRuntime.NativeHandle) Microsoft.iOS.dll:Foundation.NSObject.IsEqual(Foundation.NSObject) -Microsoft.iOS.dll:Foundation.NSObject.RecreateDataHandle() Microsoft.iOS.dll:Foundation.NSObject.ReleaseManagedRef() Microsoft.iOS.dll:Foundation.NSObject.set_disposed(System.Boolean) Microsoft.iOS.dll:Foundation.NSObject.set_flags(Foundation.NSObject/Flags) @@ -174,16 +170,10 @@ Microsoft.iOS.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/X Microsoft.iOS.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/XamarinGCHandleFlags::InitialSet Microsoft.iOS.dll:Foundation.NSObject/XamarinGCHandleFlags Foundation.NSObject/XamarinGCHandleFlags::None Microsoft.iOS.dll:Foundation.NSObjectData -Microsoft.iOS.dll:Foundation.NSObjectData* Foundation.NSObject::__data_for_mono Microsoft.iOS.dll:Foundation.NSObjectData* Foundation.NSObjectDataHandle::Data() Microsoft.iOS.dll:Foundation.NSObjectDataHandle -Microsoft.iOS.dll:Foundation.NSObjectDataHandle Foundation.NSObject::data_handle Microsoft.iOS.dll:Foundation.NSObjectDataHandle..ctor() -Microsoft.iOS.dll:Foundation.NSObjectDataHandle..ctor(System.IntPtr) Microsoft.iOS.dll:Foundation.NSObjectDataHandle.get_Data() -Microsoft.iOS.dll:Foundation.NSObjectDataHandle.get_IsInvalid() -Microsoft.iOS.dll:Foundation.NSObjectDataHandle.Invalidate() -Microsoft.iOS.dll:Foundation.NSObjectDataHandle.ReleaseHandle() Microsoft.iOS.dll:Foundation.NSObjectFlag Microsoft.iOS.dll:Foundation.NSObjectFlag Foundation.NSObjectFlag::Empty Microsoft.iOS.dll:Foundation.ProtocolAttribute @@ -193,6 +183,12 @@ Microsoft.iOS.dll:Foundation.RegisterAttribute Microsoft.iOS.dll:Foundation.RegisterAttribute..ctor(System.String, System.Boolean) Microsoft.iOS.dll:Foundation.RegisterAttribute..ctor(System.String) Microsoft.iOS.dll:Foundation.RegisterAttribute.get_IsWrapper() +Microsoft.iOS.dll:Foundation.TrackedMemory +Microsoft.iOS.dll:Foundation.TrackedMemory..ctor(System.UIntPtr) +Microsoft.iOS.dll:Foundation.TrackedMemory.CreateHandle(Foundation.NSObject) +Microsoft.iOS.dll:Foundation.TrackedMemory.Finalize() +Microsoft.iOS.dll:Foundation.TrackedMemory.get_Value() +Microsoft.iOS.dll:Foundation.TrackedMemory.set_Value(System.IntPtr) Microsoft.iOS.dll:Foundation.You_Should_Not_Call_base_In_This_Method Microsoft.iOS.dll:Foundation.You_Should_Not_Call_base_In_This_Method..ctor() Microsoft.iOS.dll:ObjCRuntime.__Registrar__ @@ -348,17 +344,17 @@ Microsoft.iOS.dll:ObjCRuntime.MarshalObjectiveCExceptionMode ObjCRuntime.Runtime Microsoft.iOS.dll:ObjCRuntime.Messaging Microsoft.iOS.dll:ObjCRuntime.Messaging.bool_objc_msgSend_IntPtr(System.IntPtr, System.IntPtr, System.IntPtr) Microsoft.iOS.dll:ObjCRuntime.Messaging.bool_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) -Microsoft.iOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_IntPtr(System.IntPtr, System.IntPtr, System.IntPtr) -Microsoft.iOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) +Microsoft.iOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_IntPtr(ObjCRuntime.ObjCSuper*, System.IntPtr, System.IntPtr) +Microsoft.iOS.dll:ObjCRuntime.Messaging.bool_objc_msgSendSuper_NativeHandle(ObjCRuntime.ObjCSuper*, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.iOS.dll:ObjCRuntime.Messaging.CGRect_objc_msgSend(System.IntPtr, System.IntPtr) Microsoft.iOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.iOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.iOS.dll:ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend_CGRect(System.IntPtr, System.IntPtr, CoreGraphics.CGRect) Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.iOS.dll:ObjCRuntime.Messaging.NativeHandle_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.iOS.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSend(System.IntPtr, System.IntPtr) -Microsoft.iOS.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSendSuper(System.IntPtr, System.IntPtr) +Microsoft.iOS.dll:ObjCRuntime.Messaging.UIntPtr_objc_msgSendSuper(ObjCRuntime.ObjCSuper*, System.IntPtr) Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_NativeHandle_bool(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, ObjCRuntime.NativeHandle, System.Byte) Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle_UIntPtr(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle, System.UIntPtr) Microsoft.iOS.dll:ObjCRuntime.Messaging.void_objc_msgSend_NativeHandle(System.IntPtr, System.IntPtr, ObjCRuntime.NativeHandle) @@ -377,8 +373,6 @@ Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::class_ptr Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::ClassHandle() Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::handle() Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::Handle() -Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObject::SuperHandle() -Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObjectData::classHandle Microsoft.iOS.dll:ObjCRuntime.NativeHandle Foundation.NSObjectData::handle Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Class::handle Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Class::Handle() @@ -386,6 +380,8 @@ Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.DisposableObject::handle Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.DisposableObject::Handle() Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.INativeObject::Handle() Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.NativeHandle::Zero +Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.ObjCSuper::classHandle +Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.ObjCSuper::receiver Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Runtime/ClassHandles::unused Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Selector::handle Microsoft.iOS.dll:ObjCRuntime.NativeHandle ObjCRuntime.Selector::Handle() @@ -428,6 +424,8 @@ Microsoft.iOS.dll:ObjCRuntime.ObjCException.get_Name() Microsoft.iOS.dll:ObjCRuntime.ObjCException.get_NSException() Microsoft.iOS.dll:ObjCRuntime.ObjCException.get_Reason() Microsoft.iOS.dll:ObjCRuntime.ObjCException.ToString() +Microsoft.iOS.dll:ObjCRuntime.ObjCSuper +Microsoft.iOS.dll:ObjCRuntime.ObjCSuper..ctor(Foundation.NSObject) Microsoft.iOS.dll:ObjCRuntime.RegistrarHelper Microsoft.iOS.dll:ObjCRuntime.RegistrarHelper.ConstructINativeObject`1(System.Type, ObjCRuntime.NativeHandle, System.Boolean) Microsoft.iOS.dll:ObjCRuntime.RegistrarHelper.ConstructNSObject`1(System.Type, ObjCRuntime.NativeHandle) @@ -662,8 +660,6 @@ Microsoft.iOS.dll:System.Boolean Foundation.NSObject::InFinalizerQueue() Microsoft.iOS.dll:System.Boolean Foundation.NSObject::IsDirectBinding() Microsoft.iOS.dll:System.Boolean Foundation.NSObject::IsRegisteredToggleRef() Microsoft.iOS.dll:System.Boolean Foundation.NSObject/NSObject_Disposer::draining -Microsoft.iOS.dll:System.Boolean Foundation.NSObjectDataHandle::invalidated -Microsoft.iOS.dll:System.Boolean Foundation.NSObjectDataHandle::IsInvalid() Microsoft.iOS.dll:System.Boolean Foundation.ProtocolAttribute::k__BackingField Microsoft.iOS.dll:System.Boolean Foundation.RegisterAttribute::is_wrapper Microsoft.iOS.dll:System.Boolean Foundation.RegisterAttribute::IsWrapper() @@ -719,7 +715,10 @@ Microsoft.iOS.dll:System.Int32 ObjCRuntime.TransientString/Encoding::value__ Microsoft.iOS.dll:System.IntPtr CoreFoundation.CFArray::_CFNullHandle() Microsoft.iOS.dll:System.IntPtr CoreFoundation.CFRange::len Microsoft.iOS.dll:System.IntPtr CoreFoundation.CFRange::loc +Microsoft.iOS.dll:System.IntPtr Foundation.NSObject::__data Microsoft.iOS.dll:System.IntPtr Foundation.NSObject/NSObject_Disposer::class_ptr +Microsoft.iOS.dll:System.IntPtr Foundation.TrackedMemory::k__BackingField +Microsoft.iOS.dll:System.IntPtr Foundation.TrackedMemory::Value() Microsoft.iOS.dll:System.IntPtr ObjCRuntime.BlockCollector::block Microsoft.iOS.dll:System.IntPtr ObjCRuntime.Libraries/CoreFoundation::Handle Microsoft.iOS.dll:System.IntPtr ObjCRuntime.NativeHandle::handle @@ -848,8 +847,11 @@ Microsoft.iOS.dll:System.IntPtr* ObjCRuntime.Runtime/MTRegistrationMap::classHan Microsoft.iOS.dll:System.Object Foundation.NSObject/NSObject_Disposer::lock_obj Microsoft.iOS.dll:System.Object ObjCRuntime.Runtime::lock_obj Microsoft.iOS.dll:System.Reflection.Assembly Foundation.NSObject::PlatformAssembly +Microsoft.iOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 Foundation.NSObject::data_table +Microsoft.iOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 Foundation.NSObject::super_map Microsoft.iOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 ObjCRuntime.Runtime::block_lifetime_table Microsoft.iOS.dll:System.Runtime.CompilerServices.ConditionalWeakTable`2 ObjCRuntime.Class::assembly_to_name +Microsoft.iOS.dll:System.Runtime.InteropServices.GCHandle Foundation.TrackedMemory::handle Microsoft.iOS.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::height Microsoft.iOS.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::width Microsoft.iOS.dll:System.Runtime.InteropServices.NFloat CoreGraphics.CGRect::x @@ -1943,14 +1945,12 @@ System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.Nullab System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::k__BackingField System.Private.CoreLib.dll:System.Boolean System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::WrapNonExceptionThrows() System.Private.CoreLib.dll:System.Boolean System.Runtime.DependentHandle::IsAllocated() -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::_isClosed -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::IsClosed() -System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.CriticalHandle::IsInvalid() System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::BestFitMapping System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::ExactSpelling System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::PreserveSig System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::SetLastError System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.DllImportAttribute::ThrowOnUnmappableChar +System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.GCHandle::IsAllocated() System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.SafeHandleMarshaller`1/ManagedToUnmanagedIn::_addRefd System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.SafeHandleMarshaller`1/ManagedToUnmanagedOut::_initialized System.Private.CoreLib.dll:System.Boolean System.Runtime.InteropServices.Marshalling.Utf8StringMarshaller/ManagedToUnmanagedIn::_allocated @@ -5969,7 +5969,6 @@ System.Private.CoreLib.dll:System.IntPtr System.Reflection.RuntimePropertyInfo:: System.Private.CoreLib.dll:System.IntPtr System.Reflection.RuntimePropertyInfo::prop System.Private.CoreLib.dll:System.IntPtr System.Runtime.CompilerServices.QCallAssembly::_assembly System.Private.CoreLib.dll:System.IntPtr System.Runtime.CompilerServices.QCallTypeHandle::_handle -System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.CriticalHandle::handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.GCHandle::_handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.SafeHandle::handle System.Private.CoreLib.dll:System.IntPtr System.Runtime.InteropServices.WeakGCHandle`1::_handle @@ -8485,15 +8484,6 @@ System.Private.CoreLib.dll:System.Runtime.InteropServices.CollectionsMarshal System.Private.CoreLib.dll:System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault`2(System.Collections.Generic.Dictionary`2, TKey, out System.Boolean&) System.Private.CoreLib.dll:System.Runtime.InteropServices.ComImportAttribute System.Private.CoreLib.dll:System.Runtime.InteropServices.ComImportAttribute..ctor() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle..ctor(System.IntPtr) -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Cleanup() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Dispose() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Dispose(System.Boolean) -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.Finalize() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.get_IsClosed() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.get_IsInvalid() -System.Private.CoreLib.dll:System.Runtime.InteropServices.CriticalHandle.ReleaseHandle() System.Private.CoreLib.dll:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute System.Private.CoreLib.dll:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute..ctor(System.Runtime.InteropServices.DllImportSearchPath) System.Private.CoreLib.dll:System.Runtime.InteropServices.DllImportAttribute @@ -8521,6 +8511,7 @@ System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Equals(System System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Equals(System.Runtime.InteropServices.GCHandle) System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.Free() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.FromIntPtr(System.IntPtr) +System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.get_IsAllocated() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.get_Target() System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.GetHandleValue(System.IntPtr) System.Private.CoreLib.dll:System.Runtime.InteropServices.GCHandle.GetHashCode() diff --git a/tests/dotnet/UnitTests/expected/iOS-MonoVM-size.txt b/tests/dotnet/UnitTests/expected/iOS-MonoVM-size.txt index 6de64cd4b7d8..4b084761bcb9 100644 --- a/tests/dotnet/UnitTests/expected/iOS-MonoVM-size.txt +++ b/tests/dotnet/UnitTests/expected/iOS-MonoVM-size.txt @@ -1,17 +1,17 @@ -AppBundleSize: 9,338,369 bytes (9,119.5 KB = 8.9 MB) +AppBundleSize: 9,380,687 bytes (9,160.8 KB = 8.9 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: _CodeSignature/CodeResources: 5,229 bytes (5.1 KB = 0.0 MB) aot-instances.aotdata.arm64: 827,592 bytes (808.2 KB = 0.8 MB) archived-expanded-entitlements.xcent: 384 bytes (0.4 KB = 0.0 MB) -Info.plist: 1,147 bytes (1.1 KB = 0.0 MB) -Microsoft.iOS.aotdata.arm64: 22,992 bytes (22.5 KB = 0.0 MB) -Microsoft.iOS.dll: 49,152 bytes (48.0 KB = 0.0 MB) +Info.plist: 1,161 bytes (1.1 KB = 0.0 MB) +Microsoft.iOS.aotdata.arm64: 23,224 bytes (22.7 KB = 0.0 MB) +Microsoft.iOS.dll: 48,640 bytes (47.5 KB = 0.0 MB) PkgInfo: 8 bytes (0.0 KB = 0.0 MB) runtimeconfig.bin: 1,481 bytes (1.4 KB = 0.0 MB) -SizeTestApp: 7,235,120 bytes (7,065.5 KB = 6.9 MB) +SizeTestApp: 7,277,328 bytes (7,106.8 KB = 6.9 MB) SizeTestApp.aotdata.arm64: 1,464 bytes (1.4 KB = 0.0 MB) -SizeTestApp.dll: 7,168 bytes (7.0 KB = 0.0 MB) -System.Private.CoreLib.aotdata.arm64: 640,792 bytes (625.8 KB = 0.6 MB) +SizeTestApp.dll: 7,680 bytes (7.5 KB = 0.0 MB) +System.Private.CoreLib.aotdata.arm64: 640,656 bytes (625.6 KB = 0.6 MB) System.Private.CoreLib.dll: 530,944 bytes (518.5 KB = 0.5 MB) System.Runtime.aotdata.arm64: 784 bytes (0.8 KB = 0.0 MB) System.Runtime.dll: 5,120 bytes (5.0 KB = 0.0 MB) diff --git a/tests/dotnet/UnitTests/expected/iOS-NativeAOT-TrimmableStatic-size.txt b/tests/dotnet/UnitTests/expected/iOS-NativeAOT-TrimmableStatic-size.txt index 75389a923d59..5c14be37f20a 100644 --- a/tests/dotnet/UnitTests/expected/iOS-NativeAOT-TrimmableStatic-size.txt +++ b/tests/dotnet/UnitTests/expected/iOS-NativeAOT-TrimmableStatic-size.txt @@ -1,8 +1,8 @@ -AppBundleSize: 9,038,992 bytes (8,827.1 KB = 8.6 MB) +AppBundleSize: 9,124,974 bytes (8,911.1 KB = 8.7 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: _CodeSignature/CodeResources: 2,589 bytes (2.5 KB = 0.0 MB) archived-expanded-entitlements.xcent: 384 bytes (0.4 KB = 0.0 MB) -Info.plist: 1,147 bytes (1.1 KB = 0.0 MB) +Info.plist: 1,161 bytes (1.1 KB = 0.0 MB) PkgInfo: 8 bytes (0.0 KB = 0.0 MB) runtimeconfig.bin: 1,888 bytes (1.8 KB = 0.0 MB) -SizeTestApp: 9,032,976 bytes (8,821.3 KB = 8.6 MB) +SizeTestApp: 9,118,944 bytes (8,905.2 KB = 8.7 MB) diff --git a/tests/dotnet/UnitTests/expected/iOS-NativeAOT-size.txt b/tests/dotnet/UnitTests/expected/iOS-NativeAOT-size.txt index 565b3f18fafb..5cc462cd43e5 100644 --- a/tests/dotnet/UnitTests/expected/iOS-NativeAOT-size.txt +++ b/tests/dotnet/UnitTests/expected/iOS-NativeAOT-size.txt @@ -1,8 +1,8 @@ -AppBundleSize: 2,783,888 bytes (2,718.6 KB = 2.7 MB) +AppBundleSize: 2,784,380 bytes (2,719.1 KB = 2.7 MB) # The following list of files and their sizes is just informational / for review, and isn't used in the test: _CodeSignature/CodeResources: 2,589 bytes (2.5 KB = 0.0 MB) archived-expanded-entitlements.xcent: 384 bytes (0.4 KB = 0.0 MB) -Info.plist: 1,147 bytes (1.1 KB = 0.0 MB) +Info.plist: 1,127 bytes (1.1 KB = 0.0 MB) PkgInfo: 8 bytes (0.0 KB = 0.0 MB) runtimeconfig.bin: 1,808 bytes (1.8 KB = 0.0 MB) -SizeTestApp: 2,777,952 bytes (2,712.8 KB = 2.6 MB) +SizeTestApp: 2,778,464 bytes (2,713.3 KB = 2.6 MB) diff --git a/tests/dotnet/size-comparison/MauiForms/oldnet/MauiForms.iOS/AppDelegate.cs b/tests/dotnet/size-comparison/MauiForms/oldnet/MauiForms.iOS/AppDelegate.cs index ccb4afb87ee2..5630f317619e 100644 --- a/tests/dotnet/size-comparison/MauiForms/oldnet/MauiForms.iOS/AppDelegate.cs +++ b/tests/dotnet/size-comparison/MauiForms/oldnet/MauiForms.iOS/AppDelegate.cs @@ -18,7 +18,7 @@ public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsAppli // // You have 17 seconds to return from this method, or iOS will terminate your application. // - public override bool FinishedLaunching (UIApplication app, NSDictionary options) + public override bool FinishedLaunching (UIApplication app, NSDictionary? options) { global::Xamarin.Forms.Forms.Init (); LoadApplication (new App ()); diff --git a/tests/dotnet/size-comparison/MySingleView/AppDelegate.cs b/tests/dotnet/size-comparison/MySingleView/AppDelegate.cs index 8e84ee355b6a..de6407594ee7 100644 --- a/tests/dotnet/size-comparison/MySingleView/AppDelegate.cs +++ b/tests/dotnet/size-comparison/MySingleView/AppDelegate.cs @@ -5,11 +5,13 @@ namespace MyComparableApp { public partial class AppDelegate : UIApplicationDelegate { - UIWindow window; + UIWindow? window; - public override bool FinishedLaunching (UIApplication app, NSDictionary options) + public override bool FinishedLaunching (UIApplication app, NSDictionary? options) { +#pragma warning disable CA1422 window = new UIWindow (UIScreen.MainScreen.Bounds); +#pragma warning restore CA1422 var dvc = new UIViewController (); var button = new UIButton (window.Bounds); diff --git a/tests/framework-test/FrameworkTests.cs b/tests/framework-test/FrameworkTests.cs index da279d818e21..6092954415c4 100644 --- a/tests/framework-test/FrameworkTests.cs +++ b/tests/framework-test/FrameworkTests.cs @@ -19,10 +19,10 @@ public class FrameworkTests { [Test] public void CFunction () { - Assert.AreEqual (42, CFunctions.theUltimateAnswer (), "a"); + Assert.That (CFunctions.theUltimateAnswer (), Is.EqualTo (42), "a"); #if !__MACOS__ - Assert.AreEqual (42, CFunctions.object_theUltimateAnswer (), "object"); - Assert.AreEqual (42, CFunctions.ar_theUltimateAnswer (), "ar"); + Assert.That (CFunctions.object_theUltimateAnswer (), Is.EqualTo (42), "object"); + Assert.That (CFunctions.ar_theUltimateAnswer (), Is.EqualTo (42), "ar"); #endif } @@ -30,7 +30,7 @@ public void CFunction () public void ObjCClass () { using (var obj = new FrameworkTest ()) { - Assert.AreEqual (42, obj.Func (), "a"); + Assert.That (obj.Func (), Is.EqualTo (42), "a"); } } } diff --git a/tests/fsharp/FSharpTests.fs b/tests/fsharp/FSharpTests.fs index ed4c75bb2031..5e05fcec9dc8 100644 --- a/tests/fsharp/FSharpTests.fs +++ b/tests/fsharp/FSharpTests.fs @@ -24,4 +24,4 @@ type FSharpTest () = let e = 5555 let pr = sprintf "%d %d %d %d %d" a b c d e - Assert.AreEqual ("1111 2222 3333 4444 5555", pr) + Assert.That (pr, Is.EqualTo ("1111 2222 3333 4444 5555")) diff --git a/tests/interdependent-binding-projects/Main.cs b/tests/interdependent-binding-projects/Main.cs index 2c08bd2dc725..892a12493f39 100644 --- a/tests/interdependent-binding-projects/Main.cs +++ b/tests/interdependent-binding-projects/Main.cs @@ -15,6 +15,6 @@ static partial void AddTestAssembliesImpl (HashSet assemblies) public class LoaderTest { public void TestAssemblyCount () { - Assert.AreEqual (3, TestLoader.GetTestAssemblies ().Count (), "Test assembly count"); + Assert.That (TestLoader.GetTestAssemblies ().Count (), Is.EqualTo (3), "Test assembly count"); } } diff --git a/tests/interdependent-binding-projects/dotnet/shared.csproj b/tests/interdependent-binding-projects/dotnet/shared.csproj index 5e4008911365..3e45c81d0def 100644 --- a/tests/interdependent-binding-projects/dotnet/shared.csproj +++ b/tests/interdependent-binding-projects/dotnet/shared.csproj @@ -27,10 +27,6 @@ $(NoWarn);CS8002 - - - true - Nullable diff --git a/tests/introspection/ApiBaseTest.cs b/tests/introspection/ApiBaseTest.cs index 02cd37df96cd..2c59f52b1ae3 100644 --- a/tests/introspection/ApiBaseTest.cs +++ b/tests/introspection/ApiBaseTest.cs @@ -101,7 +101,7 @@ protected TextWriter Writer { #if MONOMAC get { return Console.Out; } #else - get { return AppDelegate.Runner.Writer!; } + get { return AppDelegate.Runner!.Writer!; } #endif } @@ -109,7 +109,7 @@ protected TextWriter Writer { protected void ReportError (string s, params object? [] parameters) { if (!ContinueOnFailure) - Assert.Fail (s, parameters); + Assert.Fail (string.Format (s, parameters)); else { Writer.Write ("[FAIL] "); Writer.WriteLine (s, parameters); @@ -158,6 +158,7 @@ protected virtual bool SkipDueToAttribute (MemberInfo? member) return false; return !member.IsAvailableOnHostPlatform () || + !member.IsAvailableInSimulator () || SkipDueToAttribute (member.DeclaringType) || SkipDueToAttributeInProperty (member); } diff --git a/tests/introspection/ApiCMAttachmentTest.cs b/tests/introspection/ApiCMAttachmentTest.cs index a375ad550856..b8d243321409 100644 --- a/tests/introspection/ApiCMAttachmentTest.cs +++ b/tests/introspection/ApiCMAttachmentTest.cs @@ -548,9 +548,9 @@ public void CheckAttachments () obj.SetAttachment ("key", attch, CMAttachmentMode.ShouldNotPropagate); using (var otherAttch = obj.GetAttachment ("key", out otherMode)!) { obj.RemoveAllAttachments (); - Assert.AreEqual (mode, otherMode); - Assert.IsNotNull (otherAttch, "For type {0}", t.Name); - Assert.AreEqual (attch.ToString (), otherAttch.ToString (), "For type {0}", t.Name); + Assert.That (otherMode, Is.EqualTo (mode)); + Assert.That (otherAttch, Is.Not.Null, $"For type {t.Name}"); + Assert.That (otherAttch.ToString (), Is.EqualTo (attch.ToString ()), "For type {0}", t.Name); } } if (obj is IDisposable disp) { @@ -575,7 +575,7 @@ public void CheckFailAttachments () continue; var n = GetINativeInstance (t); if (n is null) - Assert.Fail ("Could not create instance of '{0}'.", t); + Assert.Fail ($"Could not create instance of '{t}'."); var obj = new AttachableNativeObject (n!); Assert.That (obj.Handle, Is.Not.EqualTo (IntPtr.Zero), t.Name + ".Handle"); using (var attch = new CFString ("myAttch")) { @@ -583,7 +583,7 @@ public void CheckFailAttachments () obj.SetAttachment ("key", attch, CMAttachmentMode.ShouldNotPropagate); using (var otherAttch = obj.GetAttachment ("key", out otherMode)) { obj.RemoveAllAttachments (); - Assert.Null (otherAttch, "For type {0}", t.Name); + Assert.That (otherAttch, Is.Null, $"For type {t.Name}"); } } if (t is IDisposable disp) { diff --git a/tests/introspection/ApiClassPtrTest.cs b/tests/introspection/ApiClassPtrTest.cs index bace683cfc92..2a718408526d 100644 --- a/tests/introspection/ApiClassPtrTest.cs +++ b/tests/introspection/ApiClassPtrTest.cs @@ -81,7 +81,7 @@ public void VerifyClassPtr () IntPtr class_ptr = (IntPtr) (NativeHandle) fi.GetValue (null)!; IntPtr register_class_ptr = GetClassPtrFromRegister (t); - Assert.AreEqual (class_ptr, register_class_ptr, "class_ptr and RegisterAttribute are different: " + t.Name); + Assert.That (register_class_ptr, Is.EqualTo (class_ptr), "class_ptr and RegisterAttribute are different: " + t.Name); } } @@ -104,7 +104,7 @@ public void VerifyClassPtrCategories () else extended_class_ptr = GetClassPtrFromRegister (extendedType); - Assert.AreEqual (class_ptr, extended_class_ptr, "class_ptr and RegisterAttribute from extended class are different: " + t.Name); + Assert.That (extended_class_ptr, Is.EqualTo (class_ptr), "class_ptr and RegisterAttribute from extended class are different: " + t.Name); } } } diff --git a/tests/introspection/ApiCoreImageFiltersTest.cs b/tests/introspection/ApiCoreImageFiltersTest.cs index 0915d646eabf..a7f7114ff9fe 100644 --- a/tests/introspection/ApiCoreImageFiltersTest.cs +++ b/tests/introspection/ApiCoreImageFiltersTest.cs @@ -98,7 +98,7 @@ public void CheckNativeFilters () } n++; } - Assert.That (filters.Count, Is.EqualTo (0), "{0} native filters missing: {1}", filters.Count, String.Join (", ", filters)); + Assert.That (filters.Count, Is.EqualTo (0), $"{filters.Count} native filters missing: {String.Join (", ", filters)}"); } [Test] @@ -149,7 +149,7 @@ public void CheckManagedFilters () if (Skip (filters [i])) filters.RemoveAt (i); } - Assert.That (filters.Count, Is.EqualTo (0), "Managed filters not found for {0}", String.Join (", ", filters)); + Assert.That (filters.Count, Is.EqualTo (0), $"Managed filters not found for {String.Join (", ", filters)}"); } static void GenerateBinding (NSObject filter, TextWriter writer) @@ -366,7 +366,7 @@ public void Protocols () if (to_confirm_manually.Length > 0) { Console.WriteLine (to_confirm_manually); } - Assert.AreEqual (0, Errors, "{0} potential errors found{1}", Errors, Errors == 0 ? string.Empty : ":\n" + ErrorData.ToString () + "\n"); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} potential errors found:\n{ErrorData}\n"); } [Test] @@ -535,7 +535,7 @@ public void Keys () ReportError ($"{t.Name}: Property `{po.Name}` should NOT have a setter."); } } - Assert.AreEqual (0, Errors, "{0} potential errors found{1}", Errors, Errors == 0 ? string.Empty : ":\n" + ErrorData.ToString () + "\n"); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} potential errors found:\n{ErrorData}\n"); } } } diff --git a/tests/introspection/ApiCtorInitTest.cs b/tests/introspection/ApiCtorInitTest.cs index 53a9b0d0ca5c..2d218ec6ae11 100644 --- a/tests/introspection/ApiCtorInitTest.cs +++ b/tests/introspection/ApiCtorInitTest.cs @@ -150,83 +150,12 @@ protected virtual bool Skip (Type type) case "ASAccountAuthenticationModificationController": return true; // started failing in Xcode 16.3 beta 1 for unknown reasons (it works in an Xcode project). #if __TVOS__ - case "MTLAccelerationStructureDescriptor": - case "MTLAccelerationStructureGeometryDescriptor": - case "MTLAccelerationStructureMotionBoundingBoxGeometryDescriptor": - case "MTLAccelerationStructureMotionTriangleGeometryDescriptor": - case "MTLAccelerationStructurePassDescriptor": - case "MTLAccelerationStructurePassSampleBufferAttachmentDescriptor": - case "MTLAccelerationStructurePassSampleBufferAttachmentDescriptorArray": - case "MTLAccelerationStructureTriangleGeometryDescriptor": - case "MTLMeshRenderPipelineDescriptor": - case "MTLMotionKeyframeData": - case "MTLRasterizationRateLayerArray": - case "MTLRasterizationRateMapDescriptor": - case "MTLRasterizationRateSampleArray": - case "MTLRenderPipelineFunctionsDescriptor": - case "MTLResourceStatePassSampleBufferAttachmentDescriptor": - case "MTLResourceStatePassSampleBufferAttachmentDescriptorArray": - // The initial tvOS 16.0 simulator doesn't have these classes, but the tvOS 16.1 simulator doess - if (TestRuntime.IsSimulator && !TestRuntime.CheckXcodeVersion (14, 1)) - return true; - break; case "CIPersonSegmentation": // removed in Xcode 26? case "CISaliencyMapFilter": // removed in Xcode 26? return TestRuntime.CheckXcodeVersion (26, 0); #endif case "PhaseConeDirectivityModelParameters": return !TestRuntime.IsSimulator; // fails on device - case "MTL4AccelerationStructureBoundingBoxGeometryDescriptor": - case "MTL4AccelerationStructureCurveGeometryDescriptor": - case "MTL4AccelerationStructureDescriptor": - case "MTL4AccelerationStructureGeometryDescriptor": - case "MTL4AccelerationStructureMotionBoundingBoxGeometryDescriptor": - case "MTL4AccelerationStructureMotionCurveGeometryDescriptor": - case "MTL4AccelerationStructureMotionTriangleGeometryDescriptor": - case "MTL4AccelerationStructureTriangleGeometryDescriptor": - case "MTL4ArgumentTableDescriptor": - case "MTL4BinaryFunctionDescriptor": - case "MTL4CommandAllocatorDescriptor": - case "MTL4CommandBufferOptions": - case "MTL4CommandQueueDescriptor": - case "MTL4CommitOptions": - case "MTL4CompilerDescriptor": - case "MTL4CompilerTaskOptions": - case "MTL4ComputePipelineDescriptor": - case "MTL4CounterHeapDescriptor": - case "MTL4FunctionDescriptor": - case "MTL4IndirectInstanceAccelerationStructureDescriptor": - case "MTL4InstanceAccelerationStructureDescriptor": - case "MTL4LibraryDescriptor": - case "MTL4LibraryFunctionDescriptor": - case "MTL4MachineLearningPipelineDescriptor": - case "MTL4MachineLearningPipelineReflection": - case "MTL4MeshRenderPipelineDescriptor": - case "MTL4PipelineDataSetSerializerDescriptor": - case "MTL4PipelineDescriptor": - case "MTL4PipelineOptions": - case "MTL4PipelineStageDynamicLinkingDescriptor": - case "MTL4PrimitiveAccelerationStructureDescriptor": - case "MTL4RenderPassDescriptor": - case "MTL4RenderPipelineBinaryFunctionsDescriptor": - case "MTL4RenderPipelineColorAttachmentDescriptor": - case "MTL4RenderPipelineColorAttachmentDescriptorArray": - case "MTL4RenderPipelineDescriptor": - case "MTL4RenderPipelineDynamicLinkingDescriptor": - case "MTL4SpecializedFunctionDescriptor": - case "MTL4StaticLinkingDescriptor": - case "MTL4StitchedFunctionDescriptor": - case "MTL4TileRenderPipelineDescriptor": - case "MTLLogicalToPhysicalColorAttachmentMap": - case "MTLResourceViewPoolDescriptor": - case "MTLTensorDescriptor": - case "MTLTensorReferenceType": - case "MTLTextureViewDescriptor": - case "MTLFXFrameInterpolatorDescriptor": - case "MTLFXTemporalDenoisedScalerDescriptor": - if (TestRuntime.IsSimulator) - return true; - break; } switch (type.Namespace) { @@ -390,7 +319,7 @@ public void DefaultCtorAllowed () } n++; } - Assert.AreEqual (0, Errors, "{0} potential errors found in {1} default ctor validated{2}", Errors, n, Errors == 0 ? string.Empty : ":\n" + ErrorData.ToString () + "\n"); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} potential errors found in {n} default ctor validated:\n{ErrorData}\n"); } // .NET constructors are not virtual, so we need to re-expose the base class .ctor when a subclass is created. @@ -442,7 +371,7 @@ public void DesignatedInitializer () n++; } } - Assert.AreEqual (0, Errors, "{0} potential errors found in {1} designated initializer validated", Errors, n); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} potential errors found in {n} designated initializer validated"); } protected virtual bool Match (ConstructorInfo ctor, Type type) @@ -710,7 +639,7 @@ public void ShouldNotExposeDefaultCtorTest () } n++; } - Assert.AreEqual (0, Errors, $"{Errors} potential errors found in {n} BaseType empty ctor validated: \n{ErrorData}\n{(genObjCTestCode ? $"\n\n{objCCode}\n" : string.Empty)}"); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} potential errors found in {n} BaseType empty ctor validated: \n{ErrorData}\n{(genObjCTestCode ? $"\n\n{objCCode}\n" : string.Empty)}"); } protected virtual bool SkipCheckShouldNotExposeDefaultCtor (Type type) @@ -752,7 +681,7 @@ public void ARAnchorCopyingCtorTest () ReportError ("{0} should re-expose IARAnchorCopying::.ctor(ARAnchor)", t); } - Assert.AreEqual (0, Errors, "{0} potential errors found when validating if subclasses of 'ARAnchor' re-expose 'IARAnchorCopying' constructor", Errors); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} potential errors found when validating if subclasses of 'ARAnchor' re-expose 'IARAnchorCopying' constructor"); } #endif } diff --git a/tests/introspection/ApiFieldTest.cs b/tests/introspection/ApiFieldTest.cs index 1cb1b0fb715e..1c2ffebdc05d 100644 --- a/tests/introspection/ApiFieldTest.cs +++ b/tests/introspection/ApiFieldTest.cs @@ -75,14 +75,6 @@ protected virtual bool Skip (PropertyInfo property) default: return false; } - case "CMSampleAttachmentKey": // kCMSampleAttachmentKey_HDR10PlusPerFrameData": - switch (property.Name) { - case "Hdr10PlusPerFrameDataKey": - if (TestRuntime.IsSimulator) - return !TestRuntime.CheckXcodeVersion (14, 1); // not available in the iOS 16.0 simulator, but it is in the iOS 16.1 simulator - break; - } - break; } return SkipDueToAttribute (property); } @@ -208,7 +200,7 @@ public void Notifications () } n++; } - Assert.AreEqual (0, Errors, "{0} errors found in {1} fields validated: {2}", Errors, n, string.Join (", ", failed_fields)); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} errors found in {n} fields validated: {string.Join (", ", failed_fields)}"); } [Test] @@ -233,7 +225,7 @@ public void NonNullNSStringFields () } n++; } - Assert.AreEqual (0, Errors, "{0} errors found in {1} fields validated: {2}", Errors, n, string.Join (", ", failed_fields)); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} errors found in {n} fields validated: {string.Join (", ", failed_fields)}"); } [Test] @@ -272,7 +264,7 @@ public void FieldExists () Dlfcn.dlclose (lib); n++; } - Assert.AreEqual (0, Errors, "{0} errors found in {1} fields validated: {2}", Errors, n, string.Join (", ", failed_fields)); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} errors found in {n} fields validated: {string.Join (", ", failed_fields)}"); } } } diff --git a/tests/introspection/ApiPInvokeTest.cs b/tests/introspection/ApiPInvokeTest.cs index 6d1df017699c..65d216667185 100644 --- a/tests/introspection/ApiPInvokeTest.cs +++ b/tests/introspection/ApiPInvokeTest.cs @@ -170,13 +170,13 @@ public void SymbolExists () IntPtr lib = Dlfcn.dlopen (path, 0); if (Dlfcn.GetIndirect (lib, name) == IntPtr.Zero && !failed_api.Contains (name)) { - ReportError ("Could not find the field '{0}' in {1}", name, path); + ReportError ("Could not find the symbol '{0}' in {1}", name, path); failed_api.Add (name); } Dlfcn.dlclose (lib); n++; } - Assert.AreEqual (0, Errors, "{0} errors found in {1} functions validated: {2}", Errors, n, string.Join (", ", failed_api)); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} errors found in {n} functions validated: {string.Join (", ", failed_api)}"); } bool SkipDueToDeviceCapabilities (Type type) @@ -282,7 +282,7 @@ protected void Check (Assembly a) n++; } } - Assert.AreEqual (0, Errors, "{0} errors found in {1} symbol lookups{2}", Errors, n, Errors == 0 ? string.Empty : ":\n" + ErrorData.ToString () + "\n"); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} errors found in {n} symbol lookups:\n{ErrorData}\n"); } protected string ResolveLibrarySymlinks (string path) diff --git a/tests/introspection/ApiProtocolTest.cs b/tests/introspection/ApiProtocolTest.cs index 8794ab944bf1..e556f72676a2 100644 --- a/tests/introspection/ApiProtocolTest.cs +++ b/tests/introspection/ApiProtocolTest.cs @@ -38,10 +38,6 @@ protected virtual bool Skip (Type type) if (TestRuntime.IsSimulatorOrDesktop) return true; break; - case "SafetyKit": - if (TestRuntime.IsSimulator) - return !TestRuntime.CheckXcodeVersion (15, 0); // doesn't seem to be available in the iOS simulator until iOS 17+ - break; case "SensorKit": // SensorKit doesn't exist on iPads if (TestRuntime.IsDevice && TestRuntime.IsiPad) return true; @@ -67,108 +63,12 @@ protected virtual bool Skip (Type type) // was removed by apple and is a compat class. case "HMMatterRequestHandler": return true; - case "CIFilterGenerator": - // only present on device :/ - return TestRuntime.IsSimulatorOrDesktop; #if !XAMCORE_5_0 case "GKHybridStrategist": // We removed the bindings for this type. return true; #endif -#if __TVOS__ - case "MTLAccelerationStructureBoundingBoxGeometryDescriptor": - case "MTLAccelerationStructureDescriptor": - case "MTLAccelerationStructureGeometryDescriptor": - case "MTLAccelerationStructureMotionBoundingBoxGeometryDescriptor": - case "MTLAccelerationStructureMotionTriangleGeometryDescriptor": - case "MTLAccelerationStructurePassDescriptor": - case "MTLAccelerationStructurePassSampleBufferAttachmentDescriptor": - case "MTLAccelerationStructurePassSampleBufferAttachmentDescriptorArray": - case "MTLAccelerationStructureTriangleGeometryDescriptor": - case "MTLInstanceAccelerationStructureDescriptor": - case "MTLIntersectionFunctionDescriptor": - case "MTLIntersectionFunctionTableDescriptor": - case "MTLMeshRenderPipelineDescriptor": - case "MTLMotionKeyframeData": - case "MTLPrimitiveAccelerationStructureDescriptor": - case "MTLRasterizationRateLayerArray": - case "MTLRasterizationRateLayerDescriptor": - case "MTLRasterizationRateMapDescriptor": - case "MTLRasterizationRateSampleArray": - case "MTLRenderPipelineFunctionsDescriptor": - case "MTLResourceStatePassDescriptor": - case "MTLResourceStatePassSampleBufferAttachmentDescriptor": - case "MTLResourceStatePassSampleBufferAttachmentDescriptorArray": - case "MTLVisibleFunctionTableDescriptor": - // The initial tvOS 16.0 simulator doesn't have these classes, but the tvOS 16.1 simulator doess - if (TestRuntime.IsSimulator && !TestRuntime.CheckXcodeVersion (14, 1)) - return true; - goto default; -#endif - case "MTL4AccelerationStructureBoundingBoxGeometryDescriptor": - case "MTL4AccelerationStructureCurveGeometryDescriptor": - case "MTL4AccelerationStructureDescriptor": - case "MTL4AccelerationStructureGeometryDescriptor": - case "MTL4AccelerationStructureMotionBoundingBoxGeometryDescriptor": - case "MTL4AccelerationStructureMotionCurveGeometryDescriptor": - case "MTL4AccelerationStructureMotionTriangleGeometryDescriptor": - case "MTL4AccelerationStructureTriangleGeometryDescriptor": - case "MTL4ArgumentTableDescriptor": - case "MTL4BinaryFunctionDescriptor": - case "MTL4CommandAllocatorDescriptor": - case "MTL4CommandBufferOptions": - case "MTL4CommandQueueDescriptor": - case "MTL4CommitOptions": - case "MTL4CompilerDescriptor": - case "MTL4CompilerTaskOptions": - case "MTL4ComputePipelineDescriptor": - case "MTL4CounterHeapDescriptor": - case "MTL4FunctionDescriptor": - case "MTL4IndirectInstanceAccelerationStructureDescriptor": - case "MTL4InstanceAccelerationStructureDescriptor": - case "MTL4LibraryDescriptor": - case "MTL4LibraryFunctionDescriptor": - case "MTL4MachineLearningPipelineDescriptor": - case "MTL4MachineLearningPipelineReflection": - case "MTL4MeshRenderPipelineDescriptor": - case "MTL4PipelineDataSetSerializerDescriptor": - case "MTL4PipelineDescriptor": - case "MTL4PipelineOptions": - case "MTL4PipelineStageDynamicLinkingDescriptor": - case "MTL4PrimitiveAccelerationStructureDescriptor": - case "MTL4RenderPassDescriptor": - case "MTL4RenderPipelineBinaryFunctionsDescriptor": - case "MTL4RenderPipelineColorAttachmentDescriptor": - case "MTL4RenderPipelineColorAttachmentDescriptorArray": - case "MTL4RenderPipelineDescriptor": - case "MTL4RenderPipelineDynamicLinkingDescriptor": - case "MTL4SpecializedFunctionDescriptor": - case "MTL4StaticLinkingDescriptor": - case "MTL4StitchedFunctionDescriptor": - case "MTL4TileRenderPipelineDescriptor": - case "MTLLogicalToPhysicalColorAttachmentMap": - case "MTLResourceViewPoolDescriptor": - case "MTLTensorDescriptor": - case "MTLTensorExtents": - case "MTLTensorReferenceType": - case "MTLTextureViewDescriptor": - case "VTFrameRateConversionConfiguration": - case "VTFrameRateConversionParameters": - case "VTLowLatencyFrameInterpolationConfiguration": - case "VTLowLatencyFrameInterpolationParameters": - case "VTLowLatencySuperResolutionScalerConfiguration": - case "VTLowLatencySuperResolutionScalerParameters": - case "VTMotionBlurConfiguration": - case "VTMotionBlurParameters": - case "VTOpticalFlowConfiguration": - case "VTOpticalFlowParameters": - case "VTSuperResolutionScalerConfiguration": - case "VTSuperResolutionScalerParameters": - case "VTTemporalNoiseFilterConfiguration": - case "VTTemporalNoiseFilterParameters": - if (TestRuntime.IsSimulator) - return true; - goto default; + default: return SkipDueToAttribute (type); } @@ -946,7 +846,7 @@ protected virtual bool Skip (Type type, string protocolName) void CheckProtocol (string protocolName, Action action) { IntPtr protocol = Runtime.GetProtocol (protocolName); - Assert.AreNotEqual (protocol, IntPtr.Zero, protocolName); + Assert.That (IntPtr.Zero, Is.Not.EqualTo (protocol), protocolName); int n = 0; foreach (Type t in Assembly.GetTypes ()) { @@ -981,7 +881,7 @@ public void Coding () // FIXME: and implement the .ctor(NSCoder) } }); - Assert.AreEqual (Errors, 0, "{0} types conforms to NSCoding but does not implement INSCoding: {1}", Errors, String.Join ('\n', list)); + Assert.That (0, Is.EqualTo (Errors), $"{Errors} types conforms to NSCoding but does not implement INSCoding: {String.Join ('\n', list)}"); } // [Test] -> iOS 6.0+ and Mountain Lion (10.8) + @@ -998,7 +898,7 @@ public virtual void SecureCoding () } } }); - Assert.AreEqual (Errors, 0, "{0} types conforms to NSSecureCoding but does not implement INSSecureCoding: {1}", Errors, String.Join ('\n', list)); + Assert.That (0, Is.EqualTo (Errors), $"{Errors} types conforms to NSSecureCoding but does not implement INSSecureCoding: {String.Join ('\n', list)}"); } bool SupportsSecureCoding (Type type) @@ -1022,7 +922,6 @@ public virtual void SupportsSecureCoding () // check that +supportsSecureCoding returns YES if (!supports) { #if __IOS__ && !__MACCATALYST__ - // broken in xcode 12 beta 1 simulator (only) if (TestRuntime.IsSimulator) { switch (type.Name) { case "ARFaceGeometry": @@ -1042,11 +941,11 @@ public virtual void SupportsSecureCoding () } else if (type.IsPublic && supports) { // there are internal types, e.g. DataWrapper : NSData, that subclass NSSecureCoding-types without // [re-]declaring their allegiance - but we can live with those small betrayals - Assert.IsFalse (NSSecureCoding.SupportsSecureCoding (type), "{0} !SupportsSecureCoding", type.Name); + Assert.That (NSSecureCoding.SupportsSecureCoding (type), Is.False, $"{type.Name} !SupportsSecureCoding"); ReportError ("SupportsSecureCoding returns true but {0} does not conforms to NSSecureCoding", type.Name); } }); - Assert.AreEqual (Errors, 0, "{0} types conforms to NSCoding but does not implement INSSecureCoding", Errors); + Assert.That (0, Is.EqualTo (Errors), $"{Errors} types conforms to NSCoding but does not implement INSSecureCoding"); } [Test] @@ -1065,7 +964,7 @@ public void Copying () } } }); - Assert.AreEqual (Errors, 0, "{0} types conforms to NSCopying but does not implement INSCopying: {1}", Errors, String.Join ('\n', list)); + Assert.That (0, Is.EqualTo (Errors), $"{Errors} types conforms to NSCopying but does not implement INSCopying: {String.Join ('\n', list)}"); } [Test] @@ -1084,7 +983,7 @@ public void MutableCopying () } } }); - Assert.AreEqual (Errors, 0, "{0} types conforms to NSMutableCopying but does not implement INSMutableCopying: {1}", Errors, String.Join ('\n', list)); + Assert.That (0, Is.EqualTo (Errors), $"{Errors} types conforms to NSMutableCopying but does not implement INSMutableCopying: {String.Join ('\n', list)}"); } [Test] @@ -1106,21 +1005,6 @@ public void GeneralCase () switch (t.Name) { case "AVPlayerInterstitialEventMonitor": // deprecated continue; -#if !MONOMAC - case "MTLCaptureManager": - case "NEHotspotConfiguration": - case "NEHotspotConfigurationManager": - case "NEHotspotEapSettings": - case "NEHotspotHS20Settings": - case "SCNGeometryTessellator": - case "SKRenderer": - // was not possible in iOS 11.4 (current minimum) simulator - if (!TestRuntime.CheckXcodeVersion (12, 0)) { - if (TestRuntime.IsSimulatorOrDesktop) - continue; - } - break; -#endif default: var e = $"[FAIL] Could not load {t.FullName}"; list.Add (e); diff --git a/tests/introspection/ApiSelectorTest.cs b/tests/introspection/ApiSelectorTest.cs index 6a453e03f8a6..d22c7b8829d2 100644 --- a/tests/introspection/ApiSelectorTest.cs +++ b/tests/introspection/ApiSelectorTest.cs @@ -46,10 +46,6 @@ protected virtual bool Skip (Type type) } switch (type.Namespace) { - case "SafetyKit": - if (TestRuntime.IsSimulator) - return !TestRuntime.CheckXcodeVersion (15, 0); // doesn't seem to be available in the iOS simulator until iOS 17+ - break; case "SensorKit": // SensorKit doesn't exist on iPads if (TestRuntime.IsDevice && TestRuntime.IsiPad) return true; @@ -210,9 +206,6 @@ protected virtual bool Skip (Type type, string selectorName) break; #if !MONOMAC case "MTLCaptureManager": - case "NEHotspotEapSettings": // Wireless Accessory Configuration is not supported in the simulator. - case "NEHotspotConfigurationManager": - case "NEHotspotHS20Settings": if (TestRuntime.IsSimulatorOrDesktop) return true; break; @@ -1303,8 +1296,6 @@ protected virtual bool Skip (Type type, string selectorName) } break; } - - // old binding mistake return (selectorName == "initWithCoder:"); } @@ -1407,7 +1398,7 @@ public void Protocols () } } } - Assert.AreEqual (0, Errors, "{0} errors found in {1} protocol selectors validated", Errors, n); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} errors found in {n} protocol selectors validated"); } void ProcessProtocolMember (Type t, MethodBase m, ref int n) @@ -1474,7 +1465,7 @@ public void InstanceMethods () Process (class_ptr, t, m, ref n); } } - Assert.AreEqual (0, Errors, "{0} errors found in {1} instance selector validated{2}", Errors, n, Errors == 0 ? string.Empty : ":\n" + ErrorData.ToString () + "\n"); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} errors found in {n} instance selector validated:\n{ErrorData}\n"); } void Process (IntPtr class_ptr, Type t, MethodBase m, ref int n) @@ -1582,7 +1573,7 @@ public void StaticMethods () } } } - Assert.AreEqual (0, Errors, "{0} errors found in {1} static selector validated{2}", Errors, n, Errors == 0 ? string.Empty : ":\n" + ErrorData.ToString () + "\n"); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} errors found in {n} static selector validated:\n{ErrorData}\n"); } } } diff --git a/tests/introspection/ApiSignatureTest.cs b/tests/introspection/ApiSignatureTest.cs index 4d88583eb5cf..d9c1fa6bd2b5 100644 --- a/tests/introspection/ApiSignatureTest.cs +++ b/tests/introspection/ApiSignatureTest.cs @@ -57,7 +57,7 @@ public abstract class ApiSignatureTest : ApiBaseTest { if (encoded [end] != '@' || encoded [end + 1] != '0' || encoded [end + 2] != ':') { if (!ContinueOnFailure) - Assert.Fail ("Unexpected format, missing '@0:', inside '{0}'", encoded); + Assert.Fail ($"Unexpected format, missing '@0:', inside '{encoded}'"); return null; } diff --git a/tests/introspection/ApiSimulatorAvailabilityTest.cs b/tests/introspection/ApiSimulatorAvailabilityTest.cs new file mode 100644 index 000000000000..9f3fd98c4b1f --- /dev/null +++ b/tests/introspection/ApiSimulatorAvailabilityTest.cs @@ -0,0 +1,201 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +// +// Verify that [UnsupportedSimulator] / [SupportedSimulator] attributes +// are consistent with actual symbol availability in the simulator. +// + +using System.IO; +using System.Linq; +using System.Reflection; +using Xamarin.Tests; + +#nullable enable + +namespace Introspection { + [Preserve (AllMembers = true)] + public abstract class ApiSimulatorAvailabilityTest : ApiBaseTest { + + protected ApiSimulatorAvailabilityTest () + { + ContinueOnFailure = true; + LogProgress = false; + } + + protected virtual bool Skip (Type type) + { + return false; + } + + protected virtual bool SkipPInvoke (MethodInfo mi) + { + return false; + } + + protected virtual bool SkipField (PropertyInfo pi) + { + return false; + } + + protected virtual bool SkipLibrary (string? libraryName) + { + return false; + } + + /// + /// Verifies that P/Invokes marked as unsupported in the simulator are indeed unavailable. + /// Also detects P/Invokes not marked as unsupported that are missing from the simulator. + /// + [Test] + public void PInvokeSimulatorAvailability () + { + if (!TestRuntime.IsSimulator) { + Assert.Ignore ("This test only runs in the simulator."); + return; + } + + var failed_api = new List (); + Errors = 0; + int n = 0; + + foreach (var type in Assembly.GetTypes ()) { + if (Skip (type)) + continue; + + if (!type.IsAvailableOnHostPlatform ()) + continue; + + foreach (var mi in type.GetMethods (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)) { + var dllimport = mi.GetCustomAttribute (); + if (dllimport is null) + continue; + + if (!mi.IsAvailableOnHostPlatform ()) + continue; + + if (MemberHasObsolete (mi)) + continue; + + if (SkipPInvoke (mi)) + continue; + + var libname = dllimport.Value; + switch (libname) { + case "__Internal": + case "System.Native": + case "System.Security.Cryptography.Native.Apple": + case "System.Net.Security.Native": + continue; + } + + if (SkipLibrary (libname)) + continue; + + string name = dllimport.EntryPoint ?? mi.Name; + // skip known missing symbols + switch (name) { + case "objc_msgSend_stret": + case "objc_msgSendSuper_stret": + continue; + } + + string path = FindLibrary (libname!, requiresFullPath: true); + IntPtr lib = Dlfcn.dlopen (path, 0); + bool symbolExists = lib != IntPtr.Zero && Dlfcn.GetIndirect (lib, name) != IntPtr.Zero; + if (lib != IntPtr.Zero) + Dlfcn.dlclose (lib); + + bool markedUnavailable = !mi.IsAvailableInSimulator () || !type.IsAvailableInSimulator (); + + if (markedUnavailable && symbolExists) { + var msg = $"P/Invoke '{type.FullName}.{mi.Name}' (symbol '{name}') is marked as unavailable in the simulator, but the symbol exists in '{path}'."; + ReportError (msg); + failed_api.Add ($"{type.FullName}.{mi.Name}"); + } else if (!markedUnavailable && !symbolExists && lib != IntPtr.Zero) { + // The library exists but the symbol doesn't - might need [UnsupportedSimulator] + var msg = $"P/Invoke '{type.FullName}.{mi.Name}' (symbol '{name}') is not marked as unavailable in the simulator, but the symbol was not found in '{path}'. Consider adding [UnsupportedSimulator]."; + ReportError (msg); + failed_api.Add ($"{type.FullName}.{mi.Name}"); + } + n++; + } + } + + AssertIfErrors ("{0} errors found in {1} P/Invoke simulator availability checks: {2}", + Errors, n, string.Join (", ", failed_api)); + } + + /// + /// Verifies that [Field] properties marked as unsupported in the simulator are indeed unavailable. + /// Also detects [Field] properties not marked as unsupported that are missing from the simulator. + /// + [Test] + public void FieldSimulatorAvailability () + { + if (!TestRuntime.IsSimulator) { + Assert.Ignore ("This test only runs in the simulator."); + return; + } + + var failed_fields = new List (); + Errors = 0; + int n = 0; + + foreach (var type in Assembly.GetTypes ()) { + if (Skip (type)) + continue; + + if (!type.IsAvailableOnHostPlatform ()) + continue; + + foreach (var p in type.GetProperties (BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) { + if (p.CanWrite || !p.CanRead) + continue; + + var fieldAttr = p.GetCustomAttribute (); + if (fieldAttr is null) + continue; + + if (!p.IsAvailableOnHostPlatform ()) + continue; + + if (MemberHasObsolete (p)) + continue; + + if (SkipField (p)) + continue; + + string symbolName = fieldAttr.SymbolName; + string? libName = fieldAttr.LibraryName; + + if (SkipLibrary (libName)) + continue; + + string path = FindLibrary (libName!); + IntPtr lib = Dlfcn.dlopen (path, 0); + bool symbolExists = lib != IntPtr.Zero && Dlfcn.GetIndirect (lib, symbolName) != IntPtr.Zero; + if (lib != IntPtr.Zero) + Dlfcn.dlclose (lib); + + bool markedUnavailable = !p.IsAvailableInSimulator () || !type.IsAvailableInSimulator (); + + if (markedUnavailable && symbolExists) { + var msg = $"Field '{type.FullName}.{p.Name}' (symbol '{symbolName}') is marked as unavailable in the simulator, but the symbol exists in '{path}'."; + ReportError (msg); + failed_fields.Add ($"{type.FullName}.{p.Name}"); + } else if (!markedUnavailable && !symbolExists && lib != IntPtr.Zero) { + // The library exists but the symbol doesn't - might need [UnsupportedSimulator] + var msg = $"Field '{type.FullName}.{p.Name}' (symbol '{symbolName}') is not marked as unavailable in the simulator, but the symbol was not found in '{path}'. Consider adding [UnsupportedSimulator]."; + ReportError (msg); + failed_fields.Add ($"{type.FullName}.{p.Name}"); + } + n++; + } + } + + AssertIfErrors ("{0} errors found in {1} field simulator availability checks: {2}", + Errors, n, string.Join (", ", failed_fields)); + } + } +} diff --git a/tests/introspection/ApiStructTest.cs b/tests/introspection/ApiStructTest.cs index cc71f137b548..5106fe6ebd68 100644 --- a/tests/introspection/ApiStructTest.cs +++ b/tests/introspection/ApiStructTest.cs @@ -44,9 +44,7 @@ public void Structs () } } - Assert.AreEqual (0, totalErrors, - "{0} errors found in {1} structures validated", - totalErrors, totalStructs); + Assert.That (totalErrors, Is.EqualTo (0), $"{totalErrors} errors found in {totalStructs} structures validated"); } protected virtual bool CheckStruct (Type type) diff --git a/tests/introspection/ApiTypoTest.cs b/tests/introspection/ApiTypoTest.cs index 109708a47a15..8bbd6384e879 100644 --- a/tests/introspection/ApiTypoTest.cs +++ b/tests/introspection/ApiTypoTest.cs @@ -27,8 +27,10 @@ using System.Text.RegularExpressions; #if MONOMAC using AppKit; +using SpellChecker = AppKit.NSSpellChecker; #else using UIKit; +using SpellChecker = UIKit.UITextChecker; #endif using Xamarin.Tests; using Xamarin.Utils; @@ -36,8 +38,11 @@ #nullable enable namespace Introspection { - public abstract class ApiTypoTest : ApiBaseTest { - protected ApiTypoTest () + [TestFixture] + public class ApiTypoTest : ApiBaseTest { + const ApplePlatform All = ApplePlatform.MacOSX | ApplePlatform.iOS | ApplePlatform.TVOS | ApplePlatform.MacCatalyst; + + public ApiTypoTest () { ContinueOnFailure = true; } @@ -64,675 +69,756 @@ public virtual bool Skip (MemberInfo methodName, string typo) "MacAttribute", }; - HashSet allowed = new HashSet () { - "Aac", - "Achivements", - "Acos", - "Acosh", - "Acn", - "Actionname", - "Activitiy", - "Addin", - "Addl", - "Addr", - "Adjustmentfor", - "Aes", // Advanced Encryption Standard - "Aifc", - "Aiff", - "Agc", - "Aio", - "Alg", // short for Algorithm - "Alpn", // Application-Layer Protocol Negotiation RFC7301 - "Amete", - "Amr", - "Anglet", - "Apng", // Animated Portable Network Graphics - "Aps", - "Arraycollation", - "Argb", - "Asin", - "Asinh", - "Atan", - "Atanh", - "Atmos", // Dolby Atmos - "Ats", // App Transport Security - "Attrib", - "Attributevalue", - "Attrs", // Attributes (used by Apple for keys) - "Audiofile", - "Automapping", - "Automatch", - "Automounted", - "Autoredirect", - "Autospace", - "Autostarts", - "Avci", // file type - "Avb", // acronym: Audio Video Bridging - "Aliasable", - "Arcball", - "Atm", - "Avg", - "Backface", - "Bancaire", // french - "Bancaires", // french - "Bary", - "Batc", - "Bgra", // acrnym for Blue, Green, Red, Alpha - "Bim", - "Biquad", - "Bitangent", - "Blinn", - "Blit", - "Bokeh", - "Bggr", // acronym for Blue, Green, Green, Red - "Bsln", - "Bssid", - "Btle", // Bluetooth Low Energy - "Bzip", - "Cabac", - "Caf", // acronym: Core Audio Format - "Cancellable", - "Cartes", // french - "Cavlc", - "Cda", // acronym: Clinical Document Architecture - "Cdrom", - "Celu", // Continuously Differentiable Exponential Linear Unit (ML) - "Cfa", // acronym: Color Filter Array - "Celp", // MPEG4ObjectID - "Characterteristic", - "Chapv", - "Cholesky", - "Chacha", - "Chromaticities", - "Ciexyz", - "Ciff", - "Cinepak", - "Clearcoat", - "Cnn", // Convolutional Neural Network - "Cns", - "Colos", - "Commerical", - "Composable", - "Conflictserror", - "Connnect", - "Counterclock", - "Copyback", - "Craete", - "Crosstraining", - "Cubemap", - "Cmaf", // Common Media Application Format (mpeg4) - "Cmy", // acronym: Cyan, magenta, yellow - "Cmyk", // acronym: Cyan, magenta, yellow and key - "Daap", - "Dav", - "Dcip", // acronym: Digital Cinema Implementation Partners - "Deca", - "Decomposables", - "Deinterlace", - "Depthwise", - "Descendents", - "Descrete", - "Dhe", // Diffie–Hellman key exchange - "Diffable", // that you can diff it.. made up word from apple - "Differental", - "Diffie", - "Directionfor", - "Dist", - "dlclose", - "dlerror", - "Dlfcn", - "dlopen", - "Dls", - "Dlsym", - "dlsym", - "Dng", - "Dns", - "Dont", - "Dop", - "Dopesheet", - "Downsample", - "Downmix", // Sound terminology that means making a stereo mix from a 5.1 surround mix. - "Dpa", - "Dpad", // Directional pad (D-pad) - "Dpads", // plural of above - "Droste", - "Dtls", - "Dtmf", // DTMF - "dy", - "Eap", - "Ebu", - "Ecc", // Elliptic Curve Cryptography - "Ecdh", // Elliptic Curve Diffie–Hellman - "Ecdhe", // Elliptic Curve Diffie-Hellman Ephemeral - "Ecdsa", // Elliptic Curve Digital Signature Algorithm - "Ecies", // Elliptic Curve Integrated Encryption Scheme - "Ecn", // Explicit Congestion Notification - "Ect", // ECN Capable Transport - "Editability", - "Edr", - "Eof", // acronym End-Of-File - "Elu", - "Emagic", - "Emaili", - "Embd", - "Emsg", // 4cc - "Enc", - "Eppc", - "Epub", - "Eftpos", // Electronic funds transfer at point of sale - "Eotf", // DisplayP3_PQ_Eotf - "Exabits", - "Exbibits", - "Exbibytes", - "Exhange", - "Exp", - "Expr", - "Exr", - "Felica", // Japanese contactless RFID smart card system - "Femtowatts", - "Fhir", - "Flipside", - "Formati", - "Fov", - "Framebuffer", - "Framesetter", - "Froms", // NSMetadataItemWhereFromsKey - "Freq", - "Ftps", - "Func", - "Gadu", - "Gbrg", // acronym for Green-Blue-Reg-Green - "Gelu", // Gaussian Error Linear Unit (ML) - "Geocoder", - "Gigapascals", - "Gibibits", - "Gibibytes", - "Girocard", - "Glorot", // NN - "Gop", // acronym for Group Of Pictures - "Gpp", - "Gps", - "Gpu", // acronym for Graphics Processing Unit - "Grbg", // acronym for Green-Red-Blue-Green - "Gru", - "Greeking", - "Gtin", - "Gui", - "Hardlink", - "Heics", // High Efficiency Image File Format (Sequence) - "Hdmi", - "Hdr", - "Hectopascals", - "Heic", // file type - "Heif", // file type - "Hevc", // CMVideoCodecType / High Efficiency Video Coding - "Heif", // High Efficiency Image File Format - "Hfp", - "Hipass", - "Hlg", // Hybrid Log-Gamma - "Hls", - "Hoa", - "Hrtf", // acronym used in AUSpatializationAlgorithm - "Hvxc", // MPEG4ObjectID - "Icns", - "Ico", - "Ies", - "Icq", - "Ident", - "Identd", - "Imageblock", - "Imagefor", - "Imap", - "Imaps", - "Img", - "Impl", // BindingImplAttribute - "Inv", - "Indoorrun", - "Indoorcycle", - "Inklist", - "Indeterm", - "Indoorwalk", - "Inode", - "Inser", - "Instamatic", - "Interac", - "Interframe", - "Interitem", - "Intermenstrual", - "Intersector", - "Intoi", - "Invitable", - "Ios", - "Iou", - "Ipa", - "Ipp", - "Iptc", - "Ircs", - "Iso", - "Itf", - "Itu", - "Itur", // Itur_2020_Hlg - "Jcb", // Japanese credit card company - "Jfif", - "Jis", - "Json", - "Keyerror", - "Keyi", - "Keypoint", - "Keypoints", - "Keyspace", - "ks", - "Kibibits", - "Kibibytes", - "Kiloampere", - "Kiloamperes", - "Kiloohms", - "Kilopascals", - "Kullback", // Kullback-Leibler Divergence - "Langauges", - "Lacunarity", - "Latm", // Low Overhead Audio Transport Multiplex - "Ldaps", - "Lerp", - "Linecap", - "Lingustic", - "libcompression", - "libdispatch", - "Loas", // Low Overhead Audio Stream - "Lod", - "Lopass", - "Lowlevel", - "Lstm", - "Lun", - "Luma", - "Lzfse", // acronym - "Lzma", // acronym - "Mada", // payment system - "Mapbuffer", - "Matchingcoalesce", - "Mcp", // metacarpophalangeal (hand) - "Mebibits", - "Mebibytes", - "Megaampere", - "Megaamperes", - "Megaliters", - "Megameters", - "Megaohms", - "Megapascals", - "Metacharacters", - "Metalness", - "Metadatas", - "Microampere", - "Microamperes", - "Microohms", - "Microwatts", - "Millimoles", - "Milliohms", - "Mimap", - "Minification", - "Mncs", - "Mgmt", - "Mobike", // acronym - "Morpher", - "mtouch", - "Mpe", // acronym - "Mps", - "Msaa", // multisample anti-aliasing - "Mtu", // acronym - "Mtc", // acronym - "Mtgp", - "Mul", - "Mult", - "Multihead", - "Multipath", - "Multipeer", - "Muxed", - "Nai", - "Nanograms", - "Nanowatts", - "Nestrov", - "Nesterov", - "nfloat", - "Nfnt", - "nint", - "Nntps", - "Ntlm", - "Nsl", // InternetLocationNslNeighborhoodIcon - "Ntsc", - "nuint", - "Ndef", - "Noi", // From NoiOSAttribute - "Nop", - "Numbernumber", - "Nyquist", - "Oaep", // Optimal asymmetric encryption padding - "Objectfor", - "Objectness", - "Occlussion", - "Ocurrences", - "Ocsp", // Online Certificate Status Protocol - "Octree", - "Oid", - "Oneup", // TVElementKeyOneupTemplate - "Organisation", // kCGImagePropertyIPTCExtRegistryOrganisationID in Xcode9.3-b1 - "Orthographyrange", - "Orth", - "Osa", // Open Scripting Architecture - "Otsu", // threshold for image binarization - "ove", - "Paeth", // PNG filter - "Palettize", - "Parms", // short for Parameters - "Peap", - "Pebibits", - "Pebibytes", - "Petabits", - "Perlin", - "Persistable", - "Pausable", - "Pcl", - "Pcm", - "Pdu", - "Persistance", - "Pesented", - "Pfs", // acronym - "Philox", - "Picometers", - "Picowatts", - "Pkcs", - "Placemark", - "Playthrough", - "Pnc", // MIDI - "Pnorm", - "Pointillize", - "Polyline", - "Polylines", - "Popularimeter", - "Preds", // short for Predicates - "Prerolls", - "Preseti", - "Prev", - "Privs", // SharingPrivsNotApplicableIcon - "Propogate", - "Psec", - "Psm", // Protocol/Service Multiplexer - "Psk", - "Ptp", - "Pvrtc", // MTLBlitOption - PowerVR Texture Compression - "Qos", - "Quaterniond", - "Quadding", - "Qura", - "Quic", - "Reacquirer", - "Reinvitation", - "Reinvite", - "Rel", - "Relocalization", - "Relu", // Rectified Linear Unit (ML) - "Relun", // ReLUn - degree n Hermite coefficients - "Reprandial", - "Replayable", - "Requestwith", - "Ridesharing", - "Rgb", - "Rgba", - "Rggb", // acronym for Red, Green, Green, Blue - "Rnn", - "Roi", - "Romm", // acronym: Reference Output Medium Metric - "Rpa", - "Rpn", // acronym - "Rsa", // Rivest, Shamir and Adleman - "Rsqrt", // reciprocal square root - "Rssi", - "Rtp", - "Rtl", - "Rtsp", - "Saml", // acronym - "Sdof", - "Scn", - "Sdk", - "Sdtv", // acronym: Standard Definition Tele Vision - "Sdnn", - "Seekable", - "Selu", // Scaled Exponential Linear unit (ML) - "Sgd", // Stochastic Gradient Descent (ML) - "Shadable", - "Sharegroup", - "Sha", // Secure Hash Algorithm - "Siemen", - "simd", - "Sinh", - "Sint", // as in "Signed Integer" - "Simd", - "Slerp", - "Slomo", - "Smpte", - "Snapshotter", - "Snorm", - "Sobel", - "Softmax", // get_SoftmaxNormalization - "Spacei", - "Sqrt", - "Srgb", - "Ssid", - "Ssids", - "Standarize", - "Stateful", - "Stateright", - "Subbeat", - "Subcaption", - "Subcardioid", - "Subentities", - "Subheadline", - "Sublocality", - "Sublocation", - "Submesh", - "Submeshes", - "Subpixel", - "Subresource", - "Subresources", - "Subsec", - "Suica", // Japanese contactless smart card type - "Superentity", - "Supertype", - "Supertypes", - "Svg", // Scalable Vector Graphics - "Sym", - "Synchronizable", - "Symbologies", - "Tanh", - "Tebibits", - "Tebibytes", - "Tensorflow", - "Tessellator", - "Texcoord", - "Texel", - "th", - "Threadgroup", - "Threadgroups", - "Thumbnailing", - "Thumbstick", - "Thumbsticks", - "Timecodes", - "Timelapse", - "Timelapses", - "Tls", - "Ttls", - "Tlv", - "Toc", - "Toci", - "Toi", - "Transceive", - "Trc", - "Truncantion", - "Tweening", - "Twips", - "tx", - "ty", - "Udi", - "Udp", - "Unconfigured", - "Undecodable", - "Unemphasized", - "Underrun", - "Unflagged", - "Unfocusing", - "Uid", - "Unmap", - "Unorm", - "Unpremultiplied", - "Unpremultiplying", - "Unprepare", - "Unproject", - "Unpublish", - "Uterance", - "Unentitled", - "Untrash", - "Utf", - "Upce", - "Uri", - "Usac", // Unified Speech and Audio Coding - "Usd", // Universal Scene Description - "Usdz", // USD zip - "Uti", - "Varispeed", - "Vergence", - "Voronoi", - "Vnode", - "Vpn", - "Warichu", - "Wep", - "Wpa", - "Warpable", - "Whitespaces", - "Wifes", - "Writeability", - "Xnor", - "Xpc", - "xy", - "Xyz", - "Xzy", - "Yobibits", - "Yobibytes", - "Yottabits", - "Yxz", - "Yzx", - "Zxy", - "Zyx", - "Yuv", - "Yuvk", - "yuvs", - "yx", - "yy", - "Yyy", - "Zebibits", - "Zebibytes", - "Zettabits", - "Zlib", -#if MONOMAC - "Abbr", - "Accum", - "Ack", // TcpSetDisableAckStretching - "Addin", - "Addons", - "Appactive", - "Approx", - "Arae", - "Attr", - "Attributesfor", - "Autoresizin", - "Avc", - "Callpout", - "Ccitt", - "Commited", - "Constrainted", - "Ctm", - "Cymk", - "Cymka", - "Cmyka", - "Compat", - "Credendtials", - "Descriptorat", - "Descriptorfor", - "Dimensionsfor", - "Dissapearing", - "Distinguised", // ITLibPlaylistPropertyDistinguisedKind - "Dirs", - "Drm", // MediaItemProperty.IsDrmProtected - "Editability", - "Eisu", - "Entryat", - "Equiv", - "Fourty", - "Grammarl", - "Greeking", - "Hsb", - "Hsba", - "Ibss", - "Iconfor", - "Incrementor", - "Indexeffective", - "Indexestable", - "Itemto", - "Lowsrc", - "Lpcm", - "Lzw", - "Mihret", - "Mps", - "Nonenumerated", - "Nsevent", - "Numberof", - "Orginal", - "Parms", - "Pbm", - "Pde", - "Performwith", - "Phy", - "Pmgt", - "Preceeding", - "Preds", - "Previewable", - "Qtvr", - "Rangewith", - "Rangeswith", - "Reassociation", - "Rectfrom", - "Registeration", - "Segmentnew", - "Semitransient", - "Sixtyfour", - "Sourcei", - "Steppable", - "Stringto", - "Succesfully", - "Supression", - "Targetand", - "Tkip", - "Tsn", - "Tunesi", - "Twentyfour", - "Uneditable", - "Unfocus", - "Unpublish", - "Usec", - "Usedby", - "Viewwrite", - "Wep", - "Wlan", - "Wme", - "Writeln", - "Xattr", -#endif + Dictionary allowed = new Dictionary () { + { "Aac", All }, + { "Abgr", All }, + { "Accurracy", All }, + { "Achivements", All }, + { "Acos", All }, + { "Acosh", All }, + { "Activatable", All }, + { "Addin", All }, + { "Addl", All }, + { "Addons", ApplePlatform.MacOSX }, + { "Addr", All }, + { "Adessive", All }, + { "Adjustmentfor", All & ~ApplePlatform.MacOSX }, + { "Afi", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Agc", All }, + { "Ahap", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Aifc", All }, + { "Aiff", All }, + { "Aime", ApplePlatform.MacOSX }, + { "Aio", ApplePlatform.MacOSX }, + { "Alg", All }, // short for Algorithm + { "Aliasable", All }, + { "Allative", All }, + { "Amete", All }, + { "Amr", All }, + { "Ancs", All & ~ApplePlatform.MacOSX }, + { "Ane", All }, + { "Anglet", All }, + { "Apac", All }, + { "Apdu", All }, + { "Apl", All & ~ApplePlatform.TVOS }, + { "Apng", All }, // Animated Portable Network Graphics + { "Apns", All & ~ApplePlatform.TVOS }, + { "Appactive", ApplePlatform.MacOSX }, + { "Applei", All }, + { "Aps", ApplePlatform.MacOSX }, + { "Apv", ApplePlatform.MacOSX }, + { "Arae", ApplePlatform.MacOSX }, + { "Arcball", All }, + { "Argb", All }, + { "Arraycollation", All & ~ApplePlatform.MacOSX }, + { "Asin", All }, + { "Asinh", All }, + { "Astc", All }, + { "Aswas", ApplePlatform.MacOSX }, + { "Atan", All }, + { "Atanh", All }, + { "Atm", All }, + { "Atmos", All }, // Dolby Atmos + { "Atr", All }, + { "Ats", All }, // App Transport Security + { "Atsc", All }, + { "Attr", ApplePlatform.MacOSX }, + { "Attrib", All }, + { "Attributesfor", ApplePlatform.MacOSX }, + { "Attributevalue", All }, + { "Attrs", All }, // Attributes (used by Apple for keys) + { "Audiofile", All }, + { "Audiograph", ApplePlatform.MacOSX }, + { "Authenticatable", ApplePlatform.MacOSX }, + { "Automapping", All }, + { "Automatch", All }, + { "Automounted", All }, + { "Autoredirect", ApplePlatform.MacCatalyst | ApplePlatform.TVOS }, + { "Autospace", ApplePlatform.MacOSX }, + { "Autostarts", ApplePlatform.MacOSX }, + { "Avb", All }, // acronym: Audio Video Bridging + { "Avci", All }, // file type + { "Avg", All }, + { "Axept", All & ~ApplePlatform.TVOS }, + { "Bancomat", All & ~ApplePlatform.TVOS }, + { "Bary", All }, + { "Ber", All }, + { "Bggr", All }, // acronym for Blue, Green, Green, Red + { "Bgra", All }, // acrnym for Blue, Green, Red, Alpha + { "Bgrx", All }, + { "Bim", All }, + { "Bitangent", All }, + { "Blinn", All }, + { "Blit", All }, + { "Blockmap", ApplePlatform.MacOSX }, + { "Blockquote", ApplePlatform.MacOSX }, + { "Brotli", All }, + { "Bsd", ApplePlatform.MacOSX }, + { "Bsln", All }, + { "Bssid", All & ~ApplePlatform.TVOS }, + { "Btle", ApplePlatform.MacOSX }, // Bluetooth Low Energy + { "Cabac", All }, + { "Caf", All }, // acronym: Core Audio Format + { "Callables", All }, + { "Callpout", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Cartes", All & ~ApplePlatform.TVOS }, // french + { "Catmull", All }, + { "Cavlc", All }, + { "Ccitt", ApplePlatform.MacOSX }, + { "Cct", All }, + { "Ccw", All }, + { "Cda", All & ~ApplePlatform.TVOS }, // acronym: Clinical Document Architecture + { "Cdma", All }, + { "Cdrom", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Cea", All }, + { "Celp", All }, // MPEG4ObjectID + { "Celu", All }, // Continuously Differentiable Exponential Linear Unit (ML) + { "Cfa", All }, // acronym: Color Filter Array + { "Chacha", All }, + { "Chapv", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Characterteristic", All }, + { "Cholesky", All }, + { "Chromaticities", All }, + { "Chw", All }, + { "Ciexyz", ApplePlatform.MacOSX }, + { "Ciff", All }, + { "Cinemagraph", ApplePlatform.TVOS }, + { "Cinepak", All }, + { "Cla", All }, + { "Clearcoat", All }, + { "Clockstamp", All }, + { "Cmaf", All }, // Common Media Application Format (mpeg4) + { "Cmy", ApplePlatform.MacOSX }, // acronym: Cyan, magenta, yellow + { "Cmyk", All }, // acronym: Cyan, magenta, yellow and key + { "Cmyka", ApplePlatform.MacOSX }, + { "Cnn", All }, // Convolutional Neural Network + { "Cns", ApplePlatform.MacOSX }, + { "Codabar", All }, + { "Commited", ApplePlatform.MacOSX }, + { "Conecs", All & ~ApplePlatform.TVOS }, + { "Constrainted", ApplePlatform.MacOSX }, + { "Conv", All }, + { "Copyback", All }, + { "Cose", All & ~ApplePlatform.TVOS }, + { "Crosstraining", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Csr", All }, + { "Ctm", ApplePlatform.MacOSX }, + { "Ctor", All }, + { "Cubemap", All }, + { "Cymk", ApplePlatform.MacOSX }, + { "Cymka", ApplePlatform.MacOSX }, + { "Daap", All }, + { "Dangi", All }, + { "Dankort", All & ~ApplePlatform.TVOS }, + { "Dav", All & ~ApplePlatform.TVOS }, + { "Dcip", All }, // acronym: Digital Cinema Implementation Partners + { "Deca", All & ~ApplePlatform.TVOS }, + { "Decomposables", All }, + { "Deinterlace", All }, + { "Denimonator", All }, + { "Denoise", All }, + { "Denoised", All }, + { "Depthwise", All }, + { "Dequantize", All }, + { "Descendents", All }, + { "Descriptorat", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Descriptorfor", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Dfsi", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Dhe", All }, // Diffie–Hellman key exchange + { "Dhs", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Dhwio", All }, + { "Dicom", All }, + { "Diconnection", All }, + { "Diffable", All }, // that you can diff it.. made up word from apple + { "Differental", All }, + { "Diffie", All }, + { "Dirbursement", All & ~ApplePlatform.TVOS }, + { "Directionfor", All & ~ApplePlatform.MacOSX }, + { "Dirs", ApplePlatform.MacOSX }, + { "Dismissable", ApplePlatform.MacOSX }, + { "Dissapearing", ApplePlatform.MacOSX }, + { "Dist", All }, + { "Distinguised", ApplePlatform.MacOSX }, // ITLibPlaylistPropertyDistinguisedKind + { "dlclose", All }, + { "dlerror", All }, + { "Dlfcn", All }, + { "Dls", ApplePlatform.MacOSX }, + { "Dng", All }, + { "Dnssec", All }, + { "Dont", All }, + { "Dop", ApplePlatform.iOS }, + { "Dopesheet", All }, + { "Downmix", All }, // Sound terminology that means making a stereo mix from a 5.1 surround mix. + { "Dpa", All }, + { "Dpad", All }, // Directional pad (D-pad) + { "Dpads", All }, // plural of above + { "Drm", ApplePlatform.MacOSX }, // MediaItemProperty.IsDrmProtected + { "Droste", All }, + { "Dsf", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Dsfi", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Dstu", All & ~ApplePlatform.TVOS }, + { "Dtls", All }, + { "Dtmf", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, // DTMF + { "Dtss", ApplePlatform.MacOSX }, + { "dy", All }, + { "Eap", All }, + { "Ebu", All }, + { "Ecc", All }, // Elliptic Curve Cryptography + { "Ecdh", All }, // Elliptic Curve Diffie–Hellman + { "Ecdhe", All }, // Elliptic Curve Diffie-Hellman Ephemeral + { "Ecdsa", All }, // Elliptic Curve Digital Signature Algorithm + { "Ecg", All & ~ApplePlatform.TVOS }, + { "Ecies", All }, // Elliptic Curve Integrated Encryption Scheme + { "Ecn", All }, // Explicit Congestion Notification + { "Ect", All }, // ECN Capable Transport + { "Editability", All & ~ApplePlatform.MacOSX }, + { "Edr", All }, + { "Eftpos", All & ~ApplePlatform.TVOS }, // Electronic funds transfer at point of sale + { "Eisu", ApplePlatform.MacOSX }, + { "Elative", All }, + { "Elu", All }, + { "Emagic", All }, + { "Emaili", All & ~ApplePlatform.TVOS }, + { "Embd", All }, + { "Emebedding", All }, + { "Emsg", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, // 4cc + { "Enc", All }, + { "Endc", All }, + { "Eof", All }, // acronym End-Of-File + { "Eppc", All }, + { "Epub", All }, + { "Erf", All }, + { "Essive", All }, + { "Evdo", All }, + { "Evictable", ApplePlatform.MacOSX | ApplePlatform.iOS }, + { "Exabits", All }, + { "Exbibits", All }, + { "Exhange", All }, + { "Expr", All }, + { "Exr", All }, + { "Extrinsics", All }, + { "Feli", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Felica", All & ~ApplePlatform.TVOS }, // Japanese contactless RFID smart card system + { "Femtowatts", All }, + { "Fft", All }, + { "Fhir", All & ~ApplePlatform.TVOS }, + { "Fieldset", All & ~ApplePlatform.MacCatalyst }, + { "Flipside", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Formati", All }, + { "Fourty", ApplePlatform.MacOSX }, + { "Fov", All }, + { "Fqdns", All }, + { "Framebuffer", All }, + { "Framesetter", All }, + { "Freq", All }, + { "Froms", ApplePlatform.MacOSX }, // NSMetadataItemWhereFromsKey + { "Ftps", All }, + { "Gadu", All & ~ApplePlatform.TVOS }, + { "Gainmap", All }, + { "Gbrg", All }, // acronym for Green-Blue-Reg-Green + { "Gbtac", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Gbtdc", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Gcm", All }, + { "Gelu", All }, // Gaussian Error Linear Unit (ML) + { "Gibibits", All }, + { "Gid", ApplePlatform.MacOSX }, + { "Gigapascals", All }, + { "Girocard", All & ~ApplePlatform.TVOS }, + { "Gles", ApplePlatform.iOS | ApplePlatform.TVOS }, + { "Glorot", All }, // NN + { "Gop", All }, // acronym for Group Of Pictures + { "Gpp", All }, + { "Gps", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Grammarl", ApplePlatform.MacOSX }, + { "Grbg", All }, // acronym for Green-Red-Blue-Green + { "Greeking", ApplePlatform.MacOSX }, + { "Groupless", All & ~ApplePlatform.TVOS }, + { "Gru", All }, + { "Gtin", All }, + { "Gui", All }, + { "Hardlink", ApplePlatform.MacOSX }, + { "Hdmi", All & ~ApplePlatform.MacOSX }, + { "Hdr", All }, + { "Heic", All }, // file type + { "Heics", All }, // High Efficiency Image File Format (Sequence) + { "Heif", All }, // High Efficiency Image File Format + { "Hermitean", All }, + { "Hevc", All }, // CMVideoCodecType / High Efficiency Video Coding + { "Hfp", All & ~ApplePlatform.MacOSX }, + { "Hhr", All }, + { "Himyan", All & ~ApplePlatform.TVOS }, + { "Hindlegs", All }, + { "Hipass", All }, + { "Histogrammed", All & ~ApplePlatform.TVOS }, + { "Hlg", All }, // Hybrid Log-Gamma + { "Hls", All }, + { "Hoa", All }, + { "Hpke", ApplePlatform.MacOSX }, + { "Hrtf", All }, // acronym used in AUSpatializationAlgorithm + { "Hsb", ApplePlatform.MacOSX }, + { "Hsba", ApplePlatform.MacOSX }, + { "Hvxc", All }, // MPEG4ObjectID + { "Hwc", All }, + { "Hwio", All }, + { "Iap", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Ibss", ApplePlatform.MacOSX }, + { "Icns", All }, + { "Ico", All }, + { "Iconfor", ApplePlatform.MacOSX }, + { "Icq", All & ~ApplePlatform.TVOS }, + { "Identd", All }, + { "Iec", All }, + { "Ies", All }, + { "Imageblock", All }, + { "Imagefor", All & ~ApplePlatform.MacOSX }, + { "Imap", All }, + { "Imaps", All }, + { "Imei", All & ~ApplePlatform.MacOSX }, + { "Img", All }, + { "Impl", All }, // BindingImplAttribute + { "Incrementor", ApplePlatform.MacOSX }, + { "Indoorcycle", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Indoorrun", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Indoorwalk", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Inessive", All }, + { "Inklist", All }, + { "Inode", ApplePlatform.MacOSX }, + { "Inot", All }, + { "Inser", All }, + { "Instamatic", ApplePlatform.MacOSX }, + { "Interac", All & ~ApplePlatform.TVOS }, + { "Interactable", ApplePlatform.MacOSX }, + { "Interframe", All }, + { "Interitem", All }, + { "Intermenstrual", All & ~ApplePlatform.TVOS }, + { "Intoi", All & ~ApplePlatform.MacOSX }, + { "Intravaginal", All & ~ApplePlatform.TVOS }, + { "Inv", All }, + { "Invitable", All }, + { "Iou", All }, + { "Ipa", All }, + { "Ipp", All }, + { "Iptc", All }, + { "Ircs", All }, + { "Isrc", All }, + { "Itemto", ApplePlatform.MacOSX }, + { "Itf", All }, + { "Itt", All & ~ApplePlatform.TVOS }, + { "Itu", All }, + { "Itur", All }, // Itur_2020_Hlg + { "Jaywan", All & ~ApplePlatform.TVOS }, + { "Jcb", All & ~ApplePlatform.TVOS }, // Japanese credit card company + { "Jfif", All }, + { "Jis", ApplePlatform.MacOSX }, + { "Jrts", All & ~ApplePlatform.TVOS }, + { "Jwks", ApplePlatform.MacOSX }, + { "Jws", All & ~ApplePlatform.TVOS }, + { "Jwt", ApplePlatform.MacOSX }, + { "Keepalive", All }, + { "Keycode", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Keyerror", All }, + { "Keyi", All }, + { "Keypath", ApplePlatform.MacOSX }, + { "Keypoint", All }, + { "Keypoints", All }, + { "Kibibits", All }, + { "Kickboard", All & ~ApplePlatform.TVOS }, + { "Kiloampere", All }, + { "Kiloamperes", All }, + { "Kiloohms", All }, + { "Kilopascals", All }, + { "ks", All }, + { "Kullback", All }, // Kullback-Leibler Divergence + { "Lacunarity", All }, + { "Langauges", All & ~ApplePlatform.MacOSX }, + { "Latm", All }, // Low Overhead Audio Transport Multiplex + { "Lbc", All }, + { "Ldaps", All }, + { "Lerp", All }, + { "libcompression", All }, + { "libdispatch", All }, + { "Lingustic", All }, + { "Lod", All }, + { "Lopass", All }, + { "Lowlevel", All }, + { "Lpcm", All }, + { "Lstm", All }, + { "Lte", All }, + { "Ltr", All }, + { "Lun", All }, + { "Lut", All }, + { "Lzfse", All }, // acronym + { "Lzma", All }, // acronym + { "Lzw", ApplePlatform.MacOSX }, + { "Mada", All & ~ApplePlatform.TVOS }, // payment system + { "Matchingcoalesce", All }, + { "Mcp", All }, // metacarpophalangeal (hand) + { "Mebibits", All }, + { "Mebx", All }, + { "Meeza", All & ~ApplePlatform.TVOS }, + { "Megaampere", All }, + { "Megaamperes", All }, + { "Megaliters", All }, + { "Megameters", All }, + { "Megaohms", All }, + { "Megapascals", All }, + { "Mennekes", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Metacharacters", All }, + { "Metadatas", All }, + { "Metalness", All }, + { "Mgmt", All }, + { "Microampere", All }, + { "Microamperes", All }, + { "Microohms", All }, + { "Microwatts", All }, + { "Mifare", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Millimoles", All }, + { "Milliohms", All }, + { "Minification", All }, + { "Mmw", All }, + { "Mncs", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Mobike", All }, // acronym + { "Monoline", All & ~ApplePlatform.TVOS }, + { "Morpher", All }, + { "Mpe", All }, // acronym + { "Mps", All }, + { "Msaa", All }, // multisample anti-aliasing + { "Msi", All }, + { "Mtc", All }, // acronym + { "Mtgp", All }, + { "Mtl", All }, + { "Mtu", All }, // acronym + { "Muid", All & ~ApplePlatform.TVOS }, + { "Mul", All }, + { "Mult", All }, + { "Multiary", All }, + { "Multipath", All }, + { "Multipeer", All }, + { "Multiscript", All }, + { "Multiselect", All & ~ApplePlatform.MacOSX }, + { "Multivariant", All }, + { "Multiview", All }, + { "Muxed", All }, + { "Nacs", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Nai", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Nanaco", All & ~ApplePlatform.TVOS }, + { "Nand", All }, + { "Nanograms", All }, + { "Nanowatts", All }, + { "Ncdhw", All }, + { "Nchw", All }, + { "nd", All }, + { "Ndef", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Ndhwc", All }, + { "Nesterov", All }, + { "Nestrov", All }, + { "Nfc", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Nfnt", All }, + { "Nhwc", All }, + { "Nntps", All }, + { "Nonenumerated", ApplePlatform.MacOSX }, + { "Noninteractive", All & ~ApplePlatform.TVOS }, + { "Noop", All }, + { "Nop", ApplePlatform.MacOSX }, + { "Nsa", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Nsevent", ApplePlatform.MacOSX }, + { "Nsl", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, // InternetLocationNslNeighborhoodIcon + { "Ntlm", All }, + { "Ntsc", All }, + { "Numberof", ApplePlatform.MacOSX }, + { "Nyquist", All & ~ApplePlatform.MacOSX }, + { "Objectness", All }, + { "Occlussion", All }, + { "Ocr", All }, + { "Ocsp", All }, // Online Certificate Status Protocol + { "Octree", All }, + { "Ocurrences", All }, + { "Odia", All }, + { "Ohwi", All }, + { "Oid", All }, + { "Oidhw", All }, + { "Oihw", All }, + { "Onnx", All }, + { "Oper", All & ~ApplePlatform.MacOSX }, + { "Organisation", All }, // kCGImagePropertyIPTCExtRegistryOrganisationID in Xcode9.3-b1 + { "Orth", All }, + { "Osa", All }, // Open Scripting Architecture + { "Otsu", All }, // threshold for image binarization + { "ove", All }, + { "Overline", All & ~ApplePlatform.TVOS }, + { "Paeth", All }, // PNG filter + { "Palettize", All }, + { "Parms", All }, + { "Pausable", All }, + { "Pbm", ApplePlatform.MacOSX }, + { "Pci", All & ~ApplePlatform.MacOSX }, + { "Pcl", All }, + { "Pcm", All }, + { "Pde", ApplePlatform.MacOSX }, + { "Pdu", All }, + { "Peap", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Pebibits", All }, + { "Performwith", ApplePlatform.MacOSX }, + { "Perlin", All }, + { "Persistable", All }, + { "Persistance", All }, + { "Petabits", All }, + { "Pfs", All }, // acronym + { "Philox", All }, + { "Photoplethysmogram", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Phq", All & ~ApplePlatform.TVOS }, + { "Phy", ApplePlatform.MacOSX }, + { "Picometers", All }, + { "Picowatts", All }, + { "Pkcs", All }, + { "Placemark", All }, + { "Playout", All }, + { "Pnc", All }, // MIDI + { "Pnorm", All }, + { "Polyline", All }, + { "Polylines", All }, + { "Popularimeter", All }, + { "Postback", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Ppd", ApplePlatform.MacOSX }, // PostScript Printer Description + { "Ppk", All }, + { "Preauthentication", ApplePlatform.MacOSX }, + { "Preds", All }, + { "Prefilter", All }, + { "Prereleased", All }, + { "Prerolls", All }, + { "Preseti", All }, + { "Previewable", ApplePlatform.MacOSX }, + { "Prf", All & ~ApplePlatform.TVOS }, + { "Propogate", All }, + { "Psec", All }, + { "Psk", All }, + { "Pskc", All & ~ApplePlatform.TVOS }, + { "Psm", All }, // Protocol/Service Multiplexer + { "Ptp", ApplePlatform.MacOSX }, + { "Pvr", All }, + { "Pvrtc", All }, // MTLBlitOption - PowerVR Texture Compression + { "Qos", All }, + { "Quadding", All }, + { "Quaterniond", All }, + { "Quic", All }, + { "Qura", All }, + { "Qwac", All }, + { "Raycast", ApplePlatform.iOS }, + { "Raycasts", ApplePlatform.iOS }, + { "Reacquirer", All }, + { "Reassociation", ApplePlatform.MacOSX }, + { "Reauthentication", ApplePlatform.MacOSX }, + { "Rectfrom", ApplePlatform.MacOSX }, + { "Registeration", ApplePlatform.MacOSX }, + { "Reinvitation", All }, + { "Reinvite", All }, + { "Rel", All }, + { "Relocalization", ApplePlatform.iOS }, + { "Relu", All }, // Rectified Linear Unit (ML) + { "Remmote", All }, + { "Replayable", All }, + { "Reprojection", All }, + { "Rgb", All }, + { "Rgba", All }, + { "Rgbaf", All }, + { "Rgbah", All }, + { "Rgbx", All }, + { "Rggb", All }, // acronym for Red, Green, Green, Blue + { "Rint", All }, + { "Rle", All }, + { "Rnn", All }, + { "Roi", All }, + { "Romm", All }, // acronym: Reference Output Medium Metric + { "Rpa", All }, + { "Rpn", All }, // acronym + { "Rsa", All }, // Rivest, Shamir and Adleman + { "Rsapss", All }, + { "Rsqrt", All }, // reciprocal square root + { "Rssi", All }, + { "Rtl", All }, + { "Rtp", All & ~ApplePlatform.MacOSX }, + { "Rtsp", All }, + { "Saml", All & ~ApplePlatform.MacCatalyst }, // acronym + { "Scc", All }, + { "Scn", All }, + { "Sdh", ApplePlatform.TVOS }, + { "Sdk", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Sdnn", All & ~ApplePlatform.TVOS }, + { "Sdof", ApplePlatform.MacOSX }, + { "Sdr", All }, + { "Sdtv", ApplePlatform.TVOS }, // acronym: Standard Definition Tele Vision + { "Securit", ApplePlatform.iOS }, + { "Seekable", All }, + { "Sel", All & ~ApplePlatform.MacOSX }, + { "Selu", All }, // Scaled Exponential Linear unit (ML) + { "Semitransient", ApplePlatform.MacOSX }, + { "Sensel", All }, + { "Shadable", All }, + { "Siemen", All & ~ApplePlatform.TVOS }, + { "Signbit", All }, + { "Sint", All }, // as in "Signed Integer" + { "Sixtyfour", ApplePlatform.MacOSX }, + { "Slerp", All }, + { "Slomo", All }, + { "Smpte", All }, + { "Snapshotter", All }, + { "Snn", All }, + { "Snorm", All }, + { "Sobel", All }, + { "Softmax", All }, // get_SoftmaxNormalization + { "Sopen", ApplePlatform.MacOSX }, + { "Spacei", All }, + { "Spl", All }, + { "Sqrt", All }, + { "Srgb", All }, + { "Ssid", All }, + { "Ssids", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Ssml", All }, + { "Sso", ApplePlatform.MacOSX }, + { "st", All }, + { "Sta", ApplePlatform.MacOSX }, + { "Standarize", All }, + { "Strided", All }, + { "Subband", All & ~ApplePlatform.TVOS }, + { "Subbeat", All }, + { "Subcaption", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Subcardioid", All & ~ApplePlatform.MacOSX }, + { "Subentities", All }, + { "Subfilter", All & ~ApplePlatform.TVOS }, + { "Subfilters", All & ~ApplePlatform.TVOS }, + { "Subheadline", All }, + { "Sublocality", All }, + { "Sublocation", All }, + { "Submesh", All }, + { "Submeshes", All }, + { "Subpixel", All }, + { "Subresources", All }, + { "Subsec", All }, + { "Suica", All & ~ApplePlatform.TVOS }, // Japanese contactless smart card type + { "Superentity", All }, + { "Supertype", All }, + { "Supertypes", All }, + { "Supression", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Svfg", All }, + { "Svg", All }, // Scalable Vector Graphics + { "Svgf", All }, + { "Swolf", All & ~ApplePlatform.TVOS }, + { "Sysex", All }, + { "Targetand", ApplePlatform.MacOSX }, + { "Tbgr", All }, + { "Tdoa", ApplePlatform.iOS }, + { "Tebibits", All }, + { "Tensorflow", All }, + { "Tessellator", All }, + { "Texcoord", All }, + { "Texel", All }, + { "Tga", All }, + { "th", All }, + { "Threadgroup", All }, + { "Threadgroups", All }, + { "Thumbnailing", All & ~ApplePlatform.TVOS }, + { "Thumbstick", All }, + { "Thumbsticks", ApplePlatform.iOS }, + { "Timecodes", All & ~ApplePlatform.TVOS }, + { "Tls", All }, + { "Tlv", All }, + { "Tmoney", All & ~ApplePlatform.TVOS }, + { "Toc", All }, + { "Toci", All }, + { "Tonemap", All }, + { "Transceive", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Trc", All }, + { "Tri", All }, + { "Ttls", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Tweening", All }, + { "Twentyfour", ApplePlatform.MacOSX }, + { "Twips", ApplePlatform.MacOSX }, + { "tx", All }, + { "ty", All }, + { "Udi", All & ~ApplePlatform.TVOS }, + { "Udp", All }, + { "Uid", All & ~ApplePlatform.TVOS }, + { "Unconfigured", All & ~ApplePlatform.MacOSX }, + { "Undecodable", All }, + { "Underrun", All }, + { "Unemphasized", ApplePlatform.MacOSX }, + { "Unentitled", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Unfetched", All }, + { "Unioning", All }, + { "Unmap", All }, + { "Unmatch", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Unorm", All }, + { "Unpremultiplied", All }, + { "Unpremultiplying", All }, + { "Unprepare", All }, + { "Unproject", All }, + { "Unpublish", All }, + { "Unsolo", All }, + { "Unsynced", ApplePlatform.MacOSX | ApplePlatform.iOS }, + { "Untrash", ApplePlatform.iOS }, + { "Upce", All }, + { "Upi", ApplePlatform.iOS }, + { "Uri", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Usac", All }, // Unified Speech and Audio Coding + { "Usd", All }, // Universal Scene Description + { "Usdz", All }, // USD zip + { "Usec", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Ussd", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Uterance", All }, + { "Utf", All }, + { "Uti", All & ~ApplePlatform.TVOS }, + { "Varispeed", All }, + { "Vbr", All }, + { "Vbv", All }, + { "Vergence", All }, + { "Vnode", All }, + { "Voip", ApplePlatform.MacCatalyst }, + { "Voronoi", All }, + { "Vpn", All }, + { "Vtt", All }, + { "Waon", All & ~ApplePlatform.TVOS }, + { "Warichu", All }, + { "Warpable", All }, + { "Wcdma", All }, + { "Wep", ApplePlatform.iOS | ApplePlatform.MacCatalyst }, + { "Wifes", All & ~ApplePlatform.TVOS }, + { "Willl", All & ~ApplePlatform.TVOS }, + { "Wlan", ApplePlatform.MacOSX | ApplePlatform.MacCatalyst }, + { "Wpa", All & ~ApplePlatform.TVOS }, + { "Writeability", All }, + { "Xattr", ApplePlatform.MacOSX }, + { "Xattrs", ApplePlatform.MacOSX }, + { "Xbgr", All }, + { "Xmp", All }, + { "Xnor", All }, + { "Xrgb", All }, + { "xy", All }, + { "Xyz", All }, + { "Xzy", All }, + { "Yobibits", All }, + { "Yottabits", All }, + { "Yuv", ApplePlatform.MacOSX }, + { "Yuvk", ApplePlatform.MacOSX }, + { "yuvs", All }, + { "yx", All }, + { "Yxz", All }, + { "yy", All }, + { "Yyy", All }, + { "Yzx", All }, + { "Zebibits", All }, + { "Zenkaku", All & ~ApplePlatform.MacOSX }, + { "Zettabits", All }, + { "Zlib", All }, + { "Zxy", All }, + { "Zyx", All }, }; - // ease maintenance of the list + // tracks which allowed words were actually seen during TypoTest HashSet used = new HashSet (); bool SkipAllowed (string? typeName, string? methodName, string typo) { - if (allowed.Contains (typo)) { + if (allowed.TryGetValue (typo, out var platforms) && platforms.HasFlag (TestRuntime.CurrentPlatform)) { used.Add (typo); return true; } @@ -758,7 +844,7 @@ public virtual void AttributeTypoTest () foreach (Type t in types) AttributeTypo (t, ref totalErrors); - Assert.AreEqual (0, totalErrors, "Attributes have typos!"); + Assert.That (totalErrors, Is.EqualTo (0), "Attributes have typos!"); } void AttributeTypo (Type t, ref int totalErrors) @@ -785,6 +871,14 @@ void AttributeTypo (Type t, ref int totalErrors) [Test] public virtual void TypoTest () { + AssertMatchingOSVersionAndSdkVersion (); + + // that's slow and there's no value to run it on devices as the API names + // being verified won't change from the simulator + TestRuntime.AssertSimulatorOrDesktop ("Typos only detected on simulator/desktop"); + + using var checker = new SpellChecker (); + var types = Assembly.GetTypes (); int totalErrors = 0; foreach (Type t in types) { @@ -793,7 +887,7 @@ public virtual void TypoTest () continue; string txt = NameCleaner (t.Name); - var typo = GetCachedTypo (txt); + var typo = GetCachedTypo (checker, txt); if (typo.Length > 0) { if (!Skip (t, typo)) { ReportError ("Typo in TYPE: {0} - {1} ", t.Name, typo); @@ -810,7 +904,7 @@ public virtual void TypoTest () continue; txt = NameCleaner (f.Name); - typo = GetCachedTypo (txt); + typo = GetCachedTypo (checker, txt); if (typo.Length > 0) { if (!Skip (f, typo)) { ReportError ("Typo in FIELD name: {0} - {1}, Type: {2}", f.Name, typo, t.Name); @@ -828,7 +922,7 @@ public virtual void TypoTest () continue; txt = NameCleaner (m.Name); - typo = GetCachedTypo (txt); + typo = GetCachedTypo (checker, txt); if (typo.Length > 0) { if (!Skip (m, typo)) { ReportError ("Typo in METHOD name: {0} - {1}, Type: {2}", m.Name, typo, t.Name); @@ -839,7 +933,7 @@ public virtual void TypoTest () var parameters = m.GetParameters (); foreach (ParameterInfo p in parameters) { txt = NameCleaner (p.Name); - typo = GetCachedTypo (txt); + typo = GetCachedTypo (checker, txt); if (typo.Length > 0) { ReportError ("Typo in PARAMETER Name: {0} - {1}, Method: {2}, Type: {3}", p.Name, typo, m.Name, t.Name); totalErrors++; @@ -849,13 +943,16 @@ public virtual void TypoTest () } } } -#if false - // ease removal of unrequired values (but needs to be checked for every profile) - var unused = allowed.Except (used); - foreach (var typo in unused) - Console.WriteLine ("Unused entry \"{0}\"", typo); -#endif - Assert.AreEqual (0, totalErrors, "Typos!"); + // verify that all allowed words for the current platform are still needed + var currentPlatform = TestRuntime.CurrentPlatform; + var unused = allowed.Keys + .Where (w => allowed [w].HasFlag (currentPlatform)) + .Except (used); + foreach (var typo in unused) { + ReportError ($"Unnecessary allowed typo \"{typo}\" is not present in any API name"); + totalErrors++; + } + Assert.That (totalErrors, Is.EqualTo (0), "Typos!"); } string? GetMessage (object attribute) @@ -926,13 +1023,25 @@ void AttributesMessageTypoRules (MemberInfo mi, string typeName, ref int totalEr } Dictionary cached_typoes = new Dictionary (); - string GetCachedTypo (string txt) + string GetCachedTypo (SpellChecker checker, string txt) { if (!cached_typoes.TryGetValue (txt, out var rv)) - cached_typoes [txt] = rv = GetTypo (txt); + cached_typoes [txt] = rv = GetTypo (checker, txt); return rv; } - public abstract string GetTypo (string txt); + + string GetTypo (SpellChecker checker, string txt) + { + var checkRange = new NSRange (0, txt.Length); +#if MONOMAC + var typoRange = checker.CheckSpelling (txt, 0, "en_US", false, 0, out var _); +#else + var typoRange = checker.RangeOfMisspelledWordInString (txt, checkRange, checkRange.Location, false, "en_US"); +#endif + if (typoRange.Length == 0) + return String.Empty; + return txt.Substring ((int) typoRange.Location, (int) typoRange.Length); + } static StringBuilder clean = new StringBuilder (); @@ -1029,7 +1138,7 @@ public void ConstantsCheck () switch (fi.Name) { case "Version": case "SdkVersion": - Assert.True (Version.TryParse (s, out _), fi.Name); + Assert.That (Version.TryParse (s, out _), Is.True, fi.Name); break; #if !XAMCORE_5_0 case "AssetsLibraryLibrary": @@ -1043,22 +1152,15 @@ public void ConstantsCheck () case "MLComputeLibrary": // Xcode 12 beta 2 does not ship these framework/headers for the simulators if (TestRuntime.IsDevice) - Assert.True (CheckLibrary (s), fi.Name); + Assert.That (CheckLibrary (s), Is.True, fi.Name); break; #endif #if __TVOS__ - case "MetalPerformanceShadersLibrary": case "MetalPerformanceShadersGraphLibrary": // not supported in tvOS (12.1) simulator so load fails if (TestRuntime.IsSimulatorOrDesktop) break; goto default; - case "PhaseLibrary": - // framework support for tvOS was added in xcode 15 - // but not supported on tvOS simulator so load fails - if (TestRuntime.IsSimulatorOrDesktop) - break; - goto default; #endif case "MetalFXLibrary": if (TestRuntime.IsSimulatorOrDesktop) @@ -1082,9 +1184,6 @@ public void ConstantsCheck () // NFC is currently not available on iPad if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) continue; - // Phone works unless Xcode 12 on simulator - if (TestRuntime.IsSimulatorOrDesktop && TestRuntime.CheckXcodeVersion (12, 0)) - continue; } #endif #if __MACOS__ @@ -1092,7 +1191,7 @@ public void ConstantsCheck () if (fi.Name == "AutomaticAssessmentConfigurationLibrary" && !TestRuntime.CheckXcodeVersion (11, 4)) continue; #endif - Assert.True (CheckLibrary (s), fi.Name); + Assert.That (CheckLibrary (s), Is.True, fi.Name); } else { Assert.Fail ($"Unknown '{fi.Name}' field cannot be verified - please fix me!"); } diff --git a/tests/introspection/ApiWeakPropertyTest.cs b/tests/introspection/ApiWeakPropertyTest.cs index e11770ba8dbb..da5e64d5025b 100644 --- a/tests/introspection/ApiWeakPropertyTest.cs +++ b/tests/introspection/ApiWeakPropertyTest.cs @@ -102,7 +102,7 @@ public void WeakPropertiesHaveArgumentSemantic () n++; } } - Assert.AreEqual (0, Errors, "{0} errors found in {1} fields validated: {2}", Errors, n, string.Join (", ", failed_properties)); + Assert.That (Errors, Is.EqualTo (0), $"{Errors} errors found in {n} fields validated: {string.Join (", ", failed_properties)}"); } bool CheckArgumentSemantic (MethodInfo meth, [NotNullWhen (true)] out string? error) diff --git a/tests/introspection/Assets.xcassets/AppIcons.appiconset/Contents.json b/tests/introspection/Assets.xcassets/AppIcons.appiconset/Contents.json index 284e15f9906c..0e65c18b41c3 100644 --- a/tests/introspection/Assets.xcassets/AppIcons.appiconset/Contents.json +++ b/tests/introspection/Assets.xcassets/AppIcons.appiconset/Contents.json @@ -1,208 +1,15 @@ { "images": [ { - "size": "29x29", - "scale": "1x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "2x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "3x", - "idiom": "iphone" - }, - { - "size": "40x40", - "scale": "2x", - "idiom": "iphone" - }, - { - "size": "40x40", - "scale": "3x", - "idiom": "iphone" - }, - { - "filename": "icon-app-57.png", - "size": "57x57", - "scale": "1x", - "idiom": "iphone" - }, - { - "filename": "icon-app-57@2x.png", - "size": "57x57", - "scale": "2x", - "idiom": "iphone" - }, - { - "filename": "icon-app-60@2x.png", - "size": "60x60", - "scale": "2x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "29x29", - "scale": "2x", - "idiom": "ipad" - }, - { - "size": "40x40", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "40x40", - "scale": "2x", - "idiom": "ipad" - }, - { - "size": "50x50", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "50x50", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-83.5@2x.png", - "size": "83.5x83.5", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-72.png", - "size": "72x72", - "scale": "1x", - "idiom": "ipad" - }, - { - "filename": "icon-app-72@2x.png", - "size": "72x72", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-76.png", - "size": "76x76", - "scale": "1x", - "idiom": "ipad" - }, - { - "filename": "icon-app-76@2x.png", - "size": "76x76", - "scale": "2x", - "idiom": "ipad" - }, - { - "role": "notificationCenter", - "size": "24x24", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "notificationCenter", - "size": "27.5x27.5", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "companionSettings", - "size": "29x29", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "companionSettings", - "size": "29x29", - "scale": "3x", - "idiom": "watch" - }, - { - "role": "appLauncher", - "size": "40x40", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "quickLook", - "size": "86x86", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "quickLook", - "size": "98x98", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "size": "16x16", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "16x16", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "32x32", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "32x32", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "128x128", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "128x128", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "256x256", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "256x256", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "512x512", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "512x512", - "scale": "2x", - "idiom": "mac" + "filename": "icon-1024.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" } ], "info": { - "version": 1, - "author": "xcode" + "author": "xcode", + "version": 1 } -} \ No newline at end of file +} + diff --git a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-1024.png b/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-1024.png new file mode 100644 index 000000000000..1e62561f25b7 Binary files /dev/null and b/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-1024.png differ diff --git a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-57.png b/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-57.png deleted file mode 100644 index ce1d9df94d4f..000000000000 Binary files a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-57.png and /dev/null differ diff --git a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png b/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png deleted file mode 100644 index d34d9c694d3f..000000000000 Binary files a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png and /dev/null differ diff --git a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png b/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png deleted file mode 100644 index 4409624b29d9..000000000000 Binary files a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png and /dev/null differ diff --git a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-72.png b/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-72.png deleted file mode 100644 index 9a77ea277312..000000000000 Binary files a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-72.png and /dev/null differ diff --git a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png b/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png deleted file mode 100644 index 32f57d7d89da..000000000000 Binary files a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png and /dev/null differ diff --git a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-76.png b/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-76.png deleted file mode 100644 index 12db0c47cc4e..000000000000 Binary files a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-76.png and /dev/null differ diff --git a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png b/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png deleted file mode 100644 index 163f1c7f0f18..000000000000 Binary files a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png and /dev/null differ diff --git a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png b/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png deleted file mode 100644 index 0bac1da399b5..000000000000 Binary files a/tests/introspection/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png and /dev/null differ diff --git a/tests/introspection/MacApiTypoTest.cs b/tests/introspection/MacApiTypoTest.cs deleted file mode 100644 index d9fd73e0ab51..000000000000 --- a/tests/introspection/MacApiTypoTest.cs +++ /dev/null @@ -1,28 +0,0 @@ - -using AppKit; - -namespace Introspection { - - [TestFixture] - public class MacApiTypoTest : ApiTypoTest { - NSSpellChecker? checker; - - public override void TypoTest () - { - AssertMatchingOSVersionAndSdkVersion (); - checker = new NSSpellChecker (); - - base.TypoTest (); - } - - public override string GetTypo (string txt) - { - var checkRange = new NSRange (0, txt.Length); - nint wordCount; - var typoRange = checker!.CheckSpelling (txt, 0, "en_US", false, 0, out wordCount); - if (typoRange.Length == 0) - return String.Empty; - return txt.Substring ((int) typoRange.Location, (int) typoRange.Length); - } - } -} diff --git a/tests/introspection/dotnet/shared.csproj b/tests/introspection/dotnet/shared.csproj index bea97d7308c1..b5d980752c99 100644 --- a/tests/introspection/dotnet/shared.csproj +++ b/tests/introspection/dotnet/shared.csproj @@ -16,17 +16,11 @@ $(DefineConstants);DEBUG - enable - $(NoWarn);IL2026;IL2057;IL2059;IL2070;IL2075;IL2096 $(NoWarn);CA1422 - - - true - Nullable @@ -40,7 +34,6 @@ - MacMain.cs @@ -58,8 +51,8 @@ + - @@ -69,15 +62,7 @@ - - - - - - - - - + @@ -99,6 +84,9 @@ ApiPInvokeTest.cs + + ApiSimulatorAvailabilityTest.cs + ApiProtocolTest.cs diff --git a/tests/introspection/iOSApiCtorInitTest.cs b/tests/introspection/iOSApiCtorInitTest.cs index 777adbd02c60..58dc7992b39e 100644 --- a/tests/introspection/iOSApiCtorInitTest.cs +++ b/tests/introspection/iOSApiCtorInitTest.cs @@ -31,28 +31,12 @@ public iOSApiCtorInitTest () protected override bool Skip (Type type) { switch (type.Namespace) { - // all default ctor did not work and were replaced with [Obsolete("",true)] placeholders - // reflecting on those would create invalid instances (no handle) that crash the app - case "CoreBluetooth": - case "MonoTouch.CoreBluetooth": - return true; - - case "CoreAudioKit": - case "MonoTouch.CoreAudioKit": - case "Metal": - case "MonoTouch.Metal": - // they works with iOS9 beta 4 (but won't work on older simulators) - if (TestRuntime.IsSimulatorOrDesktop && !TestRuntime.CheckXcodeVersion (7, 0)) - return true; - break; case "MetalKit": - case "MonoTouch.MetalKit": case "MetalPerformanceShaders": - case "MonoTouch.MetalPerformanceShaders": - if (TestRuntime.IsSimulatorOrDesktop) - return true; // some devices don't support metal and that crash some API that does not check that, e.g. #33153 - if (!TestRuntime.CheckXcodeVersion (7, 0) || (MTLDevice.SystemDefault is null)) + if (MTLDevice.SystemDefault is null) + return true; + if (TestRuntime.IsSimulatorOrDesktop) return true; break; #if __TVOS__ @@ -156,10 +140,6 @@ protected override bool Skip (Type type) case "NSPersistentStoreCoordinator": return true; - // Metal is not available on the (iOS8) simulator - case "CAMetalLayer": - return TestRuntime.IsSimulatorOrDesktop && !TestRuntime.CheckXcodeVersion (11, 0); - // in 8.2 beta 1 this crash the app (simulator) without giving any details in the logs case "WKUserNotificationInterfaceController": return true; @@ -175,10 +155,6 @@ protected override bool Skip (Type type) // NSInvalidArgumentException Reason: image must be non-nil return true; - // these work only on devices, so we skip the simulator - case "MTLHeapDescriptor": - case "MTLSharedEventListener": - return TestRuntime.IsSimulatorOrDesktop; // iOS 11 Beta 1 case "UICollectionViewFocusUpdateContext": // [Assert] -init is not a useful initializer for this class. Use one of the designated initializers instead case "UIFocusUpdateContext": // [Assert] -init is not a useful initializer for this class. Use one of the designated initializers instead @@ -190,21 +166,11 @@ protected override bool Skip (Type type) return true; case "IOSurface": // Only works on device before Xcode 11 return !TestRuntime.CheckXcodeVersion (11, 0); - case "NEHotspotEapSettings": // Wireless Accessory Configuration is not supported in the simulator. - case "NEHotspotConfigurationManager": - case "NEHotspotHS20Settings": - return TestRuntime.IsSimulatorOrDesktop; // iOS 12 case "INGetAvailableRestaurantReservationBookingDefaultsIntentResponse": // Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Unable to initialize 'INGetAvailableRestaurantReservationBookingDefaultsIntentResponse'. Please make sure that your intent definition file is valid. case "INGetAvailableRestaurantReservationBookingsIntentResponse": // Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Unable to initialize 'INGetAvailableRestaurantReservationBookingsIntentResponse'. Please make sure that your intent definition file is valid. case "INGetRestaurantGuestIntentResponse": // Objective-C exception thrown. Name: NSInternalInconsistencyException Reason: Unable to initialize 'INGetRestaurantGuestIntentResponse'. Please make sure that your intent definition file is valid. return TestRuntime.CheckXcodeVersion (10, 0); - case "CMMovementDisorderManager": // Not available in simulator, added info to radar://41110708 - return TestRuntime.IsSimulatorOrDesktop; - case "RPSystemBroadcastPickerView": // Symbol not available in simulator - return TestRuntime.IsSimulatorOrDesktop; - case "ICNotificationManagerConfiguration": // This works on device but not on simulator, and docs explicitly says it is user creatable - return TestRuntime.IsSimulatorOrDesktop; case "VNDocumentCameraViewController": // Name: NSGenericException Reason: Document camera is not available on simulator return TestRuntime.IsSimulatorOrDesktop; case "AVAudioRecorder": // Stopped working with Xcode 11.2 beta 2 diff --git a/tests/introspection/iOSApiFieldTest.cs b/tests/introspection/iOSApiFieldTest.cs index 11b1157a24f1..638aefa8cc55 100644 --- a/tests/introspection/iOSApiFieldTest.cs +++ b/tests/introspection/iOSApiFieldTest.cs @@ -129,51 +129,15 @@ protected override bool Skip (string constantName, string? libraryName) if (Class.GetHandle ("NFCNDEFReaderSession") == IntPtr.Zero) return true; break; - case "IOSurface": - return TestRuntime.IsSimulatorOrDesktop && !TestRuntime.CheckXcodeVersion (9, 0); } switch (constantName) { - // grep ImageIO binary shows those symbols are not part of the binary - // that match older results (nil) when loading them (see above) - case "kCGImagePropertyAPNGLoopCount": - case "kCGImagePropertyAPNGDelayTime": - case "kCGImagePropertyAPNGUnclampedDelayTime": - case "kCGImagePropertyMakerFujiDictionary": - case "kCGImagePropertyMakerMinoltaDictionary": - case "kCGImagePropertyMakerOlympusDictionary": - case "kCGImagePropertyMakerPentaxDictionary": - // - case "kCFHTTPAuthenticationSchemeOAuth1": - return true; // Apple does not ship a PushKit for every arch on some devices :( case "PKPushTypeVoIP": return TestRuntime.IsDevice; - // there's only partial support for metal on the simulator (on iOS9 beta 5) but most other frameworks - // that interop with it are not (yet) supported - case "kCVMetalTextureCacheMaximumTextureAgeKey": - case "kCVMetalTextureUsage": - case "MPSRectNoClip": - case "MTLCommandBufferErrorDomain": - case "MTKTextureLoaderErrorDomain": - case "MTKTextureLoaderErrorKey": - case "MTKTextureLoaderOptionAllocateMipmaps": - case "MTKTextureLoaderOptionSRGB": - case "MTKTextureLoaderOptionTextureUsage": - case "MTKTextureLoaderOptionTextureCPUCacheMode": - case "MTKModelErrorDomain": - case "MTKModelErrorKey": - return TestRuntime.IsSimulatorOrDesktop; - // Xcode 12.2 Beta 1 does not ship this but it is available in Xcode 12.0... - case "HKMetadataKeyBarometricPressure": - return true; - case "kCMSampleAttachmentKey_HDR10PlusPerFrameData": - if (TestRuntime.IsSimulator) - return !TestRuntime.CheckXcodeVersion (14, 1); // not available in the iOS 16.0 simulator, but it is in the iOS 16.1 simulator - goto default; - default: - return false; } + + return base.Skip (constantName, libraryName); } } } diff --git a/tests/introspection/iOSApiPInvokeTest.cs b/tests/introspection/iOSApiPInvokeTest.cs index e5c240d80d03..d04bbd797a7e 100644 --- a/tests/introspection/iOSApiPInvokeTest.cs +++ b/tests/introspection/iOSApiPInvokeTest.cs @@ -18,54 +18,6 @@ namespace Introspection { // we want the tests to be available because we use the linker [Preserve (AllMembers = true)] public class iOSApiPInvokeTest : ApiPInvokeTest { - - protected override bool Skip (string symbolName) - { - var simulator = TestRuntime.IsSimulatorOrDesktop; - switch (symbolName) { - // Metal support inside simulator is only available in recent iOS9 SDK - case "MTLCreateSystemDefaultDevice": - return simulator && !UIDevice.CurrentDevice.CheckSystemVersion (9, 0); - // still most Metal helpers are not available on the simulator (even when the framework is present, it's missing symbols) - case "MPSSupportsMTLDevice": - case "MPSGetPreferredDevice": - // neither are the CoreVideo extensions for Metal - case "CVMetalTextureGetTexture": - case "CVMetalTextureIsFlipped": - case "CVMetalTextureGetCleanTexCoords": - case "CVMetalTextureCacheCreate": - case "CVMetalTextureCacheFlush": - case "CVMetalTextureCacheCreateTextureFromImage": - case "MTKMetalVertexDescriptorFromModelIO": - case "MTKModelIOVertexDescriptorFromMetal": - case "MTKModelIOVertexFormatFromMetal": - case "MTKMetalVertexFormatFromModelIO": - case "MTLIOCompressionContextAppendData": - case "MTLIOCreateCompressionContext": - case "MTLIOFlushAndDestroyCompressionContext": - case "MTLIOCompressionContextDefaultChunkSize": - case "MPSImageBatchIncrementReadCount": - case "MPSImageBatchSynchronize": - case "MPSImageBatchResourceSize": - case "MPSStateBatchIncrementReadCount": - case "MPSStateBatchSynchronize": - case "MPSStateBatchResourceSize": - case "MPSHintTemporaryMemoryHighWaterMark": - case "MPSSetHeapCacheDuration": - case "MPSGetImageType": - return simulator; - case "CVPixelBufferGetIOSurface": - case "CVPixelBufferCreateWithIOSurface": - return simulator && !TestRuntime.CheckXcodeVersion (11, 0); - - default: - // MLCompute not available in simulator as of Xcode 12 beta 3 - if (simulator && symbolName.StartsWith ("MLC", StringComparison.Ordinal)) - return true; - return base.Skip (symbolName); - } - } - protected override bool SkipAssembly (Assembly a) { if (a == typeof (NSObject).Assembly) { diff --git a/tests/introspection/iOSApiSimulatorAvailabilityTest.cs b/tests/introspection/iOSApiSimulatorAvailabilityTest.cs new file mode 100644 index 000000000000..8c46cf563b78 --- /dev/null +++ b/tests/introspection/iOSApiSimulatorAvailabilityTest.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Reflection; + +namespace Introspection { + + [TestFixture] + [Preserve (AllMembers = true)] + public class iOSApiSimulatorAvailabilityTest : ApiSimulatorAvailabilityTest { + + protected override bool SkipPInvoke (MethodInfo mi) + { + switch (mi.DeclaringType?.Namespace) { + case "CoreNFC": + if (Class.GetHandle ("NFCNDEFReaderSession") == IntPtr.Zero) + return true; + break; + } + + return base.SkipPInvoke (mi); + } + + protected override bool SkipField (PropertyInfo pi) + { + switch (pi.DeclaringType?.Namespace) { + case "CoreNFC": + if (Class.GetHandle ("NFCNDEFReaderSession") == IntPtr.Zero) + return true; + break; + case "DeviceCheck": + return true; + case "Phase": + return true; + } + + return base.SkipField (pi); + } + } +} diff --git a/tests/introspection/iOSApiTypoTest.cs b/tests/introspection/iOSApiTypoTest.cs deleted file mode 100644 index 42dafda1624d..000000000000 --- a/tests/introspection/iOSApiTypoTest.cs +++ /dev/null @@ -1,34 +0,0 @@ - -using UIKit; - -namespace Introspection { - - [TestFixture] - public class iOSApiTypoTest : ApiTypoTest { - UITextChecker checker = new UITextChecker (); - - public override string GetTypo (string txt) - { - var checkRange = new NSRange (0, txt.Length); - var typoRange = checker.RangeOfMisspelledWordInString (txt, checkRange, checkRange.Location, false, "en_US"); - if (typoRange.Length == 0) - return String.Empty; - return txt.Substring ((int) typoRange.Location, (int) typoRange.Length); - } - - public override void TypoTest () - { - // the dictionary used by iOS varies with versions and - // we don't want to maintain special cases for each version - var sdk = new Version (Constants.SdkVersion); - if (!UIDevice.CurrentDevice.CheckSystemVersion (sdk.Major, sdk.Minor)) - Assert.Ignore ("Typos only verified using the latest SDK"); - - // that's slow and there's no value to run it on devices as the API names - // being verified won't change from the simulator - TestRuntime.AssertSimulatorOrDesktop ("Typos only detected on simulator"); - - base.TypoTest (); - } - } -} diff --git a/tests/linker/AppDelegate.cs b/tests/linker/AppDelegate.cs index aada6d6653f9..052309946b8d 100644 --- a/tests/linker/AppDelegate.cs +++ b/tests/linker/AppDelegate.cs @@ -12,6 +12,6 @@ static partial void AddTestAssembliesImpl (HashSet assemblies) public class LoaderTest { public void TestAssemblyCount () { - Assert.AreEqual (2, TestLoader.GetTestAssemblies ().Count (), "Test assembly count"); + Assert.That (TestLoader.GetTestAssemblies ().Count (), Is.EqualTo (2), "Test assembly count"); } } diff --git a/tests/linker/BaseOptimizeGeneratedCodeTest.cs b/tests/linker/BaseOptimizeGeneratedCodeTest.cs index f4904e104fa4..82b58582d550 100644 --- a/tests/linker/BaseOptimizeGeneratedCodeTest.cs +++ b/tests/linker/BaseOptimizeGeneratedCodeTest.cs @@ -33,7 +33,7 @@ public void SetupBlock_CustomDelegate () var action = new Action (() => counter++); Custom (action); CustomWithAttribute (action); - Assert.AreEqual (2, counter, "Counter"); + Assert.That (counter, Is.EqualTo (2), "Counter"); } delegate void CustomDelegate (IntPtr block); @@ -91,7 +91,7 @@ public void SetupBlockPerfTest () for (var i = 0; i < iterations; i++) SetupBlockUnoptimized (unoptimizedAction); unoptimizedWatch.Stop (); - Assert.AreEqual (iterations, unoptimizedCounter, "Unoptimized Counter"); + Assert.That (unoptimizedCounter, Is.EqualTo (iterations), "Unoptimized Counter"); // Run optimized var optimizedWatch = System.Diagnostics.Stopwatch.StartNew (); @@ -99,7 +99,7 @@ public void SetupBlockPerfTest () for (var i = 0; i < iterations; i++) SetupBlockOptimized (optimizedAction); optimizedWatch.Stop (); - Assert.AreEqual (iterations, optimizedCounter, "Optimized Counter"); + Assert.That (optimizedCounter, Is.EqualTo (iterations), "Optimized Counter"); //Console.WriteLine ("Optimized: {0} ms", optimizedWatch.ElapsedMilliseconds); //Console.WriteLine ("Unoptimized: {0} ms", unoptimizedWatch.ElapsedMilliseconds); @@ -145,7 +145,7 @@ public void SetupBlockCodeTest () SetupBlockOptimized_LoadLocalVariable4 (action); SetupBlockOptimized_LoadLocalVariable (action); - Assert.AreEqual (19, counter, "Counter"); + Assert.That (counter, Is.EqualTo (19), "Counter"); } public delegate void Action_IntPtr (IntPtr param); @@ -158,7 +158,7 @@ public void SetupBlockCodeTest () unsafe static void BlockCallback (IntPtr block) { var descriptor = (BlockLiteral*) block; - var del = (Action) (descriptor->Target); + var del = (Action) (descriptor->Target)!; del (); } @@ -285,17 +285,17 @@ void SetupBlockOptimized_SpecificArgument ( int dummy208 = 0, int dummy218 = 0, int dummy228 = 0, int dummy238 = 0, int dummy248 = 0, int dummy258 = 0, int dummy268 = 0, int dummy278 = 0, int dummy288 = 0, int dummy298 = 0, int dummy209 = 0, int dummy219 = 0, int dummy229 = 0, int dummy239 = 0, int dummy249 = 0, int dummy259 = 0, int dummy269 = 0, int dummy279 = 0, int dummy289 = 0, int dummy299 = 0, - Action_IntPtr block_callback = null + Action_IntPtr? block_callback = null ) { // ldarg BlockLiteral block = new BlockLiteral (); - block.SetupBlock (block_callback, callback); + block.SetupBlock (block_callback!, callback); Bindings.Test.CFunctions.x_call_block (ref block); block.CleanupBlock (); } - Action_IntPtr block_callback_instance_field; + Action_IntPtr? block_callback_instance_field; [BindingImpl (BindingImplOptions.Optimizable)] void SetupBlockOptimized_LoadField (Action callback) { @@ -514,25 +514,25 @@ public void IsARM64CallingConvention () IEnumerable instructions; IEnumerable call_instructions; - method = typeof (BaseOptimizeGeneratedCodeTest).GetMethod (nameof (GetIsARM64CallingConventionOptimized), BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static); + method = typeof (BaseOptimizeGeneratedCodeTest).GetMethod (nameof (GetIsARM64CallingConventionOptimized), BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static)!; instructions = new ILReader (method); call_instructions = instructions.Where ((v) => v.OpCode.Name == "ldsfld"); - Assert.AreEqual (0, call_instructions.Count (), "optimized: no ldsfld instruction"); + Assert.That (call_instructions.Count (), Is.EqualTo (0), "optimized: no ldsfld instruction"); - method = typeof (BaseOptimizeGeneratedCodeTest).GetMethod (nameof (GetIsARM64CallingConventionNotOptimized), BindingFlags.NonPublic | BindingFlags.Instance); + method = typeof (BaseOptimizeGeneratedCodeTest).GetMethod (nameof (GetIsARM64CallingConventionNotOptimized), BindingFlags.NonPublic | BindingFlags.Instance)!; instructions = new ILReader (method); call_instructions = instructions.Where ((v) => v.OpCode.Name == "ldsfld"); - Assert.AreEqual (1, call_instructions.Count (), "not optimized: 1 ldsfld instruction"); - - method = typeof (Runtime).GetMethod ("GetIsARM64CallingConvention", BindingFlags.Static | BindingFlags.NonPublic); + Assert.That (call_instructions.Count (), Is.EqualTo (1), "not optimized: 1 ldsfld instruction"); + + method = typeof (Runtime).GetMethod ("GetIsARM64CallingConvention", BindingFlags.Static | BindingFlags.NonPublic)!; instructions = new ILReader (method); - Assert.AreEqual (2, instructions.Count (), "IL Count"); + Assert.That (instructions.Count (), Is.EqualTo (2), "IL Count"); Assert.That (instructions.Skip (0).First ().OpCode, Is.EqualTo (OpCodes.Ldc_I4_0).Or.EqualTo (OpCodes.Ldc_I4_1), "IL 1"); Assert.That (instructions.Skip (1).First ().OpCode, Is.EqualTo (OpCodes.Ret), "IL 2"); #endif - Assert.AreEqual (Runtime.IsARM64CallingConvention, GetIsARM64CallingConventionOptimized (), "Value optimized"); - Assert.AreEqual (Runtime.IsARM64CallingConvention, GetIsARM64CallingConventionNotOptimized (), "Value unoptimized"); + Assert.That (GetIsARM64CallingConventionOptimized (), Is.EqualTo (Runtime.IsARM64CallingConvention), "Value optimized"); + Assert.That (GetIsARM64CallingConventionNotOptimized (), Is.EqualTo (Runtime.IsARM64CallingConvention), "Value unoptimized"); } [BindingImplAttribute (BindingImplOptions.Optimizable)] diff --git a/tests/linker/CommonLinkAllTest.cs b/tests/linker/CommonLinkAllTest.cs index 45b0a6f8d4ca..58fe0325c34d 100644 --- a/tests/linker/CommonLinkAllTest.cs +++ b/tests/linker/CommonLinkAllTest.cs @@ -53,7 +53,7 @@ public class CommonLinkAllTest { public void BindingsAndBeforeInitField () { ObjCRuntime.Trampolines.SDInnerBlock.Invoke (IntPtr.Zero, 0); - var fields = Type.GetType ("ObjCRuntime.Trampolines+SDInnerBlock" + WorkAroundLinkerHeuristics).GetFields (BindingFlags.NonPublic | BindingFlags.Static); + var fields = Type.GetType ("ObjCRuntime.Trampolines+SDInnerBlock" + WorkAroundLinkerHeuristics)!.GetFields (BindingFlags.NonPublic | BindingFlags.Static); Assert.That (fields.Length, Is.EqualTo (1), "one"); Assert.That (fields [0].Name, Is.EqualTo ("Handler"), "Name"); } @@ -62,16 +62,16 @@ public void BindingsAndBeforeInitField () public void BindingsAndBeforeInitField_2 () { ObjCRuntime.Trampolines.SDInnerBlock_Misnamed.Invoke (IntPtr.Zero, 0); - var fields = Type.GetType ("ObjCRuntime.Trampolines+SDInnerBlock_Misnamed" + WorkAroundLinkerHeuristics).GetFields (BindingFlags.NonPublic | BindingFlags.Static); + var fields = Type.GetType ("ObjCRuntime.Trampolines+SDInnerBlock_Misnamed" + WorkAroundLinkerHeuristics)!.GetFields (BindingFlags.NonPublic | BindingFlags.Static); Assert.That (fields.Length, Is.EqualTo (0), "zero"); } [Test] public void TypeConverter_BuiltIn () { - Assert.NotNull (TypeDescriptor.GetConverter (new BuiltInConverter ()), "BuiltInConverter"); + Assert.That (TypeDescriptor.GetConverter (new BuiltInConverter ()), Is.Not.Null, "BuiltInConverter"); - string name = (typeof (BuiltInConverter).GetCustomAttributes (false) [0] as TypeConverterAttribute).ConverterTypeName; + string? name = (typeof (BuiltInConverter).GetCustomAttributes (false) [0] as TypeConverterAttribute)?.ConverterTypeName; var typename = $"System.ComponentModel.BooleanConverter, System.ComponentModel.TypeConverter, Version={typeof (int).Assembly.GetName ().Version}, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; Assert.That (name, Is.EqualTo (typename), "ConverterTypeName"); } @@ -79,9 +79,9 @@ public void TypeConverter_BuiltIn () [Test] public void TypeConverter_Custom () { - Assert.NotNull (TypeDescriptor.GetConverter (new TypeDescriptorTest ()), "TypeDescriptorTest"); + Assert.That (TypeDescriptor.GetConverter (new TypeDescriptorTest ()), Is.Not.Null, "TypeDescriptorTest"); - string name = (typeof (TypeDescriptorTest).GetCustomAttributes (false) [0] as TypeConverterAttribute).ConverterTypeName; + string? name = (typeof (TypeDescriptorTest).GetCustomAttributes (false) [0] as TypeConverterAttribute)?.ConverterTypeName; var typename = "LinkAll.CustomConverter, link all, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"; Assert.That (name, Is.EqualTo (typename), "ConverterTypeName"); } @@ -91,7 +91,7 @@ public void ConstantsVersion_4859 () { // Check that the Makefile generated a valid version number, e.g. "12.3." was not // reference: https://github.com/dotnet/macios/issues/4859 - Assert.True (Version.TryParse (ObjCRuntime.Constants.Version, out var _), "Version"); + Assert.That (Version.TryParse (ObjCRuntime.Constants.Version, out var _), Is.True, "Version"); } } } diff --git a/tests/linker/CommonLinkAnyTest.cs b/tests/linker/CommonLinkAnyTest.cs index 10f3a5ad8390..256ab6641fce 100644 --- a/tests/linker/CommonLinkAnyTest.cs +++ b/tests/linker/CommonLinkAnyTest.cs @@ -17,18 +17,18 @@ public class CommonLinkAnyTest { public void Blocks () { int i = 0; - string b = null; + string? b = null; NSSet s = new NSSet ("a", "b", "c"); s.Enumerate (delegate (NSObject obj, ref bool stop) { stop = i++ == 1; - b = obj.ToString (); + b = obj.ToString ()!; }); // test behavior (we did not break anything) - Assert.AreEqual ("b", b, "Stop"); + Assert.That (b, Is.EqualTo ("b"), "Stop"); // test that BlockLiteral is fully preserved int size = Marshal.SizeOf (typeof (BlockLiteral)); // e.g. unused 'reserved' must not be removed - Assert.AreEqual (IntPtr.Size == 8 ? 48 : 28, size, "BlockLiteral size"); + Assert.That (size, Is.EqualTo (IntPtr.Size == 8 ? 48 : 28), "BlockLiteral size"); } @@ -39,17 +39,17 @@ public void CallerFilePath () } // https://bugzilla.xamarin.com/show_bug.cgi?id=7114 - public static void Bug7114 ([CallerFilePath] string filePath = null) + public static void Bug7114 ([CallerFilePath] string? filePath = null) { - Assert.IsNotNull (filePath, "CallerFilePath"); + Assert.That (filePath, Is.Not.Null, "CallerFilePath"); } [Test] public void AppContextGetData () { // https://github.com/dotnet/runtime/issues/50290 - Assert.IsNotNull (AppContext.GetData ("APP_PATHS"), "APP_PATHS"); - Assert.IsNotNull (AppContext.GetData ("PINVOKE_OVERRIDE"), "PINVOKE_OVERRIDE"); + Assert.That (AppContext.GetData ("APP_PATHS"), Is.Not.Null, "APP_PATHS"); + Assert.That (AppContext.GetData ("PINVOKE_OVERRIDE"), Is.Not.Null, "PINVOKE_OVERRIDE"); } [Test] @@ -68,26 +68,26 @@ public void BackingFieldInGenericType () public void JsonSerializer_Serialize () { var a = JsonSerializer.Serialize (42); - Assert.AreEqual ("42", a, "serialized 42"); + Assert.That (a, Is.EqualTo ("42"), "serialized 42"); var b = JsonSerializer.Serialize (new int [] { 42, 3, 14, 15 }); - Assert.AreEqual ("[42,3,14,15]", b, "serialized array"); + Assert.That (b, Is.EqualTo ("[42,3,14,15]"), "serialized array"); } [Test] public void JsonSerializer_Deserialize () { var a = JsonSerializer.Deserialize ("42"); - Assert.AreEqual (42, a, "deserialized 42"); + Assert.That (a, Is.EqualTo (42), "deserialized 42"); var b = JsonSerializer.Deserialize ("[42,3,14,15]"); - CollectionAssert.AreEqual (new int [] { 42, 3, 14, 15 }, b, "deserialized array"); + Assert.That (b!, Is.EqualTo (new int [] { 42, 3, 14, 15 }), "deserialized array"); } [Test] public void AES () { - Assert.NotNull (Aes.Create (), "AES"); + Assert.That (Aes.Create (), Is.Not.Null, "AES"); } static bool waited; @@ -122,7 +122,7 @@ static async Task GetWebPageAsync () string content = await response.Content.ReadAsStringAsync (); waited = true; bool success = !String.IsNullOrEmpty (content); - Assert.IsTrue (success, $"received {content.Length} bytes"); + Assert.That (success, Is.True, $"received {content.Length} bytes"); } } } @@ -138,7 +138,7 @@ public void GetWebPageAsyncTest () if (requestError) { Assert.Inconclusive ($"Test cannot be trusted. Issues performing the request. Status code '{statusCode}'"); } else { - Assert.IsTrue (waited, "async/await worked"); + Assert.That (waited, Is.True, "async/await worked"); } } finally { SynchronizationContext.SetSynchronizationContext (current_sc); diff --git a/tests/linker/ILReader.cs b/tests/linker/ILReader.cs index dc9913c83dae..0e03255620f9 100644 --- a/tests/linker/ILReader.cs +++ b/tests/linker/ILReader.cs @@ -17,9 +17,9 @@ public class ILInstruction { public MethodBase Method; public OpCode OpCode; public int Offset; - public object Operand; + public object? Operand; - public ILInstruction (MethodBase method, int offset, OpCode opcode, object operand = null) + public ILInstruction (MethodBase method, int offset, OpCode opcode, object? operand = null) { this.Method = method; this.OpCode = opcode; @@ -31,7 +31,7 @@ public override string ToString () { var methodOperand = Operand as MethodBase; if (methodOperand is not null) - return $"IL_{Offset:0000} {OpCode} {methodOperand.DeclaringType.FullName}.{methodOperand.Name}"; + return $"IL_{Offset:0000} {OpCode} {methodOperand.DeclaringType?.FullName}.{methodOperand.Name}"; return $"IL_{Offset:0000} {OpCode} {(Operand is MethodBase ? ((MethodBase) Operand).Name : Operand?.ToString ())}"; } } @@ -44,7 +44,7 @@ public class ILReader : IEnumerable { static ILReader () { foreach (var fi in typeof (OpCodes).GetFields (BindingFlags.Public | BindingFlags.Static)) { - var opCode = (OpCode) fi.GetValue (null); + var opCode = (OpCode) fi.GetValue (null)!; var value = (ushort) opCode.Value; if (value < 0x100) oneByteOpcodes [value] = opCode; @@ -77,7 +77,7 @@ List Parse (MethodBase method) if (body is null) return rv; - var bytes = body.GetILAsByteArray (); + var bytes = body.GetILAsByteArray ()!; while (position < bytes.Length) rv.Add (ReadInstruction (method, bytes, ref position)); diff --git a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/Contents.json b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/Contents.json index 6be52c8f7640..0e65c18b41c3 100644 --- a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/Contents.json +++ b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/Contents.json @@ -1,221 +1,15 @@ { "images": [ { - "size": "29x29", - "scale": "1x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "2x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "3x", - "idiom": "iphone" - }, - { - "size": "40x40", - "scale": "2x", - "idiom": "iphone" - }, - { - "size": "40x40", - "scale": "3x", - "idiom": "iphone" - }, - { - "filename": "icon-app-57.png", - "size": "57x57", - "scale": "1x", - "idiom": "iphone" - }, - { - "filename": "icon-app-57@2x.png", - "size": "57x57", - "scale": "2x", - "idiom": "iphone" - }, - { - "filename": "icon-app-60@2x.png", - "size": "60x60", - "scale": "2x", - "idiom": "iphone" - }, - { - "filename": "icon-app-60@3x.png", - "size": "60x60", - "scale": "3x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "29x29", - "scale": "2x", - "idiom": "ipad" - }, - { - "size": "40x40", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "40x40", - "scale": "2x", - "idiom": "ipad" - }, - { - "size": "50x50", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "50x50", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-83.5@2x.png", - "size": "83.5x83.5", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-72.png", - "size": "72x72", - "scale": "1x", - "idiom": "ipad" - }, - { - "filename": "icon-app-72@2x.png", - "size": "72x72", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-76.png", - "size": "76x76", - "scale": "1x", - "idiom": "ipad" - }, - { - "filename": "icon-app-76@2x.png", - "size": "76x76", - "scale": "2x", - "idiom": "ipad" - }, - { - "role": "notificationCenter", - "size": "24x24", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "notificationCenter", - "size": "27.5x27.5", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "companionSettings", - "size": "29x29", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "companionSettings", - "size": "29x29", - "scale": "3x", - "idiom": "watch" - }, - { - "role": "appLauncher", - "size": "40x40", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "longLook", - "size": "44x44", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "quickLook", - "size": "86x86", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "quickLook", - "size": "98x98", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "size": "16x16", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "16x16", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "32x32", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "32x32", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "128x128", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "128x128", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "256x256", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "256x256", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "512x512", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "512x512", - "scale": "2x", - "idiom": "mac" + "filename": "icon-1024.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" } ], "info": { - "version": 1, - "author": "xcode" + "author": "xcode", + "version": 1 } -} \ No newline at end of file +} + diff --git a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/Icon-app-60@3x.png b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/Icon-app-60@3x.png deleted file mode 100644 index 45342a7513b6..000000000000 Binary files a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/Icon-app-60@3x.png and /dev/null differ diff --git a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-1024.png b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-1024.png new file mode 100644 index 000000000000..1e62561f25b7 Binary files /dev/null and b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-1024.png differ diff --git a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-57.png b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-57.png deleted file mode 100644 index ce1d9df94d4f..000000000000 Binary files a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-57.png and /dev/null differ diff --git a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png deleted file mode 100644 index d34d9c694d3f..000000000000 Binary files a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png and /dev/null differ diff --git a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png deleted file mode 100644 index 4409624b29d9..000000000000 Binary files a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png and /dev/null differ diff --git a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-72.png b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-72.png deleted file mode 100644 index 9a77ea277312..000000000000 Binary files a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-72.png and /dev/null differ diff --git a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png deleted file mode 100644 index 32f57d7d89da..000000000000 Binary files a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png and /dev/null differ diff --git a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-76.png b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-76.png deleted file mode 100644 index 12db0c47cc4e..000000000000 Binary files a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-76.png and /dev/null differ diff --git a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png deleted file mode 100644 index 163f1c7f0f18..000000000000 Binary files a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png and /dev/null differ diff --git a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png b/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png deleted file mode 100644 index 0bac1da399b5..000000000000 Binary files a/tests/linker/dont link/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png and /dev/null differ diff --git a/tests/linker/dont link/DontLinkRegressionTests.cs b/tests/linker/dont link/DontLinkRegressionTests.cs index 304017d248cf..dc7cbed346fb 100644 --- a/tests/linker/dont link/DontLinkRegressionTests.cs +++ b/tests/linker/dont link/DontLinkRegressionTests.cs @@ -30,7 +30,7 @@ public class DontLinkRegressionTests { public void Bug587_FullAotRuntime () { KeyValuePair valuePair = queued.FirstOrDefault (delegate { return true; }); - Assert.NotNull (valuePair); + Assert.That (valuePair, Is.Not.Null); // should not crash with System.ExecutionEngineException } @@ -39,7 +39,7 @@ public void RemovedAttributes () { // since we do not link the attributes will be available - used or not by the application var fullname = typeof (NSObject).Assembly.FullName; - Assert.NotNull (Type.GetType ("ObjCRuntime.ThreadSafeAttribute, " + fullname), "ThreadSafeAttribute"); + Assert.That (Type.GetType ("ObjCRuntime.ThreadSafeAttribute, " + fullname), Is.Not.Null, "ThreadSafeAttribute"); } #if !__MACOS__ @@ -65,7 +65,7 @@ public void DefaultEncoding () // https://bugzilla.xamarin.com/show_bug.cgi?id=29928 var de = System.Text.Encoding.Default; Assert.That (de.WebName, Is.EqualTo ("utf-8"), "Name"); - Assert.True (de.IsReadOnly, "IsReadOnly"); + Assert.That (de.IsReadOnly, Is.True, "IsReadOnly"); } #if __TVOS__ @@ -77,7 +77,7 @@ void AssertThrowsWrappedNotSupportedException (Action action, string message) } catch (TargetInvocationException tie) { var nse = tie.InnerException as TargetInvocationException; if (nse is not null) - Assert.Fail ("An exception was thrown, but {0} instead of NotSupportedException. " + message, tie.InnerException.GetType ().FullName); + Assert.Fail ($"An exception was thrown, but {nse.GetType ().FullName} instead of NotSupportedException. " + message); } } [Test] @@ -114,9 +114,9 @@ public void ProcessStart_NotSupported () foreach (var notsupported_property in notsupported_properties) { foreach (var property in all_properties.Where ((v) => v.Name == notsupported_property)) { if (property.GetGetMethod () is not null) - AssertThrowsWrappedNotSupportedException (() => property.GetGetMethod ().Invoke (instance, new object [] {}), notsupported_property + " (getter)"); + AssertThrowsWrappedNotSupportedException (() => property.GetGetMethod ()!.Invoke (instance, new object [] {}), notsupported_property + " (getter)"); if (property.GetSetMethod () is not null) - AssertThrowsWrappedNotSupportedException (() => property.GetSetMethod ().Invoke (instance, new object [] { null }), notsupported_property + " (setter)"); + AssertThrowsWrappedNotSupportedException (() => property.GetSetMethod ()!.Invoke (instance, new object? [] { null }), notsupported_property + " (setter)"); } } diff --git a/tests/linker/dont link/TableViewSourceTest.cs b/tests/linker/dont link/TableViewSourceTest.cs index 727df0752a74..a99bb6e8c8da 100644 --- a/tests/linker/dont link/TableViewSourceTest.cs +++ b/tests/linker/dont link/TableViewSourceTest.cs @@ -32,13 +32,13 @@ public void ValidateMembers () var methods = new List (); foreach (var mi in typeof (UITableViewDelegate).GetMethods (flags)) - methods.Add (mi.ToString ()); + methods.Add (mi.ToString ()!); foreach (var mi in typeof (UITableViewDataSource).GetMethods (flags)) - methods.Add (mi.ToString ()); + methods.Add (mi.ToString ()!); var tvsource = new List (); foreach (var mi in typeof (UITableViewSource).GetMethods (flags)) - tvsource.Add (mi.ToString ()); + tvsource.Add (mi.ToString ()!); methods.RemoveAll (delegate (string name) { diff --git a/tests/linker/dont link/dotnet/shared.csproj b/tests/linker/dont link/dotnet/shared.csproj index 3d9e367dfda9..965f3fffa37d 100644 --- a/tests/linker/dont link/dotnet/shared.csproj +++ b/tests/linker/dont link/dotnet/shared.csproj @@ -11,10 +11,6 @@ $(NoWarn);IL2057 - - - true - Nullable @@ -56,15 +52,7 @@ - - - - - - - - - + diff --git a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/Contents.json b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/Contents.json index 6be52c8f7640..0e65c18b41c3 100644 --- a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/Contents.json +++ b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/Contents.json @@ -1,221 +1,15 @@ { "images": [ { - "size": "29x29", - "scale": "1x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "2x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "3x", - "idiom": "iphone" - }, - { - "size": "40x40", - "scale": "2x", - "idiom": "iphone" - }, - { - "size": "40x40", - "scale": "3x", - "idiom": "iphone" - }, - { - "filename": "icon-app-57.png", - "size": "57x57", - "scale": "1x", - "idiom": "iphone" - }, - { - "filename": "icon-app-57@2x.png", - "size": "57x57", - "scale": "2x", - "idiom": "iphone" - }, - { - "filename": "icon-app-60@2x.png", - "size": "60x60", - "scale": "2x", - "idiom": "iphone" - }, - { - "filename": "icon-app-60@3x.png", - "size": "60x60", - "scale": "3x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "29x29", - "scale": "2x", - "idiom": "ipad" - }, - { - "size": "40x40", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "40x40", - "scale": "2x", - "idiom": "ipad" - }, - { - "size": "50x50", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "50x50", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-83.5@2x.png", - "size": "83.5x83.5", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-72.png", - "size": "72x72", - "scale": "1x", - "idiom": "ipad" - }, - { - "filename": "icon-app-72@2x.png", - "size": "72x72", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-76.png", - "size": "76x76", - "scale": "1x", - "idiom": "ipad" - }, - { - "filename": "icon-app-76@2x.png", - "size": "76x76", - "scale": "2x", - "idiom": "ipad" - }, - { - "role": "notificationCenter", - "size": "24x24", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "notificationCenter", - "size": "27.5x27.5", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "companionSettings", - "size": "29x29", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "companionSettings", - "size": "29x29", - "scale": "3x", - "idiom": "watch" - }, - { - "role": "appLauncher", - "size": "40x40", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "longLook", - "size": "44x44", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "quickLook", - "size": "86x86", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "quickLook", - "size": "98x98", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "size": "16x16", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "16x16", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "32x32", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "32x32", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "128x128", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "128x128", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "256x256", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "256x256", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "512x512", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "512x512", - "scale": "2x", - "idiom": "mac" + "filename": "icon-1024.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" } ], "info": { - "version": 1, - "author": "xcode" + "author": "xcode", + "version": 1 } -} \ No newline at end of file +} + diff --git a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/Icon-app-60@3x.png b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/Icon-app-60@3x.png deleted file mode 100644 index 45342a7513b6..000000000000 Binary files a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/Icon-app-60@3x.png and /dev/null differ diff --git a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-1024.png b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-1024.png new file mode 100644 index 000000000000..1e62561f25b7 Binary files /dev/null and b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-1024.png differ diff --git a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-57.png b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-57.png deleted file mode 100644 index ce1d9df94d4f..000000000000 Binary files a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-57.png and /dev/null differ diff --git a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png deleted file mode 100644 index d34d9c694d3f..000000000000 Binary files a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png and /dev/null differ diff --git a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png deleted file mode 100644 index 4409624b29d9..000000000000 Binary files a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png and /dev/null differ diff --git a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-72.png b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-72.png deleted file mode 100644 index 9a77ea277312..000000000000 Binary files a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-72.png and /dev/null differ diff --git a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png deleted file mode 100644 index 32f57d7d89da..000000000000 Binary files a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png and /dev/null differ diff --git a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-76.png b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-76.png deleted file mode 100644 index 12db0c47cc4e..000000000000 Binary files a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-76.png and /dev/null differ diff --git a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png deleted file mode 100644 index 163f1c7f0f18..000000000000 Binary files a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png and /dev/null differ diff --git a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png b/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png deleted file mode 100644 index 0bac1da399b5..000000000000 Binary files a/tests/linker/link all/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png and /dev/null differ diff --git a/tests/linker/link all/AttributeTest.cs b/tests/linker/link all/AttributeTest.cs index 03581f6e7d66..c34f11e25783 100644 --- a/tests/linker/link all/AttributeTest.cs +++ b/tests/linker/link all/AttributeTest.cs @@ -115,9 +115,9 @@ public void DebugAssemblyAttributes () result = true; } #if DEBUG - Assert.True (result, "DebuggableAttribute"); + Assert.That (result, Is.True, "DebuggableAttribute"); #else - Assert.False (result, "DebuggableAttribute"); + Assert.That (result, Is.False, "DebuggableAttribute"); #endif } @@ -135,7 +135,7 @@ public void DebugTypeAttributes () [Test] public void DebugConstructorAttributes () { - var ca = typeof (FullyDecorated).GetConstructor (Type.EmptyTypes).GetCustomAttributes (false); + var ca = typeof (FullyDecorated).GetConstructor (Type.EmptyTypes)!.GetCustomAttributes (false); #if DEBUG Assert.That (ca.Length, Is.EqualTo (2), "Debug attributes in debug mode"); #else @@ -152,14 +152,14 @@ public void DebugPropertyAttributes () c.Property = 1; bool result = false; - foreach (object ca in typeof (FullyDecorated).GetProperty ("Property").GetCustomAttributes (false)) { + foreach (object ca in typeof (FullyDecorated).GetProperty ("Property")!.GetCustomAttributes (false)) { if (ca is DebuggerBrowsableAttribute) result = true; } #if DEBUG - Assert.True (result, "DebuggerBrowsable"); + Assert.That (result, Is.True, "DebuggerBrowsable"); #else - Assert.False (result, "DebuggerBrowsable"); + Assert.That (result, Is.False, "DebuggerBrowsable"); #endif } @@ -167,15 +167,15 @@ public void DebugPropertyAttributes () public void DebuggerTypeProxy_24203 () { var d = new Dictionary () { { "key", 0 } }; - Assert.NotNull (d); // just to be 100% sure it won't be linked away (with the attribute we'll be looking for) - var proxy = Type.GetType ("System.Collections.Generic.IDictionaryDebugView`2, " + mscorlib); + Assert.That (d, Is.Not.Null); // just to be 100% sure it won't be linked away (with the attribute we'll be looking for) + var proxy = Type.GetType ("System.Collections.Generic.IDictionaryDebugView`2, " + mscorlib)!; #if DEBUG - Assert.NotNull (proxy, "proxy"); + Assert.That (proxy, Is.Not.Null, "proxy"); // having the type is nice, but it must not be empty to be useful Assert.That (proxy.GetConstructors ().Length, Is.GreaterThan (0), "constructors"); Assert.That (proxy.GetProperties ().Length, Is.GreaterThan (0), "properties"); #else - Assert.Null (proxy, "proxy"); + Assert.That (proxy, Is.Null, "proxy"); #endif } @@ -185,19 +185,19 @@ public void CustomAttributesWithTypes () var assembly = GetType ().Assembly; var ta = assembly.GetCustomAttributes (); Assert.That (ta.Count (), Is.EqualTo (3), "Type[]"); - Assert.NotNull (Type.GetType ("LinkAll.Attributes.CustomTypeA"), "CustomTypeA"); - Assert.NotNull (Type.GetType ("LinkAll.Attributes.CustomTypeAA"), "CustomTypeAA"); - Assert.NotNull (Type.GetType ("LinkAll.Attributes.CustomTypeAAA"), "CustomTypeAAA"); - //Assert.NotNull (Type.GetType ("LinkAll.Attributes.CustomTypeAAAA"), "CustomTypeAAAA"); + Assert.That (Type.GetType ("LinkAll.Attributes.CustomTypeA"), Is.Not.Null, "CustomTypeA"); + Assert.That (Type.GetType ("LinkAll.Attributes.CustomTypeAA"), Is.Not.Null, "CustomTypeAA"); + Assert.That (Type.GetType ("LinkAll.Attributes.CustomTypeAAA"), Is.Not.Null, "CustomTypeAAA"); + //Assert.That (Type.GetType ("LinkAll.Attributes.CustomTypeAAAA"), Is.Not.Null, "CustomTypeAAAA"); var t = assembly.GetCustomAttributes (); Assert.That (t.Count (), Is.EqualTo (2), "Type"); - Assert.NotNull (Type.GetType ("LinkAll.Attributes.CustomType"), "CustomType"); - Assert.NotNull (Type.GetType ("LinkAll.Attributes.CustomTypeG"), "CustomTypeG"); + Assert.That (Type.GetType ("LinkAll.Attributes.CustomType"), Is.Not.Null, "CustomType"); + Assert.That (Type.GetType ("LinkAll.Attributes.CustomTypeG"), Is.Not.Null, "CustomTypeG"); //var to = assembly.GetCustomAttributes (); //Assert.That (to.Count (), Is.EqualTo (1), "Object"); - //Assert.NotNull (Type.GetType ("LinkAll.Attributes.CustomTypeO"), "CustomTypeO"); + //Assert.That (Type.GetType ("LinkAll.Attributes.CustomTypeO"), Is.Not.Null, "CustomTypeO"); } } } diff --git a/tests/linker/link all/ClassLayoutTest.cs b/tests/linker/link all/ClassLayoutTest.cs index 0d5a200c8f9d..1c626ed35d1a 100644 --- a/tests/linker/link all/ClassLayoutTest.cs +++ b/tests/linker/link all/ClassLayoutTest.cs @@ -54,9 +54,9 @@ public void DefaultLayoutClass () // auto Assert.That (fields.Length, Is.EqualTo (1), "Length"); Assert.That (fields [0].Name, Is.EqualTo ("used"), "Name"); - Assert.True (t.IsAutoLayout, "IsAutoLayout"); - Assert.False (t.IsExplicitLayout, "IsExplicitLayout"); - Assert.False (t.IsLayoutSequential, "IsLayoutSequential"); + Assert.That (t.IsAutoLayout, Is.True, "IsAutoLayout"); + Assert.That (t.IsExplicitLayout, Is.False, "IsExplicitLayout"); + Assert.That (t.IsLayoutSequential, Is.False, "IsLayoutSequential"); } [Test] @@ -70,9 +70,9 @@ public void AutoLayoutClass () Assert.That (fields.Length, Is.EqualTo (1), "Length"); Assert.That (fields [0].Name, Is.EqualTo ("used"), "Name"); - Assert.True (t.IsAutoLayout, "IsAutoLayout"); - Assert.False (t.IsExplicitLayout, "IsExplicitLayout"); - Assert.False (t.IsLayoutSequential, "IsLayoutSequential"); + Assert.That (t.IsAutoLayout, Is.True, "IsAutoLayout"); + Assert.That (t.IsExplicitLayout, Is.False, "IsExplicitLayout"); + Assert.That (t.IsLayoutSequential, Is.False, "IsLayoutSequential"); } [Test] @@ -85,9 +85,9 @@ public void LayoutSequential () var fields = t.GetFields (); Assert.That (fields.Length, Is.EqualTo (2), "Length"); - Assert.False (t.IsAutoLayout, "IsAutoLayout"); - Assert.False (t.IsExplicitLayout, "IsExplicitLayout"); - Assert.True (t.IsLayoutSequential, "IsLayoutSequential"); + Assert.That (t.IsAutoLayout, Is.False, "IsAutoLayout"); + Assert.That (t.IsExplicitLayout, Is.False, "IsExplicitLayout"); + Assert.That (t.IsLayoutSequential, Is.True, "IsLayoutSequential"); } [Test] @@ -100,9 +100,9 @@ public void ExplicitLayout () var fields = t.GetFields (); Assert.That (fields.Length, Is.EqualTo (3), "Length"); - Assert.False (t.IsAutoLayout, "IsAutoLayout"); - Assert.True (t.IsExplicitLayout, "IsExplicitLayout"); - Assert.False (t.IsLayoutSequential, "IsLayoutSequential"); + Assert.That (t.IsAutoLayout, Is.False, "IsAutoLayout"); + Assert.That (t.IsExplicitLayout, Is.True, "IsExplicitLayout"); + Assert.That (t.IsLayoutSequential, Is.False, "IsLayoutSequential"); } } } diff --git a/tests/linker/link all/DataContractTest.cs b/tests/linker/link all/DataContractTest.cs index 118e3303c900..4c9daae79b30 100644 --- a/tests/linker/link all/DataContractTest.cs +++ b/tests/linker/link all/DataContractTest.cs @@ -36,7 +36,7 @@ public static T FromXml (string xml) { using (var r = XmlReader.Create (new StringReader (xml))) { var s = new DataContractSerializer (typeof (T)); - return (T) s.ReadObject (r); + return (T) s.ReadObject (r)!; } } @@ -67,7 +67,7 @@ public void Flags () var t1 = new TestClass (SomeTypes.Audio | SomeTypes.Image); var st = ToXml (t1); var t2 = FromXml (st); - Assert.AreEqual (t2.Types, t1.Types); + Assert.That (t1.Types, Is.EqualTo (t2.Types)); } } } diff --git a/tests/linker/link all/InterfacesTest.cs b/tests/linker/link all/InterfacesTest.cs index b4705258fbad..326eb3d741a6 100644 --- a/tests/linker/link all/InterfacesTest.cs +++ b/tests/linker/link all/InterfacesTest.cs @@ -30,7 +30,7 @@ class UTF8Marshaler : ICustomMarshaler { public object MarshalNativeToManaged (IntPtr pNativeData) { - return null; + return null!; } public IntPtr MarshalManagedToNative (object managedObject) @@ -74,23 +74,23 @@ public void Bug10866 () F (new A ()); // Foo and Bar methods are both used on A and must be present - Assert.NotNull (type_a.GetMethod ("Foo", BindingFlags.Instance | BindingFlags.Public), "A::Foo"); - Assert.NotNull (type_a.GetMethod ("Bar", BindingFlags.Instance | BindingFlags.Public), "A::Bar"); + Assert.That (type_a.GetMethod ("Foo", BindingFlags.Instance | BindingFlags.Public), Is.Not.Null, "A::Foo"); + Assert.That (type_a.GetMethod ("Bar", BindingFlags.Instance | BindingFlags.Public), Is.Not.Null, "A::Bar"); // I::Foo is never used and can be removed - Assert.Null (type_i.GetMethod ("Foo", BindingFlags.Instance | BindingFlags.Public), "I::Foo"); + Assert.That (type_i.GetMethod ("Foo", BindingFlags.Instance | BindingFlags.Public), Is.Null, "I::Foo"); // I::Bar is used in F so everyone implementing I needs Bar - Assert.NotNull (type_i.GetMethod ("Bar", BindingFlags.Instance | BindingFlags.Public), "I::Bar"); + Assert.That (type_i.GetMethod ("Bar", BindingFlags.Instance | BindingFlags.Public), Is.Not.Null, "I::Bar"); // Foo and Bar are never used on B - so they can be removed - Assert.Null (type_b.GetMethod ("Foo", BindingFlags.Instance | BindingFlags.Public), "B::Foo"); + Assert.That (type_b.GetMethod ("Foo", BindingFlags.Instance | BindingFlags.Public), Is.Null, "B::Foo"); } [Test] public void Issue9566 () { var ifaces = (I []) (object) new B [0]; - Assert.IsNotNull (ifaces, "Array cast"); + Assert.That (ifaces, Is.Not.Null, "Array cast"); } [DllImport ("/usr/lib/system/libsystem_dnssd.dylib")] diff --git a/tests/linker/link all/InternalsTest.cs b/tests/linker/link all/InternalsTest.cs index d0e96ef69b66..480681065b7f 100644 --- a/tests/linker/link all/InternalsTest.cs +++ b/tests/linker/link all/InternalsTest.cs @@ -22,7 +22,7 @@ public class InternalsTest { [Test] public void RegionInfo_CountryCode () { - Assert.IsNotNull (xamarin_get_locale_country_code (), "xamarin_get_locale_country_code"); + Assert.That (xamarin_get_locale_country_code (), Is.Not.Null, "xamarin_get_locale_country_code"); } [DllImport ("__Internal", CharSet = CharSet.Unicode)] @@ -46,15 +46,15 @@ public void TimeZone_Names () Assert.That (count, Is.GreaterThan (400), "count"); for (int i = 0, offset = 0; i < count; i++, offset += IntPtr.Size) { IntPtr p = Marshal.ReadIntPtr (array, offset); - string s = Marshal.PtrToStringAnsi (p); - Assert.NotNull (s, i.ToString ()); + string s = Marshal.PtrToStringAnsi (p)!; + Assert.That (s, Is.Not.Null, i.ToString ()); Marshal.FreeHGlobal (p); } Marshal.FreeHGlobal (array); } [DllImport ("__Internal")] - extern static IntPtr xamarin_timezone_get_data (string name, ref uint size); + extern static IntPtr xamarin_timezone_get_data (string? name, ref uint size); [Test] public void TimeZone_Data () diff --git a/tests/linker/link all/LinkAllMacTest.cs b/tests/linker/link all/LinkAllMacTest.cs index 181df123d073..fad1a76cf15f 100644 --- a/tests/linker/link all/LinkAllMacTest.cs +++ b/tests/linker/link all/LinkAllMacTest.cs @@ -2,6 +2,7 @@ using System.IO; using System.Runtime.CompilerServices; using System.Threading; +using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; @@ -18,14 +19,14 @@ public void EnsureUIThreadException () NSApplication.EnsureUIThread (); ThreadPool.QueueUserWorkItem ((v) => Tester.Test ()); - Assert.IsTrue (Tester.mre.WaitOne (TimeSpan.FromSeconds (10)), "Successful wait"); + Assert.That (Tester.mre.WaitOne (TimeSpan.FromSeconds (10)), Is.True, "Successful wait"); // The UI thread check only happens for debug builds, on release build it's linked away. #if DEBUG var expected_ex_thrown = true; #else var expected_ex_thrown = false; #endif - Assert.AreEqual (expected_ex_thrown, Tester.exception_thrown, "Success"); + Assert.That (Tester.exception_thrown, Is.EqualTo (expected_ex_thrown), "Success"); } @@ -58,8 +59,8 @@ public void XmlSerialization () using (var sr = new StringReader (xml)) using (var xr = new XmlTextReader (sr)) { var xs = new XmlSerializer (typeof (SerializeMe)); - SerializeMe item = xs.Deserialize (xr) as SerializeMe; - Assert.AreEqual (2, item.SetMe, "SetMe"); + var item = xs.Deserialize (xr) as SerializeMe; + Assert.That (item!.SetMe, Is.EqualTo (2), "SetMe"); } } @@ -73,6 +74,75 @@ public SerializeMe () SetMe = 1; } } + + // https://github.com/xamarin/bugzilla-archives/blob/main/16/16505/bug.html + [Test] + public void PrintPreview_NSGraphicsContextCurrentContext () + { + TestRuntime.AssertXcodeVersion (26, 0); + + // Verify that accessing NSGraphicsContext.CurrentContext during print preview + // doesn't crash due to the linker trimming NSPrintPreviewGraphicsContext. + var printableView = new PrintableView (new CoreGraphics.CGRect (0, 0, 100, 100)); + + var printInfo = (NSPrintInfo) NSPrintInfo.SharedPrintInfo.Copy (); + printInfo.JobDisposition = "NSPrintPreviewJob"; + + var printOp = NSPrintOperation.FromView (printableView, printInfo); + printOp.ShowsPrintPanel = true; // this is required to trigger the bug + printOp.ShowsProgressPanel = true; + + var closedPreview = false; + var closeAction = new Action (() => { + if (closedPreview) + return; + NSApplication.SharedApplication.AbortModal (); + closedPreview = true; + }); + + printableView.TaskCompletionSource.Task.ContinueWith (task => { + closeAction (); + }, TaskScheduler.FromCurrentSynchronizationContext ()); + + // Auto-close after 3 seconds in case something goes wrong + var timer = NSTimer.CreateScheduledTimer (3.0, (t) => closeAction ()); + NSRunLoop.Current.AddTimer (timer, NSRunLoopMode.ModalPanel); + + printOp.RunOperation (); + + Assert.That (printableView.TaskCompletionSource.Task.IsCompletedSuccessfully, Is.True, "DrawPageBorder was called successfully"); + var context = printableView.TaskCompletionSource.Task.Result; + Assert.That (context, Is.Not.Null, "NSGraphicsContext.CurrentContext was not null during print preview"); + } + } + + class PrintableView : NSView { + public PrintableView (CoreGraphics.CGRect frame) : base (frame) { } + + public TaskCompletionSource TaskCompletionSource = new (); + + public override void DrawPageBorder (CoreGraphics.CGSize borderSize) + { + try { + var context = NSGraphicsContext.CurrentContext; + base.DrawPageBorder (borderSize); + TaskCompletionSource.TrySetResult (context); + } catch (Exception e) { + Console.WriteLine ($"Unexpected exception occurred: {e}"); + TaskCompletionSource.TrySetException (e); + } + } + + public override bool KnowsPageRange (ref Foundation.NSRange range) + { + range = new Foundation.NSRange (1, 1); + return true; + } + + public override CoreGraphics.CGRect RectForPage (nint pageNumber) + { + return Bounds; + } } } #endif // __MACOS__ diff --git a/tests/linker/link all/LinkAllTest.cs b/tests/linker/link all/LinkAllTest.cs index fb48b13833a3..8a21b29c7d13 100644 --- a/tests/linker/link all/LinkAllTest.cs +++ b/tests/linker/link all/LinkAllTest.cs @@ -80,7 +80,7 @@ public class LinkAllRegressionTest { class TypeAttribute : Attribute { - public TypeAttribute (Type type) { } + public TypeAttribute (Type? type) { } } [Type (null)] @@ -98,10 +98,10 @@ public void GetterOnly () NotPreserved np = new NotPreserved (); Assert.That (np.Two, Is.EqualTo (0), "Two==0"); - PropertyInfo pi = not_preserved_type.GetProperty ("Two"); + PropertyInfo pi = not_preserved_type.GetProperty ("Two")!; // check the *unused* setter absence from the application - Assert.NotNull (pi.GetGetMethod (), "getter"); - Assert.Null (pi.GetSetMethod (), "setter"); + Assert.That (pi.GetGetMethod (), Is.Not.Null, "getter"); + Assert.That (pi.GetSetMethod (), Is.Null, "setter"); } [Test] @@ -111,10 +111,10 @@ public void SetterOnly () NotPreserved np = new NotPreserved (); np.One = 1; - PropertyInfo pi = not_preserved_type.GetProperty ("One"); + PropertyInfo pi = not_preserved_type.GetProperty ("One")!; // check the *unused* setter absence from the application - Assert.Null (pi.GetGetMethod (), "getter"); - Assert.NotNull (pi.GetSetMethod (), "setter"); + Assert.That (pi.GetGetMethod (), Is.Null, "getter"); + Assert.That (pi.GetSetMethod (), Is.Not.Null, "setter"); } [Test] @@ -122,7 +122,7 @@ public void MEF_3862 () { // note: avoiding using "typeof(DefaultValueAttribute)" in the code // so the linker does not keep it just because of it - PropertyInfo pi = not_preserved_type.GetProperty ("Two"); + PropertyInfo pi = not_preserved_type.GetProperty ("Two")!; object [] attrs = pi.GetCustomAttributes (false); bool default_value = false; foreach (var ca in attrs) { @@ -131,14 +131,16 @@ public void MEF_3862 () break; } } - Assert.True (default_value, "DefaultValue"); + Assert.That (default_value, Is.True, "DefaultValue"); } static void Check (string calendarName, bool present) { var type = Type.GetType ("System.Globalization." + calendarName); - bool success = present == (type is not null); - Assert.AreEqual (present, type is not null, calendarName); + if (present) + Assert.That (type, Is.Not.Null, calendarName); + else + Assert.That (type, Is.Null, calendarName); } [Test] @@ -176,8 +178,8 @@ public void DetectPlatform () { // for (future) nunit[lite] platform detection - if this test fails then platform detection won't work var typename = NamespacePrefix + "UIKit.UIApplicationDelegate, " + AssemblyName; - Assert.NotNull (Helper.GetType (typename), typename); - Assert.Null (Helper.GetType ("Mono.Runtime"), "Mono.Runtime"); + Assert.That (Helper.GetType (typename), Is.Not.Null, typename); + Assert.That (Helper.GetType ("Mono.Runtime"), Is.Null, "Mono.Runtime"); } #endif // !__MACOS__ @@ -194,30 +196,30 @@ public void RemovedAttributes () string suffix = AssemblyName; // since we're linking the attributes will NOT be available - even if they are used - Assert.Null (Helper.GetType (prefix + "ObjCRuntime.IntroducedAttribute, " + suffix), "IntroducedAttribute"); - Assert.Null (Helper.GetType (prefix + "ObjCRuntime.DeprecatedAttribute, " + suffix), "DeprecatedAttribute"); - Assert.Null (Helper.GetType (prefix + "ObjCRuntime.ObsoletedAttribute, " + suffix), "ObsoletedAttribute"); - Assert.Null (Helper.GetType (prefix + "ObjCRuntime.UnavailableAttribute, " + suffix), "UnavailableAttribute"); - Assert.Null (Helper.GetType (prefix + "ObjCRuntime.ThreadSafeAttribute, " + suffix), "ThreadSafeAttribute"); - Assert.Null (Helper.GetType ("System.Runtime.Versioning.SupportedOSPlatformAttribute, " + suffix), "SupportedOSPlatformAttribute"); - Assert.Null (Helper.GetType ("System.Runtime.Versioning.UnsupportedOSPlatformAttribute, " + suffix), "UnsupportedOSPlatformAttribute"); + Assert.That (Helper.GetType (prefix + "ObjCRuntime.IntroducedAttribute, " + suffix), Is.Null, "IntroducedAttribute"); + Assert.That (Helper.GetType (prefix + "ObjCRuntime.DeprecatedAttribute, " + suffix), Is.Null, "DeprecatedAttribute"); + Assert.That (Helper.GetType (prefix + "ObjCRuntime.ObsoletedAttribute, " + suffix), Is.Null, "ObsoletedAttribute"); + Assert.That (Helper.GetType (prefix + "ObjCRuntime.UnavailableAttribute, " + suffix), Is.Null, "UnavailableAttribute"); + Assert.That (Helper.GetType (prefix + "ObjCRuntime.ThreadSafeAttribute, " + suffix), Is.Null, "ThreadSafeAttribute"); + Assert.That (Helper.GetType ("System.Runtime.Versioning.SupportedOSPlatformAttribute, " + suffix), Is.Null, "SupportedOSPlatformAttribute"); + Assert.That (Helper.GetType ("System.Runtime.Versioning.UnsupportedOSPlatformAttribute, " + suffix), Is.Null, "UnsupportedOSPlatformAttribute"); } [Test] public void Assembly_Load () { Assembly mscorlib = Assembly.Load ("System.Private.CoreLib.dll"); - Assert.NotNull (mscorlib, "System.Private.CoreLib.dll"); + Assert.That (mscorlib, Is.Not.Null, "System.Private.CoreLib.dll"); } string FindAssemblyPath () { var filename = Path.GetFileName (GetType ().Assembly.Location); - var bundlePath = NSBundle.MainBundle.BundlePath; + var bundlePath = NSBundle.MainBundle.BundlePath!; var isExtension = bundlePath.EndsWith (".appex", StringComparison.Ordinal); var mainBundlePath = bundlePath; if (isExtension) - mainBundlePath = Path.GetDirectoryName (Path.GetDirectoryName (bundlePath)); + mainBundlePath = Path.GetDirectoryName (Path.GetDirectoryName (bundlePath))!; foreach (var filepath in Directory.EnumerateFiles (mainBundlePath, filename, SearchOption.AllDirectories)) { var fname = Path.GetFileName (filepath); if (filepath.EndsWith ($"{fname}.framework/{fname}", StringComparison.Ordinal)) { @@ -238,14 +240,14 @@ string FindAssemblyPath () public void Assembly_LoadFile () { string filename = FindAssemblyPath (); - Assert.NotNull (Assembly.LoadFile (Path.GetFullPath (filename)), "1"); + Assert.That (Assembly.LoadFile (Path.GetFullPath (filename)), Is.Not.Null, "1"); } [Test] public void Assembly_LoadFrom () { string filename = FindAssemblyPath (); - Assert.NotNull (Assembly.LoadFrom (filename), "1"); + Assert.That (Assembly.LoadFrom (filename), Is.Not.Null, "1"); } [Test] @@ -262,20 +264,20 @@ public void Assembly_ReflectionOnlyLoadFrom () [Test] public void Pasteboard_ImagesTest () { - string file = Path.Combine (NSBundle.MainBundle.ResourcePath, "basn3p08.png"); + string file = Path.Combine (NSBundle.MainBundle.ResourcePath!, "basn3p08.png"); using (var dp = new CGDataProvider (file)) { - using (var cgimg = CGImage.FromPNG (dp, null, false, CGColorRenderingIntent.Default)) { + using (var cgimg = CGImage.FromPNG (dp, null, false, CGColorRenderingIntent.Default)!) { using (var img = new UIImage (cgimg)) { UIPasteboard.General.Images = new UIImage [] { img }; if (TestRuntime.CheckXcodeVersion (8, 0)) - Assert.True (UIPasteboard.General.HasImages, "HasImages"); + Assert.That (UIPasteboard.General.HasImages, Is.True, "HasImages"); - Assert.AreEqual (1, UIPasteboard.General.Images.Length, "a - length"); + Assert.That (UIPasteboard.General.Images.Length, Is.EqualTo (1), "a - length"); UIPasteboard.General.Images = new UIImage [] { img, img }; - Assert.AreEqual (2, UIPasteboard.General.Images.Length, "b - length"); - Assert.IsNotNull (UIPasteboard.General.Images [0], "b - nonnull[0]"); - Assert.IsNotNull (UIPasteboard.General.Images [1], "b - nonnull[0]"); + Assert.That (UIPasteboard.General.Images.Length, Is.EqualTo (2), "b - length"); + Assert.That (UIPasteboard.General.Images [0], Is.Not.Null, "b - nonnull[0]"); + Assert.That (UIPasteboard.General.Images [1], Is.Not.Null, "b - nonnull[1]"); } } } @@ -285,7 +287,7 @@ public void Pasteboard_ImagesTest () [Test] public void UltimateBindings () { - Assert.IsNotNull (Bindings.Test.UltimateMachine.SharedInstance, "SharedInstance"); + Assert.That (Bindings.Test.UltimateMachine.SharedInstance, Is.Not.Null, "SharedInstance"); } #region bug 14456 @@ -298,7 +300,7 @@ public enum TestEnum { [Preserve (AllMembers = true)] public class TestEnumTypeConverter : System.ComponentModel.TypeConverter { - public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + public override object ConvertTo (ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { return "hello"; } @@ -371,14 +373,14 @@ public void NestedNSObject () { // Parent type is not used - but it's not linked out var p = Helper.GetType ("LinkAll.Parent"); - Assert.NotNull (p, "Parent"); + Assert.That (p, Is.Not.Null, "Parent"); // because a nested type is a subclass of NSObject (and not part of monotouch.dll) - var n = p.GetNestedType ("Derived"); - Assert.NotNull (n, "Derived"); + var n = p.GetNestedType ("Derived")!; + Assert.That (n, Is.Not.Null, "Derived"); // however other stuff in Parent, like unused methods, will be removed - Assert.Null (p.GetMethod ("UnusedMethod"), "unused method"); + Assert.That (p.GetMethod ("UnusedMethod"), Is.Null, "unused method"); // while exported stuff will be present - Assert.NotNull (n.GetMethod ("Foo"), "unused Export method"); + Assert.That (n.GetMethod ("Foo"), Is.Not.Null, "unused Export method"); } [Test] @@ -386,10 +388,10 @@ public void Bug20363 () { // testing compile time error CancelEventArgs cea = new CancelEventArgs (); - Assert.NotNull (cea, "CancelEventArgs"); + Assert.That (cea, Is.Not.Null, "CancelEventArgs"); } - string GetField (object o, string s) + string? GetField (object o, string s) { var type = o.GetType (); var f1 = type.GetField (s, BindingFlags.Instance | BindingFlags.NonPublic); @@ -409,7 +411,7 @@ string FromPattern (string pattern, object o) s = GetField (o, ""); if (s is not null) return s; - return GetField (o, ""); + return GetField (o, "")!; } [Test] @@ -420,30 +422,30 @@ public void AnonymousType () id = 1234, contentType = "xml" }); - Assert.Null (result, result); + Assert.That (result, Is.Null, result); } [Test] public void Events () { using (var pr = new SKProductsRequest ()) { - Assert.Null (pr.WeakDelegate, "none"); + Assert.That (pr.WeakDelegate, Is.Null, "none"); // event on SKProductsRequest itself - pr.ReceivedResponse += (object sender, SKProductsRequestResponseEventArgs e) => { }; + pr.ReceivedResponse += (object? sender, SKProductsRequestResponseEventArgs e) => { }; - var t = pr.WeakDelegate.GetType (); + var t = pr.WeakDelegate!.GetType (); Assert.That (t.Name, Is.EqualTo ("_SKProductsRequestDelegate"), "delegate"); - var fi = t.GetField ("receivedResponse", BindingFlags.NonPublic | BindingFlags.Instance); - Assert.NotNull (fi, "receivedResponse"); + var fi = t.GetField ("receivedResponse", BindingFlags.NonPublic | BindingFlags.Instance)!; + Assert.That (fi, Is.Not.Null, "receivedResponse"); var value = fi.GetValue (pr.WeakDelegate); - Assert.NotNull (value, "value"); + Assert.That (value, Is.Not.Null, "value"); // and on the SKRequest defined one - pr.RequestFailed += (object sender, SKRequestErrorEventArgs e) => { }; + pr.RequestFailed += (object? sender, SKRequestErrorEventArgs e) => { }; // and the existing (initial field) is still set fi = t.GetField ("receivedResponse", BindingFlags.NonPublic | BindingFlags.Instance); - Assert.NotNull (fi, "receivedResponse/SKRequest"); + Assert.That (fi, Is.Not.Null, "receivedResponse/SKRequest"); } } @@ -453,24 +455,15 @@ public void Aot_27116 () var nix = (from nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces () where nic.Id.StartsWith ("en") || nic.Id.StartsWith ("pdp_ip") select nic); - Assert.NotNull (nix); + Assert.That (nix, Is.Not.Null); } [Test] public void AppleTls () { // make test work for classic (monotouch) and unified (iOS, tvOS) - var fqn = typeof (NSObject).AssemblyQualifiedName.Replace ("Foundation.NSObject", "Security.Tls.AppleTlsProvider"); - Assert.Null (Helper.GetType (fqn), "Should NOT be included (no SslStream or Socket support)"); - } - - [Test] - // https://bugzilla.xamarin.com/show_bug.cgi?id=59247 - public void WebKit_NSProxy () - { - // this test works only because "Link all" does not use WebKit - var fqn = typeof (NSObject).AssemblyQualifiedName.Replace ("Foundation.NSObject", "Foundation.NSProxy"); - Assert.Null (Helper.GetType (fqn), fqn); + var fqn = typeof (NSObject).AssemblyQualifiedName!.Replace ("Foundation.NSObject", "Security.Tls.AppleTlsProvider"); + Assert.That (Helper.GetType (fqn), Is.Null, "Should NOT be included (no SslStream or Socket support)"); } static Type type_Task = typeof (Task); @@ -482,24 +475,24 @@ public void Bug59015 () CheckAsyncTaskMethodBuilder (typeof (AsyncTaskMethodBuilder)); var snfwc = type_Task.GetMethod ("NotifyDebuggerOfWaitCompletion", BindingFlags.Instance | BindingFlags.NonPublic); #if DEBUG - Assert.NotNull (snfwc, "Task.NotifyDebuggerOfWaitCompletion"); + Assert.That (snfwc, Is.Not.Null, "Task.NotifyDebuggerOfWaitCompletion"); #else // something keeps it from being removed - // Assert.Null (snfwc, "Task.NotifyDebuggerOfWaitCompletion"); + // Assert.That (snfwc, Is.Null, "Task.NotifyDebuggerOfWaitCompletion"); #endif } void CheckAsyncTaskMethodBuilder (Type atmb) { - Assert.NotNull (atmb, "AsyncTaskMethodBuilder"); + Assert.That (atmb, Is.Not.Null, "AsyncTaskMethodBuilder"); var snfwc = atmb.GetMethod ("SetNotificationForWaitCompletion", BindingFlags.Instance | BindingFlags.NonPublic); var oifd = atmb.GetProperty ("ObjectIdForDebugger", BindingFlags.Instance | BindingFlags.NonPublic); #if DEBUG - Assert.NotNull (snfwc, atmb.FullName + ".SetNotificationForWaitCompletion"); - Assert.NotNull (oifd, atmb.FullName + ".ObjectIdForDebugger"); + Assert.That (snfwc, Is.Not.Null, atmb.FullName + ".SetNotificationForWaitCompletion"); + Assert.That (oifd, Is.Not.Null, atmb.FullName + ".ObjectIdForDebugger"); #else - Assert.Null (snfwc, atmb.FullName + ".SetNotificationForWaitCompletion"); - Assert.Null (oifd, atmb.FullName + ".ObjectIdForDebugger"); + Assert.That (snfwc, Is.Null, atmb.FullName + ".SetNotificationForWaitCompletion"); + Assert.That (oifd, Is.Null, atmb.FullName + ".ObjectIdForDebugger"); #endif } @@ -509,7 +502,7 @@ public void LinkedAwayGenericTypeAsOptionalMemberInProtocol () { // https://github.com/dotnet/macios/issues/3523 // This test will fail at build time if it regresses (usually these types of build tests go into monotouch-test, but monotouch-test uses NSSet elsewhere, which this test requires to be linked away). - Assert.IsNull (typeof (NSObject).Assembly.GetType (NamespacePrefix + "Foundation.NSSet`1"), "NSSet must be linked away, otherwise this test is useless"); + Assert.That (typeof (NSObject).Assembly.GetType (NamespacePrefix + "Foundation.NSSet`1"), Is.Null, "NSSet must be linked away, otherwise this test is useless"); } [Protocol (Name = "ProtocolWithGenericsInOptionalMember", WrapperType = typeof (ProtocolWithGenericsInOptionalMemberWrapper))] @@ -546,11 +539,11 @@ public void NoFatCorlib () public void CGPdfPage () { TestRuntime.AssertXcodeVersion (9, 0); - var pdfPath = NSBundle.MainBundle.PathForResource ("Tamarin", "pdf"); + var pdfPath = NSBundle.MainBundle.PathForResource ("Tamarin", "pdf")!; using var view = new PdfView (); - view.Document = new PdfDocument (NSUrl.FromFilename (pdfPath)); - using var page = view.CurrentPage; - Assert.IsNotNull (page.Page, "Page"); + view.Document = new PdfDocument (NSUrl.FromFilename (pdfPath)!); + using var page = view.CurrentPage!; + Assert.That (page.Page, Is.Not.Null, "Page"); } #endif } diff --git a/tests/linker/link all/LinqExpressionTest.cs b/tests/linker/link all/LinqExpressionTest.cs index dbee07a1082b..0607cba0d7a7 100644 --- a/tests/linker/link all/LinqExpressionTest.cs +++ b/tests/linker/link all/LinqExpressionTest.cs @@ -15,9 +15,9 @@ public class LinqExpressionTest { [Test] public void Expression_T_Ctor () { - var ctor = typeof (LinqExpressionTest).GetConstructor (Type.EmptyTypes); + var ctor = typeof (LinqExpressionTest).GetConstructor (Type.EmptyTypes)!; var expr = Expression.New (ctor, new Expression [0]); - Assert.NotNull (Expression.Lambda (typeof (Bug14863Delegate), expr, null), "Lambda"); + Assert.That (Expression.Lambda (typeof (Bug14863Delegate), expr, null), Is.Not.Null, "Lambda"); // note: reflection is used to create an instance of Expression using an internal ctor // it can be indirectly "preserved" by other code (in Expression) but it can fail in other cases // ref: https://bugzilla.xamarin.com/show_bug.cgi?id=14863 diff --git a/tests/linker/link all/PreserveTest.cs b/tests/linker/link all/PreserveTest.cs index 9792f8ce5e73..cd019ddd9592 100644 --- a/tests/linker/link all/PreserveTest.cs +++ b/tests/linker/link all/PreserveTest.cs @@ -24,20 +24,20 @@ namespace LinkAll.Attributes { // type and members preserved by assembly-level attribute above class TypeWithMembers { - public string Present { get; set; } + public string Present { get; set; } = ""; } // type (only, not members) preserved by assembly-level attribute above class TypeWithoutMembers { - public string Absent { get; set; } + public string Absent { get; set; } = ""; } class MemberWithCustomAttribute { // since [Obfuscation] was manually preserved then we'll preserve everything that's decorated with the attribute [Obfuscation] - public string Custom { get; set; } + public string Custom { get; set; } = ""; } [TestFixture] @@ -56,20 +56,20 @@ public class PreserveTest { [Test] public void PreserveTypeWithMembers () { - var t = Type.GetType ("LinkAll.Attributes.TypeWithMembers" + WorkAroundLinkerHeuristics); + var t = Type.GetType ("LinkAll.Attributes.TypeWithMembers" + WorkAroundLinkerHeuristics)!; // both type and members are preserved - Assert.NotNull (t, "type"); - Assert.NotNull (t.GetProperty ("Present"), "members"); + Assert.That (t, Is.Not.Null, "type"); + Assert.That (t.GetProperty ("Present"), Is.Not.Null, "members"); } [Test] public void PreserveTypeWithoutMembers () { - var t = Type.GetType ("LinkAll.Attributes.TypeWithoutMembers" + WorkAroundLinkerHeuristics); + var t = Type.GetType ("LinkAll.Attributes.TypeWithoutMembers" + WorkAroundLinkerHeuristics)!; // type is preserved - Assert.NotNull (t, "type"); + Assert.That (t, Is.Not.Null, "type"); // but we did not ask the linker to preserve it's members - Assert.Null (t.GetProperty ("Absent"), "members"); + Assert.That (t.GetProperty ("Absent"), Is.Null, "members"); } [Test] @@ -77,8 +77,8 @@ public void Runtime_RegisterEntryAssembly () { TestRuntime.AssertSimulator ("https://github.com/dotnet/macios/issues/10457"); - var klass = Type.GetType ("ObjCRuntime.Runtime, " + AssemblyName); - Assert.NotNull (klass, "Runtime"); + var klass = Type.GetType ("ObjCRuntime.Runtime, " + AssemblyName)!; + Assert.That (klass, Is.Not.Null, "Runtime"); // RegisterEntryAssembly is only needed for the simulator (not on devices) so it's only preserved for sim builds var method = klass.GetMethod ("RegisterEntryAssembly", BindingFlags.NonPublic | BindingFlags.Static, null, new [] { typeof (Assembly) }, null); #if __MACOS__ @@ -94,90 +94,90 @@ public void MonoTouchException_Unconditional () { const string klassName = "ObjCRuntime.ObjCException"; var klass = Type.GetType (klassName + ", " + AssemblyName); - Assert.NotNull (klass, klassName); + Assert.That (klass, Is.Not.Null, klassName); } [Test] public void Class_Unconditional () { - var klass = Type.GetType ("ObjCRuntime.Class, " + AssemblyName); - Assert.NotNull (klass, "Class"); + var klass = Type.GetType ("ObjCRuntime.Class, " + AssemblyName)!; + Assert.That (klass, Is.Not.Null, "Class"); // handle is unconditionally preserved var field = klass.GetField ("handle", BindingFlags.NonPublic | BindingFlags.Instance); - Assert.NotNull (field, "handle"); + Assert.That (field, Is.Not.Null, "handle"); } [Test] public void Runtime_Unconditional () { - var klass = Type.GetType ("ObjCRuntime.Runtime, " + AssemblyName); - Assert.NotNull (klass, "Runtime"); + var klass = Type.GetType ("ObjCRuntime.Runtime, " + AssemblyName)!; + Assert.That (klass, Is.Not.Null, "Runtime"); // Initialize and a few other methods are unconditionally preserved var method = klass.GetMethod ("Initialize", BindingFlags.NonPublic | BindingFlags.Static); - Assert.NotNull (method, "Initialize"); + Assert.That (method, Is.Not.Null, "Initialize"); method = klass.GetMethod ("RegisterNSObject", BindingFlags.NonPublic | BindingFlags.Static, null, new Type [] { typeof (NSObject), typeof (IntPtr) }, null); - Assert.NotNull (method, "RegisterNSObject"); + Assert.That (method, Is.Not.Null, "RegisterNSObject"); } [Test] public void Selector_Unconditional () { - var klass = Type.GetType ("ObjCRuntime.Selector, " + AssemblyName); - Assert.NotNull (klass, "Selector"); + var klass = Type.GetType ("ObjCRuntime.Selector, " + AssemblyName)!; + Assert.That (klass, Is.Not.Null, "Selector"); // handle and is unconditionally preserved var field = klass.GetField ("handle", BindingFlags.NonPublic | BindingFlags.Instance); - Assert.NotNull (field, "handle"); + Assert.That (field, Is.Not.Null, "handle"); var method = klass.GetMethod ("GetHandle", BindingFlags.Public | BindingFlags.Static); - Assert.NotNull (method, "GetHandle"); + Assert.That (method, Is.Not.Null, "GetHandle"); } [Test] public void SmartEnumTest () { - var consumer = GetType ().Assembly.GetType ("LinkAll.Attributes.SmartConsumer" + WorkAroundLinkerHeuristics); - Assert.NotNull (consumer, "SmartConsumer"); - Assert.NotNull (consumer.GetMethod ("GetSmartEnumValue"), "GetSmartEnumValue"); - Assert.NotNull (consumer.GetMethod ("SetSmartEnumValue"), "SetSmartEnumValue"); - var smartEnum = GetType ().Assembly.GetType ("LinkAll.Attributes.SmartEnum"); - Assert.NotNull (smartEnum, "SmartEnum"); - var smartExtensions = GetType ().Assembly.GetType ("LinkAll.Attributes.SmartEnumExtensions" + WorkAroundLinkerHeuristics); - Assert.NotNull (smartExtensions, "SmartEnumExtensions"); - Assert.NotNull (smartExtensions.GetMethod ("GetConstant"), "GetConstant"); - Assert.NotNull (smartExtensions.GetMethod ("GetValue"), "GetValue"); + var consumer = GetType ().Assembly.GetType ("LinkAll.Attributes.SmartConsumer" + WorkAroundLinkerHeuristics)!; + Assert.That (consumer, Is.Not.Null, "SmartConsumer"); + Assert.That (consumer.GetMethod ("GetSmartEnumValue"), Is.Not.Null, "GetSmartEnumValue"); + Assert.That (consumer.GetMethod ("SetSmartEnumValue"), Is.Not.Null, "SetSmartEnumValue"); + var smartEnum = GetType ().Assembly.GetType ("LinkAll.Attributes.SmartEnum")!; + Assert.That (smartEnum, Is.Not.Null, "SmartEnum"); + var smartExtensions = GetType ().Assembly.GetType ("LinkAll.Attributes.SmartEnumExtensions" + WorkAroundLinkerHeuristics)!; + Assert.That (smartExtensions, Is.Not.Null, "SmartEnumExtensions"); + Assert.That (smartExtensions.GetMethod ("GetConstant"), Is.Not.Null, "GetConstant"); + Assert.That (smartExtensions.GetMethod ("GetValue"), Is.Not.Null, "GetValue"); // Unused smart enums and their extensions should be linked away - Assert.IsNull (typeof (NSObject).Assembly.GetType ("AVFoundation.AVMediaTypes"), "AVMediaTypes"); - Assert.IsNull (typeof (NSObject).Assembly.GetType ("AVFoundation.AVMediaTypesExtensions"), "AVMediaTypesExtensions"); + Assert.That (typeof (NSObject).Assembly.GetType ("AVFoundation.AVMediaTypes"), Is.Null, "AVMediaTypes"); + Assert.That (typeof (NSObject).Assembly.GetType ("AVFoundation.AVMediaTypesExtensions"), Is.Null, "AVMediaTypesExtensions"); } [Test] public void PreserveAllExcludesNestedTypes () { var parentClass = GetType ().Assembly.GetType ("LinkAll.Attributes.ParentClass" + WorkAroundLinkerHeuristics); - Assert.NotNull (parentClass, "ParentClass"); + Assert.That (parentClass, Is.Not.Null, "ParentClass"); var nestedEnum = GetType ().Assembly.GetType ("LinkAll.Attributes.ParentClass.NestedEnum" + WorkAroundLinkerHeuristics); - Assert.Null (nestedEnum, "NestedEnum"); + Assert.That (nestedEnum, Is.Null, "NestedEnum"); var nestedStruct = GetType ().Assembly.GetType ("LinkAll.Attributes.ParentClass.NestedStruct" + WorkAroundLinkerHeuristics); - Assert.Null (nestedStruct, "NestedStruct"); + Assert.That (nestedStruct, Is.Null, "NestedStruct"); var nestedClass = GetType ().Assembly.GetType ("LinkAll.Attributes.ParentClass.NestedClass" + WorkAroundLinkerHeuristics); - Assert.Null (nestedClass, "NestedClass"); + Assert.That (nestedClass, Is.Null, "NestedClass"); } [Test] public void PreserveAllKeepsEnumValues () { - var enumType = GetType ().Assembly.GetType ("LinkAll.Attributes.MyEnum" + WorkAroundLinkerHeuristics); - Assert.NotNull (enumType, "MyEnum"); - Assert.AreEqual (3, enumType.GetFields (BindingFlags.Public | BindingFlags.Static).Length, "fields"); + var enumType = GetType ().Assembly.GetType ("LinkAll.Attributes.MyEnum" + WorkAroundLinkerHeuristics)!; + Assert.That (enumType, Is.Not.Null, "MyEnum"); + Assert.That (enumType.GetFields (BindingFlags.Public | BindingFlags.Static).Length, Is.EqualTo (3), "fields"); AssertHasStaticField ("A", 1); AssertHasStaticField ("B", 2); AssertHasStaticField ("C", 4); void AssertHasStaticField (string name, int value) { - var field = enumType.GetField (name, BindingFlags.Public | BindingFlags.Static); - Assert.NotNull (field, name); - Assert.AreEqual (value, (int) field.GetValue (null), $"{name} == {value}"); + var field = enumType.GetField (name, BindingFlags.Public | BindingFlags.Static)!; + Assert.That (field, Is.Not.Null, name); + Assert.That ((int) field.GetValue (null)!, Is.EqualTo (value), $"{name} == {value}"); } } } diff --git a/tests/linker/link all/SealerTest.cs b/tests/linker/link all/SealerTest.cs index 578de40d4378..152978877278 100644 --- a/tests/linker/link all/SealerTest.cs +++ b/tests/linker/link all/SealerTest.cs @@ -45,22 +45,22 @@ public void SetUp () public void Sealed () { // this can not be optimized into a sealed type - Assert.False (typeof (Unsealable).IsSealed, "Unsealed"); + Assert.That (typeof (Unsealable).IsSealed, Is.False, "Unsealed"); #if DEBUG || __MACOS__ // this is not a sealed type (in the source) - Assert.False (typeof (Sealable).IsSealed, "Sealable"); - Assert.False (typeof (Base).IsSealed, "Base"); - Assert.False (typeof (Subclass).IsSealed, "Subclass"); - Assert.False (typeof (Interface).IsSealed, "Interface"); + Assert.That (typeof (Sealable).IsSealed, Is.False, "Sealable"); + Assert.That (typeof (Base).IsSealed, Is.False, "Base"); + Assert.That (typeof (Subclass).IsSealed, Is.False, "Subclass"); + Assert.That (typeof (Interface).IsSealed, Is.False, "Interface"); #else // Sealable can be optimized / sealed as nothing else is (or can) subclass it - Assert.True (typeof (Sealable).IsSealed, "Sealable"); + Assert.That (typeof (Sealable).IsSealed, Is.True, "Sealable"); // Base is subclassed so it can't be sealed - Assert.False (typeof (Base).IsSealed, "Base"); + Assert.That (typeof (Base).IsSealed, Is.False, "Base"); // Subclass is not subclassed anymore and can be sealed - Assert.True (typeof (Subclass).IsSealed, "Subclass"); + Assert.That (typeof (Subclass).IsSealed, Is.True, "Subclass"); // interface can not be sealed - Assert.False (typeof (Interface).IsSealed, "Interface"); + Assert.That (typeof (Interface).IsSealed, Is.False, "Interface"); #endif } @@ -68,19 +68,19 @@ public void Sealed () public void Final () { var t = typeof (Sealable); - var a = t.GetMethod ("A"); - var b = t.GetMethod ("B"); - var c = t.GetMethod ("C"); + var a = t.GetMethod ("A")!; + var b = t.GetMethod ("B")!; + var c = t.GetMethod ("C")!; #if DEBUG || __MACOS__ // this is not a sealed (C#) method (in the source) - Assert.False (a.IsFinal, "A"); - Assert.False (b.IsFinal, "B"); - Assert.False (c.IsFinal, "C"); + Assert.That (a.IsFinal, Is.False, "A"); + Assert.That (b.IsFinal, Is.False, "B"); + Assert.That (c.IsFinal, Is.False, "C"); #else // but it can be optimized / sealed as nothing else is (or can) overrides it - Assert.True (a.IsFinal, "A"); - Assert.True (b.IsFinal, "B"); - Assert.False (c.IsFinal, "C"); // devirtualized + Assert.That (a.IsFinal, Is.True, "A"); + Assert.That (b.IsFinal, Is.True, "B"); + Assert.That (c.IsFinal, Is.False, "C"); // devirtualized #endif } @@ -88,21 +88,21 @@ public void Final () public void Virtual () { var t = typeof (Sealable); - var a = t.GetMethod ("A"); - var b = t.GetMethod ("B"); - var c = t.GetMethod ("C"); + var a = t.GetMethod ("A")!; + var b = t.GetMethod ("B")!; + var c = t.GetMethod ("C")!; #if DEBUG || __MACOS__ // both methods are virtual (both in C# and IL) - Assert.True (a.IsVirtual, "A"); - Assert.True (b.IsVirtual, "B"); - Assert.True (c.IsVirtual, "C"); + Assert.That (a.IsVirtual, Is.True, "A"); + Assert.That (b.IsVirtual, Is.True, "B"); + Assert.That (c.IsVirtual, Is.True, "C"); #else // calling A needs dispatch to base type Unsealable - Assert.True (a.IsVirtual, "A"); + Assert.That (a.IsVirtual, Is.True, "A"); // B is an override and must remain virtual - Assert.True (b.IsVirtual, "B"); + Assert.That (b.IsVirtual, Is.True, "B"); // C has no special requirement and can be de-virtualized - Assert.False (c.IsVirtual, "C"); + Assert.That (c.IsVirtual, Is.False, "C"); #endif } @@ -110,9 +110,9 @@ public void Virtual () public void Interface () { var t = typeof (Subclass); - var a = t.GetMethod ("A"); + var a = t.GetMethod ("A")!; // A cannot be de-virtualized since Concrete must satisfy Interface thru Base - Assert.True (a.IsVirtual, "A"); + Assert.That (a.IsVirtual, Is.True, "A"); } } } diff --git a/tests/linker/link all/SerializationTest.cs b/tests/linker/link all/SerializationTest.cs index 8e1fd97a17b3..3c0b9eae60f6 100644 --- a/tests/linker/link all/SerializationTest.cs +++ b/tests/linker/link all/SerializationTest.cs @@ -13,12 +13,12 @@ namespace LinkAll { static class Helper { public static Type GetType (string name) { - return Type.GetType (name); + return Type.GetType (name)!; } public static Type GetType (string typeName, bool throwOnError) { - return Type.GetType (typeName, throwOnError); + return Type.GetType (typeName, throwOnError)!; } } } @@ -84,7 +84,7 @@ public void UnusedType () // the serialization attributes only keeps the method(s) if the type was used var t = Helper.GetType ("LinkAll.Serialization.Unused"); // since it's not used in the app then it's removed by the linker - Assert.Null (t, "type"); + Assert.That (t, Is.Null, "type"); } [Test] @@ -93,9 +93,9 @@ public void UsedType () // the serialization attributes only keeps the method(s) if the type was used var t = Helper.GetType ("LinkAll.Serialization.Used"); // since it's used here... - Assert.NotNull (new Used (), "reference"); + Assert.That (new Used (), Is.Not.Null, "reference"); // it's not removed by the linker - Assert.NotNull (t, "type"); + Assert.That (t, Is.Not.Null, "type"); // and since it's not the 4 decorated methods are also kept (even if uncalled) Assert.That (t.GetMethods ().Length, Is.EqualTo (4), "4"); } diff --git a/tests/linker/link all/StructLayoutTest.cs b/tests/linker/link all/StructLayoutTest.cs index b47621117b5e..e6fc5d2dca2e 100644 --- a/tests/linker/link all/StructLayoutTest.cs +++ b/tests/linker/link all/StructLayoutTest.cs @@ -53,9 +53,9 @@ public void DefaultLayoutStruct () // sequential var fields = t.GetFields (); Assert.That (fields.Length, Is.EqualTo (2), "Length"); - Assert.False (t.IsAutoLayout, "IsAutoLayout"); - Assert.False (t.IsExplicitLayout, "IsExplicitLayout"); - Assert.True (t.IsLayoutSequential, "IsLayoutSequential"); + Assert.That (t.IsAutoLayout, Is.False, "IsAutoLayout"); + Assert.That (t.IsExplicitLayout, Is.False, "IsExplicitLayout"); + Assert.That (t.IsLayoutSequential, Is.True, "IsLayoutSequential"); } [Test] @@ -68,9 +68,9 @@ public void AutoLayoutStruct () var fields = t.GetFields (); Assert.That (fields.Length, Is.EqualTo (2), "Length"); - Assert.True (t.IsAutoLayout, "IsAutoLayout"); - Assert.False (t.IsExplicitLayout, "IsExplicitLayout"); - Assert.False (t.IsLayoutSequential, "IsLayoutSequential"); + Assert.That (t.IsAutoLayout, Is.True, "IsAutoLayout"); + Assert.That (t.IsExplicitLayout, Is.False, "IsExplicitLayout"); + Assert.That (t.IsLayoutSequential, Is.False, "IsLayoutSequential"); } [Test] @@ -83,9 +83,9 @@ public void LayoutSequential () var fields = t.GetFields (); Assert.That (fields.Length, Is.EqualTo (2), "Length"); - Assert.False (t.IsAutoLayout, "IsAutoLayout"); - Assert.False (t.IsExplicitLayout, "IsExplicitLayout"); - Assert.True (t.IsLayoutSequential, "IsLayoutSequential"); + Assert.That (t.IsAutoLayout, Is.False, "IsAutoLayout"); + Assert.That (t.IsExplicitLayout, Is.False, "IsExplicitLayout"); + Assert.That (t.IsLayoutSequential, Is.True, "IsLayoutSequential"); } [Test] @@ -98,9 +98,9 @@ public void ExplicitLayout () var fields = t.GetFields (); Assert.That (fields.Length, Is.EqualTo (3), "Length"); - Assert.False (t.IsAutoLayout, "IsAutoLayout"); - Assert.True (t.IsExplicitLayout, "IsExplicitLayout"); - Assert.False (t.IsLayoutSequential, "IsLayoutSequential"); + Assert.That (t.IsAutoLayout, Is.False, "IsAutoLayout"); + Assert.That (t.IsExplicitLayout, Is.True, "IsExplicitLayout"); + Assert.That (t.IsLayoutSequential, Is.False, "IsLayoutSequential"); } } } diff --git a/tests/linker/link all/XmlSerializationTest.cs b/tests/linker/link all/XmlSerializationTest.cs index 5943406fb7ed..9c7acb6f1bb4 100644 --- a/tests/linker/link all/XmlSerializationTest.cs +++ b/tests/linker/link all/XmlSerializationTest.cs @@ -15,21 +15,21 @@ namespace LinkAll.Serialization.Xml { [Serializable] [XmlRoot ("rsp", IsNullable = false)] - public class XmlResult { + public class XmlResult where T : class { [XmlAttribute ("stat")] public int StatusCode { get; set; } [XmlElement ("photos")] [XmlElement ("photosets")] - public T Result { get; set; } + public T? Result { get; set; } } [Serializable] [XmlRoot ("rsp")] - public class XmlField { + public class XmlField where T : class { [XmlElement ("photos")] [XmlElement ("photosets")] - public T Result; + public T? Result; } [Ignore ("https://github.com/dotnet/runtime/issues/41389")] @@ -52,7 +52,7 @@ public void GenericProperty_Bug5543 () r.StatusCode = -1; ms.Position = 0; - XmlResult back = (XmlResult) serializer.Deserialize (ms); + var back = (XmlResult) serializer.Deserialize (ms)!; Assert.That (back.Result, Is.EqualTo ("5543"), "Result"); Assert.That (back.StatusCode, Is.EqualTo (10), "StatusCode"); diff --git a/tests/linker/link all/dotnet/shared.csproj b/tests/linker/link all/dotnet/shared.csproj index a8bad04a8cf9..6b75ec2a2d4e 100644 --- a/tests/linker/link all/dotnet/shared.csproj +++ b/tests/linker/link all/dotnet/shared.csproj @@ -18,10 +18,6 @@ $(NoWarn);CA1422 - - - true - Nullable @@ -88,14 +84,12 @@ - - - - - - - - - + + + + + + + diff --git a/tests/linker/link sdk/AotBugs.cs b/tests/linker/link sdk/AotBugs.cs index c97b6a6d1bd3..a63cc4205247 100644 --- a/tests/linker/link sdk/AotBugs.cs +++ b/tests/linker/link sdk/AotBugs.cs @@ -40,27 +40,27 @@ public partial class AotBugsTest : IAotTest { public void Aot_3285 () { // called as an extension method (always worked) - Assert.False (GetType ().GetInterfaces (typeof (IExpectException)).Select (interf => interf is not null).FirstOrDefault (), "false"); + Assert.That (GetType ().GetInterfaces (typeof (IExpectException)).Select (interf => interf is not null).FirstOrDefault (), Is.False, "false"); // workaround for #3285 - similar to previous fix for monotouch/aot // called as a static method (does not change the result - but it was closer to the original test case) - Assert.True (AotExtension.GetInterfaces (GetType (), typeof (IAotTest)).Select (interf => interf is not null).FirstOrDefault (delegate { return true; }), "delegate"); + Assert.That (AotExtension.GetInterfaces (GetType (), typeof (IAotTest)).Select (interf => interf is not null).FirstOrDefault (delegate { return true; }), Is.True, "delegate"); // actual, failing, test case (fixed by inlining code) - Assert.True (GetType ().GetInterfaces (typeof (IAotTest)).Select (interf => interf is not null).FirstOrDefault (), "FirstOrDefault/true"); + Assert.That (GetType ().GetInterfaces (typeof (IAotTest)).Select (interf => interf is not null).FirstOrDefault (), Is.True, "FirstOrDefault/true"); // other similar cases (returning bool with optional predicate delegate) var enumerable = GetType ().GetInterfaces (typeof (IAotTest)).Select (interf => interf is not null); - Assert.True (enumerable.Any (), "Any"); - Assert.True (enumerable.ElementAt (0), "ElementAt"); - Assert.True (enumerable.ElementAtOrDefault (0), "ElementAtOrDefault"); - Assert.True (enumerable.First (), "First"); - Assert.True (enumerable.Last (), "Last"); // failed before fix - Assert.True (enumerable.LastOrDefault (), "LastOrDefault"); // failed before fix - Assert.True (enumerable.Max (), "Max"); - Assert.True (enumerable.Min (), "Min"); - Assert.True (enumerable.Single (), "Single"); // failed before fix - Assert.True (enumerable.SingleOrDefault (), "SingleOrDefault"); // failed before fix + Assert.That (enumerable.Any (), Is.True, "Any"); + Assert.That (enumerable.ElementAt (0), Is.True, "ElementAt"); + Assert.That (enumerable.ElementAtOrDefault (0), Is.True, "ElementAtOrDefault"); + Assert.That (enumerable.First (), Is.True, "First"); + Assert.That (enumerable.Last (), Is.True, "Last"); // failed before fix + Assert.That (enumerable.LastOrDefault (), Is.True, "LastOrDefault"); // failed before fix + Assert.That (enumerable.Max (), Is.True, "Max"); + Assert.That (enumerable.Min (), Is.True, "Min"); + Assert.That (enumerable.Single (), Is.True, "Single"); // failed before fix + Assert.That (enumerable.SingleOrDefault (), Is.True, "SingleOrDefault"); // failed before fix } [Test] @@ -72,7 +72,7 @@ public void ConcurrentDictionary_3444 () } class SomeObject { - public event EventHandler Event; + public event EventHandler? Event; public void RaiseEvent () { @@ -82,7 +82,7 @@ public void RaiseEvent () } } - void OnEvent (object sender, EventArgs e) + void OnEvent (object? sender, EventArgs e) { } @@ -103,7 +103,8 @@ public void Workaround_3682 () var e = so.GetType ().GetEvent ("Event"); if (e is not null) { var add = e.GetAddMethod (); - add.Invoke (so, new object [] { new EventHandler (OnEvent) }); + if (add is not null) + add.Invoke (so, new object [] { new EventHandler (OnEvent) }); } } @@ -148,7 +149,7 @@ public void Linq_Join_3627 () var query = (from wqual in c join personTable in p on wqual.FK_PERSON equals personTable.Id select new CounselingWithPerson (wqual, personTable)); - Assert.NotNull (query.ToList ()); + Assert.That (query.ToList (), Is.Not.Null); // above throws ExecutionEngineException } @@ -163,12 +164,12 @@ public void Workaround_3627 () var query = (from wqual in c join personTable in p on wqual.FK_PERSON.ToString () equals personTable.Id.ToString () select new CounselingWithPerson (wqual, personTable)); - Assert.NotNull (query.ToList ()); + Assert.That (query.ToList (), Is.Not.Null); } public class Foo { public int Id { get; set; } - public string Name { get; set; } + public string Name { get; set; } = ""; } [Test] @@ -225,7 +226,7 @@ public void Any_3735 () Environment.SpecialFolder.ApplicationData, Environment.SpecialFolder.CommonApplicationData }; - Assert.True (array.Any (folder => folder == Environment.SpecialFolder.ApplicationData)); + Assert.That (array.Any (folder => folder == Environment.SpecialFolder.ApplicationData), Is.True); // above throws ExecutionEngineException // Attempting to JIT compile method '(wrapper managed-to-managed) System.Environment/SpecialFolder[]:System.Collections.Generic.IEnumerable`1.GetEnumerator ()' while running with --aot-only. } @@ -238,7 +239,7 @@ public void Workaround_3735 () List list = new List () { MidpointRounding.AwayFromZero }; - Assert.True (list.Any (rounding => rounding == MidpointRounding.AwayFromZero)); + Assert.That (list.Any (rounding => rounding == MidpointRounding.AwayFromZero), Is.True); } Task InnerTestB () @@ -288,7 +289,7 @@ join s in Table
    () on q.SectionId equals s.Id select q; // note: orderby causing: // Attempting to JIT compile method 'System.Linq.OrderedEnumerable`1<<>__AnonType0`2>:CreateOrderedEnumerable (System.Func`2<<>__AnonType0`2, int>,System.Collections.Generic.IComparer`1,bool)' while running with --aot-only. - Assert.NotNull (result); + Assert.That (result, Is.Not.Null); } [Test] @@ -301,7 +302,7 @@ join s in Table
    () on q.SectionId equals s.Id where s.BoardId == boardId orderby q.IsAnswered.ToString (), s.Position.ToString (), q.Position.ToString () select q; - Assert.NotNull (result); + Assert.That (result, Is.Not.Null); } [Test] @@ -315,7 +316,7 @@ join s in Table
    () on q.SectionId equals s.Id select q; // query is ok foreach (var result in results) - Assert.NotNull (result); + Assert.That (result, Is.Not.Null); } [Test] @@ -328,7 +329,7 @@ join s in Table
    () on q.SectionId.ToString () equals s.Id.ToString () where s.BoardId == boardId select q; foreach (var result in results) - Assert.NotNull (result); + Assert.That (result, Is.Not.Null); } public class VirtualGeneric { @@ -346,7 +347,7 @@ public virtual ICollection MakeCollectionOfInputs (T input1, T input2, T i public void Virtual_4114 () { VirtualGeneric g = new VirtualGeneric (); - Assert.NotNull (g.MakeCollectionOfInputs (1.0, 2.0, 3.0)); + Assert.That (g.MakeCollectionOfInputs (1.0, 2.0, 3.0), Is.Not.Null); } public class OverrideGeneric : VirtualGeneric { @@ -368,15 +369,15 @@ public void Override_4114 () g.MakeCollectionOfInputs (1.0, 2.0, 3.0); } - public sealed class NewDictionary { + public sealed class NewDictionary where TKey : notnull { Dictionary _dictionary = new Dictionary (); - public NewDictionary (IEnumerable> items) + public NewDictionary (IEnumerable>? items) { ForEach (items, (item) => _dictionary.Add (item.Key, item.Value)); } - static void ForEach (IEnumerable collection, Action action) + static void ForEach (IEnumerable? collection, Action action) { if (collection is not null) foreach (T item in collection) @@ -392,8 +393,10 @@ public void ForEachKVP_4114 () } public class Enumbers { - public IEnumerable> Enumerate (List> alist) + public IEnumerable> Enumerate (List>? alist) { + if (alist is null) + throw new NullReferenceException (); return MakeEnumerable (alist.ToArray ()); } @@ -411,7 +414,7 @@ public void AsEnumerable_4114 () Assert.Throws (() => e.Enumerate (null)); } - static object mInstance = null; + static object? mInstance = null; [MethodImpl (MethodImplOptions.Synchronized)] public static object getInstance () @@ -458,7 +461,7 @@ public void Bug8379_b () public static IEnumerable GetStringList () where T : struct, IConvertible { - return Enum.GetValues (typeof (T)).Cast ().Select (x => x.ToString ()); + return Enum.GetValues (typeof (T)).Cast ().Select (x => x.ToString () ?? ""); } [Test] @@ -466,7 +469,7 @@ public void Bug12811a () { int n = 1; foreach (var e in GetStringList ()) { - Assert.NotNull (e, n.ToString ()); + Assert.That (e, Is.Not.Null, n.ToString ()); n++; } } @@ -476,7 +479,7 @@ public void Bug12811b () { int n = 1; foreach (var e in Enum.GetValues (typeof (NSFileManagerItemReplacementOptions)).Cast ().Select (x => x.ToString ())) { - Assert.NotNull (e, n.ToString ()); + Assert.That (e, Is.Not.Null, n.ToString ()); n++; } } @@ -527,10 +530,10 @@ public enum MyEnum8ElementsInUInt16 : ushort { [Test] public void Bug12605 () { - Assert.AreEqual ("One", Convert.ToString ((MyEnum8ElementsInInt32) 1), "1"); - Assert.AreEqual ("One", Convert.ToString ((MyEnum8ElementsInUInt32) 1), "2"); - Assert.AreEqual ("One", Convert.ToString ((MyEnum7ElementsInUInt16) 1), "3"); - Assert.AreEqual ("One", Convert.ToString ((MyEnum8ElementsInUInt16) 1), "4"); + Assert.That (Convert.ToString ((MyEnum8ElementsInInt32) 1), Is.EqualTo ("One"), "1"); + Assert.That (Convert.ToString ((MyEnum8ElementsInUInt32) 1), Is.EqualTo ("One"), "2"); + Assert.That (Convert.ToString ((MyEnum7ElementsInUInt16) 1), Is.EqualTo ("One"), "3"); + Assert.That (Convert.ToString ((MyEnum8ElementsInUInt16) 1), Is.EqualTo ("One"), "4"); } [Test] @@ -557,7 +560,7 @@ public void Bug12895 () (?:[Ee][+-]?[0-9]+)? # Optional exponent (?![A-Za-z0-9_]) # Must not be followed by an alphanumeric character )", System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace); - Assert.NotNull (r); // looking got EEE while executing, on devices, the above code + Assert.That (r, Is.Not.Null); // looking got EEE while executing, on devices, the above code } [Test] diff --git a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/Contents.json b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/Contents.json index 6be52c8f7640..0e65c18b41c3 100644 --- a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/Contents.json +++ b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/Contents.json @@ -1,221 +1,15 @@ { "images": [ { - "size": "29x29", - "scale": "1x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "2x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "3x", - "idiom": "iphone" - }, - { - "size": "40x40", - "scale": "2x", - "idiom": "iphone" - }, - { - "size": "40x40", - "scale": "3x", - "idiom": "iphone" - }, - { - "filename": "icon-app-57.png", - "size": "57x57", - "scale": "1x", - "idiom": "iphone" - }, - { - "filename": "icon-app-57@2x.png", - "size": "57x57", - "scale": "2x", - "idiom": "iphone" - }, - { - "filename": "icon-app-60@2x.png", - "size": "60x60", - "scale": "2x", - "idiom": "iphone" - }, - { - "filename": "icon-app-60@3x.png", - "size": "60x60", - "scale": "3x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "29x29", - "scale": "2x", - "idiom": "ipad" - }, - { - "size": "40x40", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "40x40", - "scale": "2x", - "idiom": "ipad" - }, - { - "size": "50x50", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "50x50", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-83.5@2x.png", - "size": "83.5x83.5", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-72.png", - "size": "72x72", - "scale": "1x", - "idiom": "ipad" - }, - { - "filename": "icon-app-72@2x.png", - "size": "72x72", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-76.png", - "size": "76x76", - "scale": "1x", - "idiom": "ipad" - }, - { - "filename": "icon-app-76@2x.png", - "size": "76x76", - "scale": "2x", - "idiom": "ipad" - }, - { - "role": "notificationCenter", - "size": "24x24", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "notificationCenter", - "size": "27.5x27.5", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "companionSettings", - "size": "29x29", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "companionSettings", - "size": "29x29", - "scale": "3x", - "idiom": "watch" - }, - { - "role": "appLauncher", - "size": "40x40", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "longLook", - "size": "44x44", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "quickLook", - "size": "86x86", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "quickLook", - "size": "98x98", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "size": "16x16", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "16x16", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "32x32", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "32x32", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "128x128", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "128x128", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "256x256", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "256x256", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "512x512", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "512x512", - "scale": "2x", - "idiom": "mac" + "filename": "icon-1024.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" } ], "info": { - "version": 1, - "author": "xcode" + "author": "xcode", + "version": 1 } -} \ No newline at end of file +} + diff --git a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/Icon-app-60@3x.png b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/Icon-app-60@3x.png deleted file mode 100644 index 45342a7513b6..000000000000 Binary files a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/Icon-app-60@3x.png and /dev/null differ diff --git a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-1024.png b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-1024.png new file mode 100644 index 000000000000..1e62561f25b7 Binary files /dev/null and b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-1024.png differ diff --git a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-57.png b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-57.png deleted file mode 100644 index ce1d9df94d4f..000000000000 Binary files a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-57.png and /dev/null differ diff --git a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png deleted file mode 100644 index d34d9c694d3f..000000000000 Binary files a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png and /dev/null differ diff --git a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png deleted file mode 100644 index 4409624b29d9..000000000000 Binary files a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png and /dev/null differ diff --git a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-72.png b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-72.png deleted file mode 100644 index 9a77ea277312..000000000000 Binary files a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-72.png and /dev/null differ diff --git a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png deleted file mode 100644 index 32f57d7d89da..000000000000 Binary files a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png and /dev/null differ diff --git a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-76.png b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-76.png deleted file mode 100644 index 12db0c47cc4e..000000000000 Binary files a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-76.png and /dev/null differ diff --git a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png deleted file mode 100644 index 163f1c7f0f18..000000000000 Binary files a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png and /dev/null differ diff --git a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png b/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png deleted file mode 100644 index 0bac1da399b5..000000000000 Binary files a/tests/linker/link sdk/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png and /dev/null differ diff --git a/tests/linker/link sdk/BitcodeTest.cs b/tests/linker/link sdk/BitcodeTest.cs index 1e32c93b6e6c..4255bcf9d742 100644 --- a/tests/linker/link sdk/BitcodeTest.cs +++ b/tests/linker/link sdk/BitcodeTest.cs @@ -9,8 +9,8 @@ public void FilterClauseTest () { var supported = true; if (supported) { - Assert.AreEqual (0, FilterClause (), "Filter me"); - Assert.AreEqual (10, FilterClauseProperty, "Filter me getter"); + Assert.That (FilterClause (), Is.EqualTo (0), "Filter me"); + Assert.That (FilterClauseProperty, Is.EqualTo (10), "Filter me getter"); Assert.DoesNotThrow (() => FilterClauseProperty = 20, "Filter me setter"); } else { Assert.Throws (() => FilterClause (), "Filter me not supported"); @@ -47,7 +47,7 @@ static int FilterClauseProperty { throw new Exception ("FilterMe"); } catch (Exception e) when (e.Message == "FilterMe") { } catch { - Assert.Fail ("Filter failure: {0}", value); + Assert.Fail ($"Filter failure: {value}"); } } } @@ -63,13 +63,17 @@ public void FaultClauseTest () // This is because we only have an indirect way of making csc produce a fault clause var enumeratorType = GetType ().GetNestedTypes (BindingFlags.NonPublic).First ((v) => v.Name.Contains ($"<{nameof (FaultClause)}>")); var method = enumeratorType.GetMethod ("MoveNext", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); + if (method is null) + throw new InvalidOperationException ("MoveNext"); var body = method.GetMethodBody (); - Assert.IsTrue (body.ExceptionHandlingClauses.Any ((v) => v.Flags == ExceptionHandlingClauseOptions.Fault), "Any fault clauses"); + if (body is null) + throw new InvalidOperationException ("MoveNext body"); + Assert.That (body.ExceptionHandlingClauses.Any ((v) => v.Flags == ExceptionHandlingClauseOptions.Fault), Is.True, "Any fault clauses"); // Then assert that the method can be called successfully. var rv = FaultClause ().ToArray (); - Assert.AreEqual (1, rv.Count (), "Count"); - Assert.AreEqual (1, rv [0], "Item 1"); + Assert.That (rv.Count (), Is.EqualTo (1), "Count"); + Assert.That (rv [0], Is.EqualTo (1), "Item 1"); } diff --git a/tests/linker/link sdk/Bug1820Test.cs b/tests/linker/link sdk/Bug1820Test.cs index f66a9de7dc26..6f0efd3d572f 100644 --- a/tests/linker/link sdk/Bug1820Test.cs +++ b/tests/linker/link sdk/Bug1820Test.cs @@ -15,7 +15,7 @@ public partial class XmlSerializationTest { [XmlRoot (Namespace = "", IsNullable = false)] public class Response { private DataUpdates dataUpdatesField; - private static XmlSerializer serializer; + private static XmlSerializer? serializer; public Response () { @@ -38,10 +38,10 @@ private static XmlSerializer Serializer { public static Response Deserialize (string xml) { - StringReader stringReader = null; + StringReader? stringReader = null; try { stringReader = new StringReader (xml); - return ((Response) (Serializer.Deserialize (XmlReader.Create (stringReader)))); + return (Response) (Serializer.Deserialize (XmlReader.Create (stringReader)) ?? throw new InvalidOperationException ("Deserialization returned null.")); } finally { if ((stringReader is not null)) { stringReader.Dispose (); @@ -55,7 +55,7 @@ public static Response Deserialize (string xml) [XmlRoot (Namespace = "", IsNullable = false)] public class DataUpdates { private List dataUpdateInfoField; - private static XmlSerializer serializer; + private static XmlSerializer? serializer; public DataUpdates () { @@ -79,10 +79,10 @@ private static XmlSerializer Serializer { public static DataUpdates Deserialize (string xml) { - StringReader stringReader = null; + StringReader? stringReader = null; try { stringReader = new StringReader (xml); - return ((DataUpdates) (Serializer.Deserialize (XmlReader.Create (stringReader)))); + return (DataUpdates) (Serializer.Deserialize (XmlReader.Create (stringReader)) ?? throw new InvalidOperationException ("Deserialization returned null.")); } finally { if ((stringReader is not null)) { stringReader.Dispose (); @@ -96,9 +96,9 @@ public static DataUpdates Deserialize (string xml) public class DataUpdatesDataUpdateInfo { private DateTime dataDateField; - private string dataTypeField; + private string dataTypeField = ""; private DateTime lastUpdatedDateField; - private static XmlSerializer serializer; + private static XmlSerializer? serializer; public DataUpdatesDataUpdateInfo () { @@ -132,10 +132,10 @@ private static XmlSerializer Serializer { public static DataUpdatesDataUpdateInfo Deserialize (string xml) { - StringReader stringReader = null; + StringReader? stringReader = null; try { stringReader = new StringReader (xml); - return ((DataUpdatesDataUpdateInfo) (Serializer.Deserialize (XmlReader.Create (stringReader)))); + return (DataUpdatesDataUpdateInfo) (Serializer.Deserialize (XmlReader.Create (stringReader)) ?? throw new InvalidOperationException ("Deserialization returned null.")); } finally { if ((stringReader is not null)) { stringReader.Dispose (); diff --git a/tests/linker/link sdk/CryptoTest.cs b/tests/linker/link sdk/CryptoTest.cs index ebe6064269ab..866aee26ff81 100644 --- a/tests/linker/link sdk/CryptoTest.cs +++ b/tests/linker/link sdk/CryptoTest.cs @@ -27,7 +27,7 @@ public void AesCreate () // Aes resides in mscorlib.dll but needs to create instance of types that are // located inside System.Core.dll - IOW the linker needs to be aware of this Aes aes = Aes.Create (); - Assert.NotNull (aes, "Aes"); + Assert.That (aes, Is.Not.Null, "Aes"); const string prefix = "System.Security.Cryptography, "; Assert.That (aes.GetType ().Assembly.FullName, Does.StartWith (prefix), prefix); } @@ -41,16 +41,18 @@ public void TrustUsingNewCallback () // untrusted, custom ICertificatePolicy and ServerCertificateValidationCallback without // having caching issues (in S.Net or the SSL handshake cache) try { - ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) + ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate? cert, X509Chain? chain, SslPolicyErrors errors) { + if (cert is null || chain is null) + return false; Assert.That (errors, Is.EqualTo (SslPolicyErrors.None), "certificateProblem"); X509Certificate2 c2 = X509CertificateLoader.LoadCertificate (cert.GetRawCertData ()); - Assert.True (chain.Build (c2), "Build"); + Assert.That (chain.Build (c2), Is.True, "Build"); trust_validation_callback++; return true; }; WebClient wc = new WebClient (); - Assert.IsNotNull (wc.DownloadString (NetworkResources.XamarinUrl)); + Assert.That (wc.DownloadString (NetworkResources.XamarinUrl), Is.Not.Null); // caching means it will be called at least for the first run, but it might not // be called again in subsequent requests (unless it expires) Assert.That (trust_validation_callback, Is.GreaterThan (0), "validation done"); @@ -93,17 +95,19 @@ public void TLS1_ServerNameExtension () var actual = ServicePointManager.SecurityProtocol; try { - ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) + ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate? cert, X509Chain? chain, SslPolicyErrors errors) { + if (cert is null || chain is null) + return false; Assert.That (errors, Is.EqualTo (SslPolicyErrors.None), "certificateProblem"); X509Certificate2 c2 = X509CertificateLoader.LoadCertificate (cert.GetRawCertData ()); - Assert.True (chain.Build (c2), "Build"); + Assert.That (chain.Build (c2), Is.True, "Build"); sne_validation_callback++; return true; }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; WebClient wc = new WebClient (); - Assert.IsNotNull (wc.DownloadString (NetworkResources.StatsUrl)); + Assert.That (wc.DownloadString (NetworkResources.StatsUrl), Is.Not.Null); } catch (WebException we) { // failing to get data does not mean the SSL/TLS session was not established if (sne_validation_callback == 0) { @@ -133,16 +137,16 @@ public void Chain () chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; chain.ChainPolicy.CustomTrustStore.Add (rootCert); - Assert.False (chain.Build (cert), "Online"); - Assert.True (chain.ChainStatus.Any (s => s.Status.HasFlag (X509ChainStatusFlags.RevocationStatusUnknown)), "Online"); + Assert.That (chain.Build (cert), Is.False, "Online"); + Assert.That (chain.ChainStatus.Any (s => s.Status.HasFlag (X509ChainStatusFlags.RevocationStatusUnknown)), Is.True, "Online"); chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline; - Assert.False (chain.Build (cert), "Offline"); - Assert.True (chain.ChainStatus.Any (s => s.Status.HasFlag (X509ChainStatusFlags.RevocationStatusUnknown)), "Offline"); + Assert.That (chain.Build (cert), Is.False, "Offline"); + Assert.That (chain.ChainStatus.Any (s => s.Status.HasFlag (X509ChainStatusFlags.RevocationStatusUnknown)), Is.True, "Offline"); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; - Assert.True (chain.Build (cert), "NoCheck"); - Assert.AreEqual (0, chain.ChainStatus.Length, "NoCheck"); + Assert.That (chain.Build (cert), Is.True, "NoCheck"); + Assert.That (chain.ChainStatus.Length, Is.EqualTo (0), "NoCheck"); } byte [] sha256_data = { @@ -205,7 +209,7 @@ public void Sha256 () { X509Certificate2 c = X509CertificateLoader.LoadCertificate (sha256_data); // can't build is fine - as long as we do not throw - Assert.False (new X509Chain (false).Build (c), "Build"); + Assert.That (new X509Chain (false).Build (c), Is.False, "Build"); } } } diff --git a/tests/linker/link sdk/DataContractTest.cs b/tests/linker/link sdk/DataContractTest.cs index 14f2c52577ca..3156d5f14272 100644 --- a/tests/linker/link sdk/DataContractTest.cs +++ b/tests/linker/link sdk/DataContractTest.cs @@ -17,7 +17,7 @@ public class MyClass { public MyClass () { } [DataMember] - List MyList { get; set; } + List MyList { get; set; } = []; } [TestFixture] diff --git a/tests/linker/link sdk/DllImportTest.cs b/tests/linker/link sdk/DllImportTest.cs index 1c014a4fe788..eafc04fbeec8 100644 --- a/tests/linker/link sdk/DllImportTest.cs +++ b/tests/linker/link sdk/DllImportTest.cs @@ -34,7 +34,7 @@ public class NestedSecondLevel { public void ScanForStrip_17327 () { // note: must be tested on a release (strip'ed) build - Assert.NotNull (NestedFirstLevel.NestedSecondLevel.xamarin_get_locale_country_code ()); + Assert.That (NestedFirstLevel.NestedSecondLevel.xamarin_get_locale_country_code (), Is.Not.Null); } [Test] @@ -89,7 +89,7 @@ public void PingSend () }; var timeout = TimeSpan.FromSeconds (10); var tasks = hosts.Select (host => (new Ping ()).SendPingAsync (host, timeout)).ToArray (); - Assert.IsTrue (Task.WaitAll (tasks, timeout.Add (TimeSpan.FromSeconds (10))), "One or more of the ping requests timed out."); + Assert.That (Task.WaitAll (tasks, timeout.Add (TimeSpan.FromSeconds (10))), Is.True, "One or more of the ping requests timed out."); var results = tasks.Select (task => task.Result.Status).ToArray (); Assert.That (results, Has.Some.EqualTo (IPStatus.Success), "Pong any host"); } diff --git a/tests/linker/link sdk/HttpClientHandlerTest.cs b/tests/linker/link sdk/HttpClientHandlerTest.cs index 321bc565397f..fd9d6d3bda85 100644 --- a/tests/linker/link sdk/HttpClientHandlerTest.cs +++ b/tests/linker/link sdk/HttpClientHandlerTest.cs @@ -15,20 +15,20 @@ public class HttpClientHandlerTest { public void HttpClient () { using (var handler = new HttpClientHandler ()) { - Assert.True (handler.AllowAutoRedirect, "AllowAutoRedirect"); - Assert.NotNull (handler.CookieContainer, "CookieContainer"); - Assert.Null (handler.Credentials, "Credentials"); + Assert.That (handler.AllowAutoRedirect, Is.True, "AllowAutoRedirect"); + Assert.That (handler.CookieContainer, Is.Not.Null, "CookieContainer"); + Assert.That (handler.Credentials, Is.Null, "Credentials"); // (so far) not exposed in other, native handlers Assert.That (handler.AutomaticDecompression, Is.EqualTo (DecompressionMethods.None), "AutomaticDecompression"); Assert.That (handler.ClientCertificateOptions, Is.EqualTo (ClientCertificateOption.Manual), "ClientCertificateOptions"); Assert.That (handler.MaxAutomaticRedirections, Is.EqualTo (50), "MaxAutomaticRedirections"); - Assert.Null (handler.Proxy, "Proxy"); - Assert.True (handler.SupportsAutomaticDecompression, "SupportsAutomaticDecompression"); - Assert.True (handler.SupportsProxy, "SupportsProxy"); - Assert.True (handler.SupportsRedirectConfiguration, "SupportsRedirectConfiguration"); - Assert.True (handler.UseCookies, "UseCookies"); - Assert.False (handler.UseDefaultCredentials, "UseDefaultCredentials"); - Assert.True (handler.UseProxy, "UseProxy"); + Assert.That (handler.Proxy, Is.Null, "Proxy"); + Assert.That (handler.SupportsAutomaticDecompression, Is.True, "SupportsAutomaticDecompression"); + Assert.That (handler.SupportsProxy, Is.True, "SupportsProxy"); + Assert.That (handler.SupportsRedirectConfiguration, Is.True, "SupportsRedirectConfiguration"); + Assert.That (handler.UseCookies, Is.True, "UseCookies"); + Assert.That (handler.UseDefaultCredentials, Is.False, "UseDefaultCredentials"); + Assert.That (handler.UseProxy, Is.True, "UseProxy"); } } @@ -36,10 +36,10 @@ public void HttpClient () public void CFNetwork () { using (var handler = new CFNetworkHandler ()) { - Assert.True (handler.AllowAutoRedirect, "AllowAutoRedirect"); - Assert.NotNull (handler.CookieContainer, "CookieContainer"); + Assert.That (handler.AllowAutoRedirect, Is.True, "AllowAutoRedirect"); + Assert.That (handler.CookieContainer, Is.Not.Null, "CookieContainer"); // custom, not in HttpClientHandler - Assert.False (handler.UseSystemProxy, "UseSystemProxy"); + Assert.That (handler.UseSystemProxy, Is.False, "UseSystemProxy"); } } @@ -47,10 +47,10 @@ public void CFNetwork () public void NSUrlSession () { using (var handler = new NSUrlSessionHandler ()) { - Assert.True (handler.AllowAutoRedirect, "AllowAutoRedirect"); - Assert.Null (handler.Credentials, "Credentials"); + Assert.That (handler.AllowAutoRedirect, Is.True, "AllowAutoRedirect"); + Assert.That (handler.Credentials, Is.Null, "Credentials"); // custom, not in HttpClientHandler - Assert.False (handler.DisableCaching, "DisableCaching"); + Assert.That (handler.DisableCaching, Is.False, "DisableCaching"); } } } diff --git a/tests/linker/link sdk/LinkExtraDefsTest.cs b/tests/linker/link sdk/LinkExtraDefsTest.cs index d8329c7abab2..85a510fb9417 100644 --- a/tests/linker/link sdk/LinkExtraDefsTest.cs +++ b/tests/linker/link sdk/LinkExtraDefsTest.cs @@ -26,25 +26,31 @@ public class LinkExtraDefsTest { [Test] public void Corlib () { - Type t = Type.GetType ("System.Security.PermissionSet, " + typeof (int).Assembly.GetName ().Name); - Assert.NotNull (t, "System.Security.PermissionSet"); + var t = Type.GetType ("System.Security.PermissionSet, " + typeof (int).Assembly.GetName ().Name); + Assert.That (t, Is.Not.Null, "System.Security.PermissionSet"); + if (t is null) + throw new InvalidOperationException ("System.Security.PermissionSet"); } [Test] public void System () { - Type t = Type.GetType ("System.Net.Mime.ContentType, System.Net.Mail"); - Assert.NotNull (t, "System.Net.Mime.ContentType"); + var t = Type.GetType ("System.Net.Mime.ContentType, System.Net.Mail"); + Assert.That (t, Is.Not.Null, "System.Net.Mime.ContentType"); + if (t is null) + throw new InvalidOperationException ("System.Net.Mime.ContentType"); // we asked for ParseValue to be preserved - Assert.NotNull (t.GetMethod ("ParseValue", BindingFlags.Instance | BindingFlags.NonPublic), "Parse"); + Assert.That (t.GetMethod ("ParseValue", BindingFlags.Instance | BindingFlags.NonPublic), Is.Not.Null, "Parse"); } #if !__MACOS__ [Test] public void MonoTouch () { - Type t = Type.GetType ("CoreBluetooth.CBUUID, " + typeof (NSObject).Assembly.ToString ()); - Assert.NotNull (t, "[MonoTouch.]CoreBluetooth.CBUUID"); + var t = Type.GetType ("CoreBluetooth.CBUUID, " + typeof (NSObject).Assembly.ToString ()); + Assert.That (t, Is.Not.Null, "[MonoTouch.]CoreBluetooth.CBUUID"); + if (t is null) + throw new InvalidOperationException ("CoreBluetooth.CBUUID"); // check (generated) fields since we instructed the linker to keep them var f = t.GetFields (BindingFlags.NonPublic | BindingFlags.Static); Assert.That (f.Length, Is.Not.EqualTo (0), "fields were preserved"); diff --git a/tests/linker/link sdk/LinkSdkRegressionTest.cs b/tests/linker/link sdk/LinkSdkRegressionTest.cs index dd8890e24975..b75d223ed24a 100644 --- a/tests/linker/link sdk/LinkSdkRegressionTest.cs +++ b/tests/linker/link sdk/LinkSdkRegressionTest.cs @@ -68,8 +68,8 @@ public void Bug205_ExposingIEnumerable () // http://bugzilla.xamarin.com/show_bug.cgi?id=234 public void Bug234_Interlocked () { - string str = null; - Assert.Null (Interlocked.Exchange (ref str, "one"), "Exchange"); + string? str = null; + Assert.That (Interlocked.Exchange (ref str, "one"), Is.Null, "Exchange"); // the above should not crash with System.ExecutionEngineException Assert.That (str, Is.EqualTo ("one"), "one"); } @@ -82,7 +82,7 @@ public void Bug300_Linker_PredicateOf () Dictionary queued = new Dictionary (); KeyValuePair valuePair = queued.FirstOrDefault (); // above should not crash with System.ExecutionEngineException - Assert.NotNull (valuePair); + Assert.That (valuePair, Is.Not.Null); } [Test] @@ -103,7 +103,7 @@ public void Bug769_UnregistredDelegate () var tmp = Class.ThrowOnInitFailure; Class.ThrowOnInitFailure = false; try { - Assert.NotNull (new MKMapViewDelegate ()); + Assert.That (new MKMapViewDelegate (), Is.Not.Null); // the above should not throw an Exception } finally { Class.ThrowOnInitFailure = tmp; @@ -119,11 +119,13 @@ public void Bug865_CanOpenUrl () if (TestRuntime.CheckXcodeVersion (15, 0)) Assert.Ignore ("NSUrl was fixed with Xcode 15.0"); - Assert.False (UIApplication.SharedApplication.CanOpenUrl (null), "null"); +#pragma warning disable CS8625 // Intentional null test case + Assert.That (UIApplication.SharedApplication.CanOpenUrl (null), Is.False, "null"); +#pragma warning restore CS8625 // the above should not throw an ArgumentNullException // and that's important because NSUrl.FromString and NSUrl.ctor(string) differs const string bad_tel = "tel://1800 023 009"; - Assert.Null (NSUrl.FromString (bad_tel), "bad url"); + Assert.That (NSUrl.FromString (bad_tel), Is.Null, "bad url"); // we now throw if `init*` fails Assert.Throws (() => new NSUrl (bad_tel), "ctor, bad url"); } @@ -148,9 +150,9 @@ public void Bug980_AddressBook_NRE () using (ABPeoplePickerNavigationController picker = new ABPeoplePickerNavigationController ()) { // no NRE should occur if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) - Assert.Null (picker.AddressBook); + Assert.That (picker.AddressBook, Is.Null); else - Assert.NotNull (picker.AddressBook); + Assert.That (picker.AddressBook, Is.Not.Null); } } @@ -166,7 +168,7 @@ public void AddressBook_Constants () } #endif // !__MACOS__ TestRuntime.AssertSystemVersion (ApplePlatform.MacCatalyst, 14, 0, throwIfOtherPlatform: false); // The AddressBook framework was introduced in Mac Catalyst 14.0 - Assert.IsNotNull (ABPersonAddressKey.City, "ABPersonAddressKey"); + Assert.That (ABPersonAddressKey.City, Is.Not.Null, "ABPersonAddressKey"); } #endif // HAS_ADDRESSBOOKUI @@ -176,7 +178,7 @@ public void AddressBook_Constants () public void Bug1387_UIEdgeInsets_ToString () { var insets = new UIEdgeInsets (1, 2, 3, 4); - Assert.False (insets.ToString ().Contains ("UIEdgeInsets")); + Assert.That (insets.ToString ().Contains ("UIEdgeInsets"), Is.False); } #endif // !__MACOS__ @@ -191,8 +193,8 @@ void CheckExceptionDetailProperty (PropertyInfo pi) } // to be valid both getter and setter must be present if [DataMember] if (data_member) { - Assert.NotNull (pi.GetGetMethod (true), "get_" + pi.Name); - Assert.NotNull (pi.GetSetMethod (true), "set_" + pi.Name); + Assert.That (pi.GetGetMethod (true), Is.Not.Null, "get_" + pi.Name); + Assert.That (pi.GetSetMethod (true), Is.Not.Null, "set_" + pi.Name); } else { // check well-known [DataMember] switch (pi.Name) { @@ -201,7 +203,7 @@ void CheckExceptionDetailProperty (PropertyInfo pi) case "Message": case "StackTrace": case "Type": - Assert.Fail ("{0} is missing it's [DataMember] attribute", pi.Name); + Assert.Fail ($"{pi.Name} is missing its [DataMember] attribute"); break; } } @@ -240,7 +242,7 @@ public void Bug1790_TimeZoneInfo_Local () // the simulator has complete file access but the device won't have - i.e. we can't depend on it var hasFileAccess = TestRuntime.IsSimulatorOrDesktop; Assert.That (File.Exists ("/etc/localtime"), Is.EqualTo (hasFileAccess), "/etc/localtime"); - Assert.NotNull (TimeZoneInfo.Local, "Local"); + Assert.That (TimeZoneInfo.Local, Is.Not.Null, "Local"); // should not throw a TimeZoneNotFoundException on devices } @@ -284,7 +286,8 @@ public void Bug2000_NSPersistentStoreCoordinator () model.Entities = new NSEntityDescription [1] { entity }; model.SetEntities (model.Entities, String.Empty); - var sqlitePath = Path.Combine (NSFileManager.TemporaryDirectory, $"test-{System.Diagnostics.Process.GetCurrentProcess ().Id}.sqlite"); + var temporaryDirectory = NSFileManager.TemporaryDirectory ?? Path.GetTempPath (); + var sqlitePath = Path.Combine (temporaryDirectory, $"test-{System.Diagnostics.Process.GetCurrentProcess ().Id}.sqlite"); NSUrl url = NSUrl.FromFilename (sqlitePath); try { @@ -292,7 +295,7 @@ public void Bug2000_NSPersistentStoreCoordinator () NSError error; var c = new NSPersistentStoreCoordinator (model); c.AddPersistentStore (NSPersistentStoreCoordinator.SQLiteStoreType, null, url, null, out error); - Assert.IsNull (error, "error"); + Assert.That (error, Is.Null, "error"); } finally { File.Delete (sqlitePath); } @@ -456,12 +459,12 @@ public static HardwareVersion Version { // could not be duplicated on iPad2 (rolf), iPad1 (spouliot), iPodTouch4 (spouliot) public void Hardware_SO () { - Assert.NotNull (DeviceHardware.Version, "Hardware"); + Assert.That (DeviceHardware.Version, Is.Not.Null, "Hardware"); } public class Location { } - private static Location mInstance = null; + private static Location? mInstance = null; [MethodImpl (MethodImplOptions.Synchronized)] public static Location getInstance () @@ -475,7 +478,7 @@ public static Location getInstance () public void Synchronized_3904 () { // crash with LLVM - Assert.NotNull (getInstance (), "Location"); + Assert.That (getInstance (), Is.Not.Null, "Location"); } [Test] @@ -489,7 +492,7 @@ public void ConvertToDouble_4620 () [Test] public void NetworkInterface_4631 () { - Assert.NotNull (NetworkInterface.GetAllNetworkInterfaces ()); + Assert.That (NetworkInterface.GetAllNetworkInterfaces (), Is.Not.Null); } [Test] @@ -501,7 +504,7 @@ public void WebClient_SSL_Leak () try { // note: needs to be executed under Instrument to verify it does not leak string s = wc.DownloadString (url); - Assert.NotNull (s); + Assert.That (s, Is.Not.Null); return; // one url succeeded, that's enough } catch (Exception e) { var msg = $"Url '{url}' failed: {e.ToString ()}"; @@ -517,7 +520,7 @@ public void WebClient_SSL_Leak () public void WebProxy_Leak () { // note: needs to be executed under Instrument to verify it does not leak - Assert.NotNull (global::CoreFoundation.CFNetwork.GetSystemProxySettings (), "should not leak"); + Assert.That (global::CoreFoundation.CFNetwork.GetSystemProxySettings (), Is.Not.Null, "should not leak"); } #endif // !__TVOS__ && !__MACOS__ @@ -549,7 +552,7 @@ public void ForeignKey_650402 () public void Pointer_5200 () { // ensure the linker did not remove the type, which is used by the runtime - Assert.NotNull (GetTypeHelper ("System.Reflection.Pointer, " + typeof (int).Assembly.GetName ().Name)); + Assert.That (GetTypeHelper ("System.Reflection.Pointer, " + typeof (int).Assembly.GetName ().Name), Is.Not.Null); } [Test] @@ -560,7 +563,7 @@ public void LockRecursionException_5311 () class AddedInSilverlight5 : INotifyPropertyChanging { #pragma warning disable CS0067 // The event 'LinkSdkRegressionTest.AddedInSilverlight5.PropertyChanging' is never used - public event PropertyChangingEventHandler PropertyChanging; + public event PropertyChangingEventHandler? PropertyChanging; #pragma warning restore CS0067 } @@ -573,9 +576,17 @@ public void INotifyPropertyChanging_5337 () [Test] public void MonoIOStat_6118 () { - string file = NSBundle.MainBundle.ExecutablePath; + var file = NSBundle.MainBundle.ExecutablePath; + if (string.IsNullOrEmpty (file)) + throw new InvalidOperationException ("No executable path."); DateTime c1 = File.GetCreationTime (file).ToUniversalTime (); - DateTime c2 = (DateTime) NSFileManager.DefaultManager.GetAttributes (file).CreationDate; + var attributes = NSFileManager.DefaultManager.GetAttributes (file); + if (attributes is null) + throw new InvalidOperationException ("No file attributes."); + var creationDate = attributes.CreationDate; + if (creationDate is null) + throw new InvalidOperationException ("No creation date."); + DateTime c2 = (DateTime) creationDate; Assert.That ((c1 - c2).Seconds, Is.LessThan (30), "MonoIOStat"); } @@ -584,13 +595,17 @@ public void ObjectHandleCtor () { Type o = typeof (Object); // this returns a new System.Runtime.Remoting.ObjectHandle which (was) linked away previously - Assert.NotNull (Activator.CreateInstance (o.Assembly.GetName ().Name, o.FullName), "ObjectHandle"); + var assemblyName = o.Assembly.GetName ().Name; + var typeName = o.FullName; + if (string.IsNullOrEmpty (assemblyName) || string.IsNullOrEmpty (typeName)) + throw new InvalidOperationException ("Unable to create an ObjectHandle."); + Assert.That (Activator.CreateInstance (assemblyName, typeName), Is.Not.Null, "ObjectHandle"); } [Test] public void AttributeUsageAttribute_Persistance () { - Assert.IsFalse (Attribute.IsDefined (GetType (), typeof (SerializableAttribute))); + Assert.That (Attribute.IsDefined (GetType (), typeof (SerializableAttribute)), Is.False); } [Test] @@ -614,7 +629,7 @@ public void Update (object o) public void Action_14493 () { var Demo = new Demo_14493 (); - Action a = null; + Action? a = null; a += Demo.Update; a -= Demo.Update; // Crash here } @@ -629,7 +644,7 @@ public void AotGcMemmove_Crash_17284 () { var arr = new AnEnum [16]; var c = new ReadOnlyCollection (arr); - Assert.False (c.Contains (AnEnum.First)); + Assert.That (c.Contains (AnEnum.First), Is.False); } enum MyEnum { @@ -642,7 +657,7 @@ public void Aot_Gsharedvt_21893 () { IList _myValues = new List { MyEnum.AValue }; bool pleaseDontCrash = _myValues.Contains (MyEnum.AnotherValue); - Assert.False (pleaseDontCrash); + Assert.That (pleaseDontCrash, Is.False); } [Test] @@ -674,9 +689,9 @@ string TestFolder (Environment.SpecialFolder folder, bool supported = true, bool string file = Path.Combine (path, "temp.txt"); try { File.WriteAllText (file, "mine"); - Assert.False (readOnly, "!readOnly " + folder); + Assert.That (readOnly, Is.False, "!readOnly " + folder); } catch { - Assert.True (readOnly, "readOnly " + folder); + Assert.That (readOnly, Is.True, "readOnly " + folder); } finally { File.Delete (file); } @@ -710,10 +725,10 @@ void SpecialFolderImpl () { // iOS8 changes the rules of the game var fm = NSFileManager.DefaultManager; - var docs = fm.GetUrls (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User) [0].Path; - var libs = fm.GetUrls (NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User) [0].Path; + var docs = fm.GetUrls (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User) [0].Path ?? ""; + var libs = fm.GetUrls (NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User) [0].Path ?? ""; #if __MACOS__ - var home = Environment.GetEnvironmentVariable ("HOME"); + var home = Environment.GetEnvironmentVariable ("HOME") ?? throw new InvalidOperationException ("No HOME directory."); #endif // note: this test is more interesting on devices because of the sandbox they have @@ -880,7 +895,7 @@ void SpecialFolderImpl () path = TestFolder (Environment.SpecialFolder.Resources, supported: false); #else path = TestFolder (Environment.SpecialFolder.Resources, readOnly: tvos && device); - Assert.True (path.EndsWith ("/Library", StringComparison.Ordinal), "Resources"); + Assert.That (path.EndsWith ("/Library", StringComparison.Ordinal), Is.True, "Resources"); #endif } @@ -889,23 +904,31 @@ void SpecialFolderImpl () public void Events () { using (var tv = new UITextView ()) { - Assert.Null (tv.WeakDelegate, "none"); + Assert.That (tv.WeakDelegate, Is.Null, "none"); // event on UITextView itself - tv.Ended += (object sender, EventArgs e) => { }; + tv.Ended += (object? sender, EventArgs e) => { }; - var t = tv.WeakDelegate.GetType (); + var weakDelegate = tv.WeakDelegate; + Assert.That (weakDelegate, Is.Not.Null, "textview delegate"); + if (weakDelegate is null) + throw new InvalidOperationException ("The text view delegate was not created."); + var t = weakDelegate.GetType (); Assert.That (t.Name, Is.EqualTo ("_UITextViewDelegate"), "textview"); var fi = t.GetField ("editingEnded", BindingFlags.NonPublic | BindingFlags.Instance); - Assert.NotNull (fi, "editingEnded"); - var value = fi.GetValue (tv.WeakDelegate); - Assert.NotNull (value, "value"); + Assert.That (fi, Is.Not.Null, "editingEnded"); + if (fi is null) + throw new InvalidOperationException ("The editingEnded field was not found."); + var value = fi.GetValue (weakDelegate); + Assert.That (value, Is.Not.Null, "value"); // and on the UIScrollView defined one - tv.Scrolled += (object sender, EventArgs e) => { }; + tv.Scrolled += (object? sender, EventArgs e) => { }; // and the existing (initial field) is still set fi = t.GetField ("editingEnded", BindingFlags.NonPublic | BindingFlags.Instance); - Assert.NotNull (fi, "editingEnded/scrollview"); + Assert.That (fi, Is.Not.Null, "editingEnded/scrollview"); + if (fi is null) + throw new InvalidOperationException ("The editingEnded field was not found after scroll hookup."); } } #endif // !__MACOS__ @@ -923,13 +946,17 @@ public void UIButtonSubclass () } #endif // !__MACOS__ - static void CheckILLinkStubbedMethod (MethodInfo m) + static void CheckILLinkStubbedMethod (MethodInfo? m) { // ILLink does not remove the method, but it can "stub" (empty) it - Assert.NotNull (m, "Method not found (null)"); + if (m is null) + throw new InvalidOperationException ("Method not found (null)"); var mb = m.GetMethodBody (); - Assert.NotNull (m, "GetMethodBody"); + if (mb is null) + throw new InvalidOperationException ("GetMethodBody"); var il = mb.GetILAsByteArray (); + if (il is null) + throw new InvalidOperationException ("GetILAsByteArray"); #if DEBUG // means some stuff in addition to the `ret` instruction Assert.That (il.Length, Is.GreaterThan (1), "il > 1"); @@ -971,14 +998,14 @@ public void EnsureDelegateAssignIsNotOverwritingInternalDelegate () [Test] public void MonoRuntime34671 () { - Assert.Null (GetTypeHelper ("Mono.Runtime"), "Mono.Runtime"); + Assert.That (GetTypeHelper ("Mono.Runtime"), Is.Null, "Mono.Runtime"); } [Test] public void TraceListeners36255 () { Trace.Close (); // here too - Assert.NotNull (Trace.Listeners, "C6 had a SecurityPermission call"); + Assert.That (Trace.Listeners, Is.Not.Null, "C6 had a SecurityPermission call"); } #if !__MACOS__ @@ -991,10 +1018,14 @@ public void Github5024 () sc.SetSearchResultsUpdater ((vc) => { }); var a = typeof (UISearchController).AssemblyQualifiedName; + if (string.IsNullOrEmpty (a)) + throw new InvalidOperationException ("No assembly qualified name for UISearchController."); var n = a.Replace ("UIKit.UISearchController", "UIKit.UISearchController+__Xamarin_UISearchResultsUpdating"); var t = Type.GetType (n); - Assert.NotNull (t, "private inner type"); - Assert.IsNotNull (t.GetMethod ("UpdateSearchResultsForSearchController"), "preserved"); + Assert.That (t, Is.Not.Null, "private inner type"); + if (t is null) + throw new InvalidOperationException ("The private inner type was not found."); + Assert.That (t.GetMethod ("UpdateSearchResultsForSearchController"), Is.Not.Null, "preserved"); } } #endif // !__MACOS__ @@ -1003,16 +1034,16 @@ public void Github5024 () public void OldTlsProvider_LinkedOut () { // make test work for classic (monotouch) and unified (iOS, tvOS) - var fqn = typeof (NSObject).AssemblyQualifiedName.Replace ("Foundation.NSObject", "Security.Tls.OldTlsProvider"); - Assert.Null (GetTypeHelper (fqn), "Should not be included"); + var fqn = GetReplacedNSObjectAssemblyQualifiedName ("Security.Tls.OldTlsProvider"); + Assert.That (GetTypeHelper (fqn), Is.Null, "Should not be included"); } [Test] public void AppleTls_Default () { // make test work for classic (monotouch) and unified (iOS, tvOS) - var fqn = typeof (NSObject).AssemblyQualifiedName.Replace ("Foundation.NSObject", "Security.Tls.AppleTlsProvider"); - Assert.Null (GetTypeHelper (fqn), "Should be included"); + var fqn = GetReplacedNSObjectAssemblyQualifiedName ("Security.Tls.AppleTlsProvider"); + Assert.That (GetTypeHelper (fqn), Is.Null, "Should be included"); } #if !__TVOS__ // WebKit isn't available in tvOS @@ -1022,23 +1053,31 @@ public void WebKit_NSProxy () { // a reference to WKWebView will bring the internal NSProxy type var t = typeof (WKWebView); - Assert.NotNull (t, "avoid compiler optimization of unused variable"); - var fqn = typeof (NSObject).AssemblyQualifiedName.Replace ("Foundation.NSObject", "Foundation.NSProxy"); - Assert.NotNull (GetTypeHelper (fqn), fqn); + Assert.That (t, Is.Not.Null, "avoid compiler optimization of unused variable"); + var fqn = GetReplacedNSObjectAssemblyQualifiedName ("Foundation.NSProxy"); + Assert.That (GetTypeHelper (fqn), Is.Not.Null, fqn); } #endif // !__TVOS__ // Fools linker not to keep the type by using it in test check - static Type GetTypeHelper (string name) + static Type? GetTypeHelper (string name) { return Type.GetType (name); } - static Type GetTypeHelper (string name, bool throwOnError) + static Type? GetTypeHelper (string name, bool throwOnError) { return Type.GetType (name, throwOnError); } + static string GetReplacedNSObjectAssemblyQualifiedName (string replacement) + { + var assemblyQualifiedName = typeof (NSObject).AssemblyQualifiedName; + if (string.IsNullOrEmpty (assemblyQualifiedName)) + throw new InvalidOperationException ("No assembly qualified name for NSObject."); + return assemblyQualifiedName.Replace ("Foundation.NSObject", replacement); + } + [Test] // https://github.com/dotnet/macios/issues/6711 public void PreserveINativeObject () @@ -1046,7 +1085,7 @@ public void PreserveINativeObject () // linker will keep the MTAudioProcessingTap type var mta = typeof (MediaToolbox.MTAudioProcessingTap); // and we check that it still implement INativeObject - Assert.IsNotNull (mta.GetInterface ("ObjCRuntime.INativeObject"), "INativeObject"); + Assert.That (mta.GetInterface ("ObjCRuntime.INativeObject"), Is.Not.Null, "INativeObject"); } [Test] @@ -1054,7 +1093,7 @@ public void PreserveINativeObject () public void AsQueryable_Enumerable () { var list = new List { "hello hello" }; - Assert.NotNull (list.AsQueryable ().GroupBy (x => x).FirstOrDefault ()?.FirstOrDefault (), "Enumerable"); + Assert.That (list.AsQueryable ().GroupBy (x => x).FirstOrDefault ()?.FirstOrDefault (), Is.Not.Null, "Enumerable"); } public class CustomIdentity : IIdentity { @@ -1073,7 +1112,11 @@ public class CustomPrincipal : IPrincipal { public void Principal () { Thread.CurrentPrincipal = new CustomPrincipal (); - Assert.That (Thread.CurrentPrincipal.Identity.Name, Is.EqualTo ("abc"), "Name"); + var identity = Thread.CurrentPrincipal?.Identity; + Assert.That (identity, Is.Not.Null, "Identity"); + if (identity is null) + throw new InvalidOperationException ("No current principal identity."); + Assert.That (identity.Name, Is.EqualTo ("abc"), "Name"); } [Test] diff --git a/tests/linker/link sdk/LinkSdkTest.cs b/tests/linker/link sdk/LinkSdkTest.cs index 2e8b677c6020..1b55662ae8c1 100644 --- a/tests/linker/link sdk/LinkSdkTest.cs +++ b/tests/linker/link sdk/LinkSdkTest.cs @@ -6,8 +6,10 @@ public class LinkSdkTest { static void Check (string calendarName, bool present) { var type = Type.GetType ("System.Globalization." + calendarName); - bool success = present == (type is not null); - Assert.AreEqual (present, type is not null, calendarName); + if (present) + Assert.That (type, Is.Not.Null, calendarName); + else + Assert.That (type, Is.Null, calendarName); } [Test] diff --git a/tests/linker/link sdk/LocaleTest.cs b/tests/linker/link sdk/LocaleTest.cs index fa4e1fef6261..1e7f965a9923 100644 --- a/tests/linker/link sdk/LocaleTest.cs +++ b/tests/linker/link sdk/LocaleTest.cs @@ -33,13 +33,13 @@ void DictComparer () var n1 = "SEARCHFIELDS"; var n2 = "Searchfields"; - Assert.True (string.Equals (n1, n2, StringComparison.OrdinalIgnoreCase), "string equality"); + Assert.That (string.Equals (n1, n2, StringComparison.OrdinalIgnoreCase), Is.True, "string equality"); var dict = new Dictionary (StringComparer.OrdinalIgnoreCase); dict [n1] = "test"; - string result; - Assert.True (dict.TryGetValue (n2, out result), "dictionary value"); + string? result; + Assert.That (dict.TryGetValue (n2, out result), Is.True, "dictionary value"); } } } diff --git a/tests/linker/link sdk/OptimizeGeneratedCodeTest.cs b/tests/linker/link sdk/OptimizeGeneratedCodeTest.cs index 58623aec8774..37516ce8638f 100644 --- a/tests/linker/link sdk/OptimizeGeneratedCodeTest.cs +++ b/tests/linker/link sdk/OptimizeGeneratedCodeTest.cs @@ -66,7 +66,7 @@ public class OptimizeGeneratedCodeTest : BaseOptimizeGeneratedCodeTest { public void IsNewRefcountEnabled () { using (UIWebView wv = new UIWebView ()) { - Assert.Null (wv.Request, "IsNewRefcountEnabled"); + Assert.That (wv.Request, Is.Null, "IsNewRefcountEnabled"); } } @@ -90,9 +90,9 @@ public void SingleRuntimeArchDevice () { var empty = CGRect.Empty; using (UIView v = new UIView ()) - using (UIFont font = UIFont.SystemFontOfSize (12f)) { + using (UIFont font = UIFont.SystemFontOfSize (12f)!) { var size = "MonoTouch".StringSize (font); - Assert.False (size.IsEmpty, "!Empty"); + Assert.That (size.IsEmpty, Is.False, "!Empty"); } } #endif // !__TVOS__ @@ -107,7 +107,7 @@ public void DoubleRuntimeArchDevice () { var empty = CGSize.Empty; using (UIView v = new UIView ()) { - Assert.True (v.SizeThatFits (empty).IsEmpty, "Empty"); + Assert.That (v.SizeThatFits (empty).IsEmpty, Is.True, "Empty"); } } #endif // !__MACOS__ @@ -152,7 +152,7 @@ public void FinallyTest () // bug #26415 FinallyTestMethod (); - Assert.IsTrue (finally_invoked); + Assert.That (finally_invoked, Is.True); } bool finally_invoked; diff --git a/tests/linker/link sdk/PclTest.cs b/tests/linker/link sdk/PclTest.cs index 9737f1ecaadb..9224bf9a6b90 100644 --- a/tests/linker/link sdk/PclTest.cs +++ b/tests/linker/link sdk/PclTest.cs @@ -23,32 +23,32 @@ public void System () const string url = "http://www.google.com"; Uri uri = new Uri (url); - Assert.False (this is ICommand, "ICommand"); + Assert.That (this is ICommand, Is.False, "ICommand"); try { HttpWebRequest hwr = WebRequest.CreateHttp (uri); try { - Assert.True (hwr.SupportsCookieContainer, "SupportsCookieContainer"); + Assert.That (hwr.SupportsCookieContainer, Is.True, "SupportsCookieContainer"); } catch (NotImplementedException) { // feature is not available, but the symbol itself is needed } WebResponse wr = hwr.GetResponse (); try { - Assert.True (wr.SupportsHeaders, "SupportsHeaders"); + Assert.That (wr.SupportsHeaders, Is.True, "SupportsHeaders"); } catch (NotImplementedException) { // feature is not available, but the symbol itself is needed } wr.Dispose (); try { - Assert.NotNull (WebRequest.CreateHttp (url)); + Assert.That (WebRequest.CreateHttp (url), Is.Not.Null); } catch (NotImplementedException) { // feature is not available, but the symbol itself is needed } try { - Assert.NotNull (WebRequest.CreateHttp (uri)); + Assert.That (WebRequest.CreateHttp (uri), Is.Not.Null); } catch (NotImplementedException) { // feature is not available, but the symbol itself is needed } diff --git a/tests/linker/link sdk/ReflectionTest.cs b/tests/linker/link sdk/ReflectionTest.cs index 9965f33878ca..96886bb2449e 100644 --- a/tests/linker/link sdk/ReflectionTest.cs +++ b/tests/linker/link sdk/ReflectionTest.cs @@ -13,14 +13,14 @@ public void ParameterInfoName () { // linker will disable the metadata removal optimization if that property is used by user code // however it's used inside mscorlib.dll (and SDK) so it cannot be checked while testing - //Assert.Null (typeof (ParameterInfo).GetProperty ("Name"), "Name"); + //Assert.That (typeof (ParameterInfo).GetProperty ("Name"), Is.Null, "Name"); // Call the method we want to test, so that the linker doesn't remove it. // The method needs to be in a different class, because this class has the Preserve attribute, // and the linker will keep the parameter names inside such classes. ReflectionTestClass.MethodWithParameters (null, 0); - var mi = GetType ().Assembly.GetType ("Linker.Shared.Reflection.ReflectionTestClass").GetMethod ("MethodWithParameters"); + var mi = GetType ().Assembly.GetType ("Linker.Shared.Reflection.ReflectionTestClass")!.GetMethod ("MethodWithParameters")!; var p = mi.GetParameters (); #if DEBUG // dotnet has adopted (and adapted) the metadata reducer and runs it on it's own conditions @@ -42,7 +42,7 @@ public void ParameterInfoName () } class ReflectionTestClass { - public static void MethodWithParameters (string firstParameter, int secondParameter) + public static void MethodWithParameters (string? firstParameter, int secondParameter) { } } diff --git a/tests/linker/link sdk/TaskTest.cs b/tests/linker/link sdk/TaskTest.cs index b614bc21e4be..2a264122aa0a 100644 --- a/tests/linker/link sdk/TaskTest.cs +++ b/tests/linker/link sdk/TaskTest.cs @@ -21,12 +21,12 @@ public void ContinueWithDifferentOptionsAreCanceledTest () mre.Set (); contSuccess.Wait (100); - Assert.True (contSuccess.IsCompleted, "contSuccess.IsCompleted"); - Assert.True (contFailed.IsCompleted, "contFailed.IsCompleted"); - Assert.True (contCanceled.IsCompleted, "contCanceled.IsCompleted"); - Assert.False (contSuccess.IsCanceled, "contSuccess.IsCanceled"); - Assert.True (contFailed.IsCanceled, "contFailed.IsCanceled"); - Assert.True (contCanceled.IsCanceled, "contCanceled.IsCanceled"); + Assert.That (contSuccess.IsCompleted, Is.True, "contSuccess.IsCompleted"); + Assert.That (contFailed.IsCompleted, Is.True, "contFailed.IsCompleted"); + Assert.That (contCanceled.IsCompleted, Is.True, "contCanceled.IsCompleted"); + Assert.That (contSuccess.IsCanceled, Is.False, "contSuccess.IsCanceled"); + Assert.That (contFailed.IsCanceled, Is.True, "contFailed.IsCanceled"); + Assert.That (contCanceled.IsCanceled, Is.True, "contCanceled.IsCanceled"); } [Test] @@ -45,7 +45,7 @@ public void ContinueWhenAll_WithMixedCompletionState () mre.Set (); cont.Wait (200); - Assert.True (ran, "ran"); + Assert.That (ran, Is.True, "ran"); Assert.That (cont.Status, Is.EqualTo (TaskStatus.RanToCompletion), "Status"); } } diff --git a/tests/linker/link sdk/dotnet/shared.csproj b/tests/linker/link sdk/dotnet/shared.csproj index 334ddf463a04..464d06986f00 100644 --- a/tests/linker/link sdk/dotnet/shared.csproj +++ b/tests/linker/link sdk/dotnet/shared.csproj @@ -21,10 +21,6 @@ $(NoWarn);IL2026;IL2032;IL2057;IL2070;IL2075;IL2080;IL2111 - - - true - Nullable @@ -77,14 +73,6 @@ - - - - - - - - - + diff --git a/tests/linker/trimmode copy/dotnet/shared.csproj b/tests/linker/trimmode copy/dotnet/shared.csproj index d2c484bbde68..b27fdf881492 100644 --- a/tests/linker/trimmode copy/dotnet/shared.csproj +++ b/tests/linker/trimmode copy/dotnet/shared.csproj @@ -12,10 +12,6 @@ $(NoWarn);IL2057 - - - true - Nullable @@ -57,15 +53,7 @@ - - - - - - - - - + diff --git a/tests/linker/trimmode link/dotnet/shared.csproj b/tests/linker/trimmode link/dotnet/shared.csproj index 4e9f12dba660..48401810a36d 100644 --- a/tests/linker/trimmode link/dotnet/shared.csproj +++ b/tests/linker/trimmode link/dotnet/shared.csproj @@ -28,10 +28,6 @@ $(NoWarn);IL2026;IL2032;IL2057;IL2070;IL2075;IL2080;IL2111 - - - true - Nullable @@ -90,14 +86,12 @@ - - - - - - - - - + + + + + + + diff --git a/tests/mmptest/mmptest.csproj b/tests/mmptest/mmptest.csproj index f56e77b4e764..a28ba735e604 100644 --- a/tests/mmptest/mmptest.csproj +++ b/tests/mmptest/mmptest.csproj @@ -11,7 +11,6 @@ Xamarin.MMP.Tests mmptest v4.7.2 - preview true diff --git a/tests/monotouch-test/ARKit/ARAnchorTest.cs b/tests/monotouch-test/ARKit/ARAnchorTest.cs index 567a7638839d..435fb2c94317 100644 --- a/tests/monotouch-test/ARKit/ARAnchorTest.cs +++ b/tests/monotouch-test/ARKit/ARAnchorTest.cs @@ -32,7 +32,7 @@ public void Setup () public void MarshallingTest () { var faceAnchor = new ARAnchor ("My Anchor", MatrixFloat4x4.Identity); - Assert.AreEqual (MatrixFloat4x4.Identity, faceAnchor.Transform, "Transform"); + Assert.That (faceAnchor.Transform, Is.EqualTo (MatrixFloat4x4.Identity), "Transform"); } } } diff --git a/tests/monotouch-test/ARKit/ARConfigurationTest.cs b/tests/monotouch-test/ARKit/ARConfigurationTest.cs index 567cf41d6182..a2f03498a874 100644 --- a/tests/monotouch-test/ARKit/ARConfigurationTest.cs +++ b/tests/monotouch-test/ARKit/ARConfigurationTest.cs @@ -21,17 +21,17 @@ public void Setup () [Test] public void GetSupportedVideoFormats_9_3 () { - Assert.NotNull (ARWorldTrackingConfiguration.GetSupportedVideoFormats (), "ARWorldTrackingConfiguration"); - Assert.NotNull (AROrientationTrackingConfiguration.GetSupportedVideoFormats (), "AROrientationTrackingConfiguration"); - Assert.NotNull (ARFaceTrackingConfiguration.GetSupportedVideoFormats (), "ARFaceTrackingConfiguration"); + Assert.That (ARWorldTrackingConfiguration.GetSupportedVideoFormats (), Is.Not.Null, "ARWorldTrackingConfiguration"); + Assert.That (AROrientationTrackingConfiguration.GetSupportedVideoFormats (), Is.Not.Null, "AROrientationTrackingConfiguration"); + Assert.That (ARFaceTrackingConfiguration.GetSupportedVideoFormats (), Is.Not.Null, "ARFaceTrackingConfiguration"); } [Test] public void GetSupportedVideoFormats_10_0 () { TestRuntime.AssertXcodeVersion (10, 0); - Assert.NotNull (ARImageTrackingConfiguration.GetSupportedVideoFormats (), "ARImageTrackingConfiguration"); - Assert.NotNull (ARObjectScanningConfiguration.GetSupportedVideoFormats (), "ARObjectScanningConfiguration"); + Assert.That (ARImageTrackingConfiguration.GetSupportedVideoFormats (), Is.Not.Null, "ARImageTrackingConfiguration"); + Assert.That (ARObjectScanningConfiguration.GetSupportedVideoFormats (), Is.Not.Null, "ARObjectScanningConfiguration"); } } } diff --git a/tests/monotouch-test/ARKit/AREnvironmentProbeAnchorTest.cs b/tests/monotouch-test/ARKit/AREnvironmentProbeAnchorTest.cs index 186da1aebbc3..9b7e0923eaee 100644 --- a/tests/monotouch-test/ARKit/AREnvironmentProbeAnchorTest.cs +++ b/tests/monotouch-test/ARKit/AREnvironmentProbeAnchorTest.cs @@ -33,20 +33,20 @@ public void Setup () public void MarshallingTest () { var probeAnchor = new AREnvironmentProbeAnchor (MatrixFloat4x4.Identity, new VectorFloat3 (1, 1, 1)); - Assert.AreEqual (MatrixFloat4x4.Identity, probeAnchor.Transform, "Transform"); + Assert.That (probeAnchor.Transform, Is.EqualTo (MatrixFloat4x4.Identity), "Transform"); // broken since Xcode 12 on simulator (only), fixed in simulator in Xcode 14 if ((Runtime.Arch == Arch.DEVICE) || !TestRuntime.CheckXcodeVersion (12, 0) || TestRuntime.CheckXcodeVersion (14, 0)) - Assert.AreEqual (new VectorFloat3 (1, 1, 1), probeAnchor.Extent, "Extent"); + Assert.That (probeAnchor.Extent, Is.EqualTo (new VectorFloat3 (1, 1, 1)), "Extent"); } [Test] public void MarshallingTest2 () { var probeAnchorWithName = new AREnvironmentProbeAnchor ("My Anchor", MatrixFloat4x4.Identity, new VectorFloat3 (1, 1, 1)); - Assert.AreEqual (MatrixFloat4x4.Identity, probeAnchorWithName.Transform, "Transform"); + Assert.That (probeAnchorWithName.Transform, Is.EqualTo (MatrixFloat4x4.Identity), "Transform"); // broken since Xcode 12 on simulator (only), fixed in simulator in Xcode 14 if ((Runtime.Arch == Arch.DEVICE) || !TestRuntime.CheckXcodeVersion (12, 0) || TestRuntime.CheckXcodeVersion (14, 0)) - Assert.AreEqual (new VectorFloat3 (1, 1, 1), probeAnchorWithName.Extent, "Extent"); + Assert.That (probeAnchorWithName.Extent, Is.EqualTo (new VectorFloat3 (1, 1, 1)), "Extent"); } } } diff --git a/tests/monotouch-test/ARKit/ARFaceGeometryTest.cs b/tests/monotouch-test/ARKit/ARFaceGeometryTest.cs index b69229252223..9f07f331ec52 100644 --- a/tests/monotouch-test/ARKit/ARFaceGeometryTest.cs +++ b/tests/monotouch-test/ARKit/ARFaceGeometryTest.cs @@ -93,8 +93,8 @@ public void VerticesTest () { var face = new ARFaceGeometryPoker (); var vertices = face.GetVertices (); - Assert.AreEqual (new VectorFloat3 (1, 2, 3), vertices [0], "Vertex 1"); - Assert.AreEqual (new VectorFloat3 (4, 5, 6), vertices [1], "Vertex 2"); + Assert.That (vertices [0], Is.EqualTo (new VectorFloat3 (1, 2, 3)), "Vertex 1"); + Assert.That (vertices [1], Is.EqualTo (new VectorFloat3 (4, 5, 6)), "Vertex 2"); } [Test] @@ -102,15 +102,15 @@ public void TextureCoordinatesTest () { var face = new ARFaceGeometryPoker (); var textureCoordinates = face.GetTextureCoordinates (); - Assert.AreEqual (new VectorFloat2 (1, 2), textureCoordinates [0], "Texture Coordinates 1"); - Assert.AreEqual (new VectorFloat2 (3, 4), textureCoordinates [1], "Texture Coordinates 2"); + Assert.That (textureCoordinates [0], Is.EqualTo (new VectorFloat2 (1, 2)), "Texture Coordinates 1"); + Assert.That (textureCoordinates [1], Is.EqualTo (new VectorFloat2 (3, 4)), "Texture Coordinates 2"); } [Test] public void TriangleIndicesTest () { var face = new ARFaceGeometryPoker (); - Assert.AreEqual (new short [] { 1, 2, 3, 4, 5, 6 }, face.GetTriangleIndices ()); + Assert.That (face.GetTriangleIndices (), Is.EqualTo (new short [] { 1, 2, 3, 4, 5, 6 })); } } } diff --git a/tests/monotouch-test/ARKit/ARPlaneGeometryTest.cs b/tests/monotouch-test/ARKit/ARPlaneGeometryTest.cs index 7faf0ea2ae5e..bddb5fb24577 100644 --- a/tests/monotouch-test/ARKit/ARPlaneGeometryTest.cs +++ b/tests/monotouch-test/ARKit/ARPlaneGeometryTest.cs @@ -107,8 +107,8 @@ public void VerticesTest () { var face = new ARPlaneGeometryPoker (); var vertices = face.GetVertices (); - Assert.AreEqual (new VectorFloat3 (1, 2, 3), vertices [0], "Vertex 1"); - Assert.AreEqual (new VectorFloat3 (4, 5, 6), vertices [1], "Vertex 2"); + Assert.That (vertices [0], Is.EqualTo (new VectorFloat3 (1, 2, 3)), "Vertex 1"); + Assert.That (vertices [1], Is.EqualTo (new VectorFloat3 (4, 5, 6)), "Vertex 2"); } [Test] @@ -116,15 +116,15 @@ public void TextureCoordinatesTest () { var face = new ARPlaneGeometryPoker (); var textureCoordinates = face.GetTextureCoordinates (); - Assert.AreEqual (new VectorFloat2 (1, 2), textureCoordinates [0], "Texture Coordinates 1"); - Assert.AreEqual (new VectorFloat2 (3, 4), textureCoordinates [1], "Texture Coordinates 2"); + Assert.That (textureCoordinates [0], Is.EqualTo (new VectorFloat2 (1, 2)), "Texture Coordinates 1"); + Assert.That (textureCoordinates [1], Is.EqualTo (new VectorFloat2 (3, 4)), "Texture Coordinates 2"); } [Test] public void TriangleIndicesTest () { var face = new ARPlaneGeometryPoker (); - Assert.AreEqual (new short [] { 1, 2, 3, 4, 5, 6 }, face.GetTriangleIndices ()); + Assert.That (face.GetTriangleIndices (), Is.EqualTo (new short [] { 1, 2, 3, 4, 5, 6 })); } [Test] @@ -134,8 +134,8 @@ public void BoundaryVerticesTest () var face = new ARPlaneGeometryPoker (); var boundaryVertices = face.GetBoundaryVertices (); - Assert.AreEqual (new VectorFloat3 (1, 2, 3), boundaryVertices [0], "Boundary Vertex 1"); - Assert.AreEqual (new VectorFloat3 (4, 5, 6), boundaryVertices [1], "Boundary Vertex 2"); + Assert.That (boundaryVertices [0], Is.EqualTo (new VectorFloat3 (1, 2, 3)), "Boundary Vertex 1"); + Assert.That (boundaryVertices [1], Is.EqualTo (new VectorFloat3 (4, 5, 6)), "Boundary Vertex 2"); } } } diff --git a/tests/monotouch-test/ARKit/ARPointCloudTest.cs b/tests/monotouch-test/ARKit/ARPointCloudTest.cs index f3a1bb31f5e4..ecdf00083b70 100644 --- a/tests/monotouch-test/ARKit/ARPointCloudTest.cs +++ b/tests/monotouch-test/ARKit/ARPointCloudTest.cs @@ -83,8 +83,8 @@ public void PointsTest () var cloud = new ARPointCloudPoker (); var points = cloud.Points; - Assert.AreEqual (new VectorFloat3 (1, 2, 3), cloud.Points [0]); - Assert.AreEqual (new VectorFloat3 (4, 5, 6), cloud.Points [1]); + Assert.That (cloud.Points [0], Is.EqualTo (new VectorFloat3 (1, 2, 3))); + Assert.That (cloud.Points [1], Is.EqualTo (new VectorFloat3 (4, 5, 6))); } [Test] @@ -93,8 +93,8 @@ public void IdentifiersTest () var cloud = new ARPointCloudPoker (); var points = cloud.Identifiers; - Assert.AreEqual (0, cloud.Identifiers [0]); - Assert.AreEqual (1, cloud.Identifiers [1]); + Assert.That (cloud.Identifiers [0], Is.EqualTo (0)); + Assert.That (cloud.Identifiers [1], Is.EqualTo (1)); } } } diff --git a/tests/monotouch-test/ARKit/ARReferenceObjectTest.cs b/tests/monotouch-test/ARKit/ARReferenceObjectTest.cs index b4e1e373fbbd..895efaecc744 100644 --- a/tests/monotouch-test/ARKit/ARReferenceObjectTest.cs +++ b/tests/monotouch-test/ARKit/ARReferenceObjectTest.cs @@ -35,12 +35,12 @@ public void MarshallingTest () TestRuntime.AssertNotSimulator (); // The Objective-C constructor is just stubbed out to return NULL in the simulator, so this test only works on device. var model3 = new ARReferenceObject (NSUrl.FromFilename ("Model3.arobject"), out NSError error); - Assert.IsNull (error, "Error"); - Assert.AreEqual ("Model3", model3.Name, "Name"); - Assert.NotNull (model3.Center, "Center"); - Assert.NotNull (model3.Extent, "Extent"); - Assert.NotNull (model3.Scale, "Scale"); - Assert.NotNull (model3.ApplyTransform (MatrixFloat4x4.Identity), "ApplyTransform"); + Assert.That (error, Is.Null, "Error"); + Assert.That (model3.Name, Is.EqualTo ("Model3"), "Name"); + Assert.That (model3.Center, Is.Not.Null, "Center"); + Assert.That (model3.Extent, Is.Not.Null, "Extent"); + Assert.That (model3.Scale, Is.Not.Null, "Scale"); + Assert.That (model3.ApplyTransform (MatrixFloat4x4.Identity), Is.Not.Null, "ApplyTransform"); } } } diff --git a/tests/monotouch-test/ARKit/ARSkeleton2DTest.cs b/tests/monotouch-test/ARKit/ARSkeleton2DTest.cs index 8155bf910b39..b573b1360e54 100644 --- a/tests/monotouch-test/ARKit/ARSkeleton2DTest.cs +++ b/tests/monotouch-test/ARKit/ARSkeleton2DTest.cs @@ -67,8 +67,8 @@ public void JointLandmarksTest () var skeleton = new ARSkeleton2DPoker (); var landmarks = skeleton.JointLandmarks; - Assert.AreEqual (new Vector2 (1, 2), landmarks [0]); - Assert.AreEqual (new Vector2 (3, 4), landmarks [1]); + Assert.That (landmarks [0], Is.EqualTo (new Vector2 (1, 2))); + Assert.That (landmarks [1], Is.EqualTo (new Vector2 (3, 4))); } } } diff --git a/tests/monotouch-test/ARKit/ARSkeleton3DTest.cs b/tests/monotouch-test/ARKit/ARSkeleton3DTest.cs index b0c41d273dd0..121ac5c1aee9 100644 --- a/tests/monotouch-test/ARKit/ARSkeleton3DTest.cs +++ b/tests/monotouch-test/ARKit/ARSkeleton3DTest.cs @@ -80,8 +80,8 @@ public void JointModelTransformsTest () var skeleton = new ARSkeleton3DPoker (); var landmarks = skeleton.JointModelTransforms; - Assert.AreEqual (Matrix4.Identity, landmarks [0]); - Assert.AreEqual (Matrix4.Identity, landmarks [1]); + Assert.That (landmarks [0], Is.EqualTo (Matrix4.Identity)); + Assert.That (landmarks [1], Is.EqualTo (Matrix4.Identity)); } [Test] @@ -90,8 +90,8 @@ public void JointLocalTransformsTest () var skeleton = new ARSkeleton3DPoker (); var landmarks = skeleton.JointLocalTransforms; - Assert.AreEqual (Matrix4.Identity, landmarks [0]); - Assert.AreEqual (Matrix4.Identity, landmarks [1]); + Assert.That (landmarks [0], Is.EqualTo (Matrix4.Identity)); + Assert.That (landmarks [1], Is.EqualTo (Matrix4.Identity)); } } } diff --git a/tests/monotouch-test/ARKit/ARSkeletonTest.cs b/tests/monotouch-test/ARKit/ARSkeletonTest.cs index 28d6eddd37c2..527160ead094 100644 --- a/tests/monotouch-test/ARKit/ARSkeletonTest.cs +++ b/tests/monotouch-test/ARKit/ARSkeletonTest.cs @@ -21,7 +21,7 @@ public void Setup () public void UnknownPointTest () { using (var notKnownPoint = new NSString ("nariz")) - Assert.IsNull (ARSkeleton.CreateJointName (notKnownPoint)); + Assert.That (ARSkeleton.CreateJointName (notKnownPoint), Is.Null); } } diff --git a/tests/monotouch-test/AVFoundation/AVAssetImageGeneratorTest.cs b/tests/monotouch-test/AVFoundation/AVAssetImageGeneratorTest.cs index 6d3b9c2c035e..38140b3ef032 100644 --- a/tests/monotouch-test/AVFoundation/AVAssetImageGeneratorTest.cs +++ b/tests/monotouch-test/AVFoundation/AVAssetImageGeneratorTest.cs @@ -26,11 +26,11 @@ public void Defaults () using (NSUrl video_url = NSUrl.FromFilename (video_asset_path)) using (AVAsset video_asset = AVAsset.FromUrl (video_url)) using (AVAssetImageGenerator aig = new AVAssetImageGenerator (video_asset)) { - Assert.Null (aig.ApertureMode, "ApertureMode"); - Assert.False (aig.AppliesPreferredTrackTransform, "AppliesPreferredTrackTransform"); + Assert.That (aig.ApertureMode, Is.Null, "ApertureMode"); + Assert.That (aig.AppliesPreferredTrackTransform, Is.False, "AppliesPreferredTrackTransform"); Assert.That (aig.MaximumSize, Is.EqualTo (CGSize.Empty), "MaximumSize"); - Assert.True (aig.RequestedTimeToleranceAfter.IsPositiveInfinity, "RequestedTimeToleranceAfter"); - Assert.True (aig.RequestedTimeToleranceBefore.IsPositiveInfinity, "RequestedTimeToleranceBefore"); + Assert.That (aig.RequestedTimeToleranceAfter.IsPositiveInfinity, Is.True, "RequestedTimeToleranceAfter"); + Assert.That (aig.RequestedTimeToleranceBefore.IsPositiveInfinity, Is.True, "RequestedTimeToleranceBefore"); } } @@ -42,7 +42,7 @@ public void AppliesPreferredTrackTransform () using (AVAssetImageGenerator aig = new AVAssetImageGenerator (video_asset)) { // setter was missing see https://bugzilla.xamarin.com/show_bug.cgi?id=5216 aig.AppliesPreferredTrackTransform = true; - Assert.True (aig.AppliesPreferredTrackTransform, "AppliesPreferredTrackTransform"); + Assert.That (aig.AppliesPreferredTrackTransform, Is.True, "AppliesPreferredTrackTransform"); } } @@ -57,9 +57,9 @@ public void CopyCGImageAtTime () CMTime actual; NSError error; var img = aig.CopyCGImageAtTime (CMTime.Zero, out actual, out error); - Assert.NotNull (img, "CopyCGImageAtTime"); - Assert.False (actual.IsInvalid, "actual"); - Assert.Null (error, "error"); + Assert.That (img, Is.Not.Null, "CopyCGImageAtTime"); + Assert.That (actual.IsInvalid, Is.False, "actual"); + Assert.That (error, Is.Null, "error"); } } @@ -74,9 +74,9 @@ public void CopyCGImageAtTime_Invalid () CMTime actual; NSError error; var img = aig.CopyCGImageAtTime (CMTime.Zero, out actual, out error); - Assert.Null (img, "missing"); - Assert.True (actual.IsInvalid, "actual"); - Assert.NotNull (error, "error"); + Assert.That (img, Is.Null, "missing"); + Assert.That (actual.IsInvalid, Is.True, "actual"); + Assert.That (error, Is.Not.Null, "error"); } } @@ -107,8 +107,8 @@ public void GenerateCGImagesAsynchronously () IsBackground = true, }; thread.Start (); - Assert.True (mre.WaitOne (2000), "wait"); - Assert.True (handled, "handled"); + Assert.That (mre.WaitOne (2000), Is.True, "wait"); + Assert.That (handled, Is.True, "handled"); } void handler (CMTime requestedTime, IntPtr imageRef, CMTime actualTime, AVAssetImageGeneratorResult result, NSError error) diff --git a/tests/monotouch-test/AVFoundation/AVAudioConverterPrimeInfoTest.cs b/tests/monotouch-test/AVFoundation/AVAudioConverterPrimeInfoTest.cs index b789af1280ed..ddf05a857591 100644 --- a/tests/monotouch-test/AVFoundation/AVAudioConverterPrimeInfoTest.cs +++ b/tests/monotouch-test/AVFoundation/AVAudioConverterPrimeInfoTest.cs @@ -13,8 +13,8 @@ public void ConstructorTest () var info = new AVAudioConverterPrimeInfo (leading, trailing); - Assert.AreEqual (leading, info.LeadingFrames, "Wrong LeadingFrames value."); - Assert.AreEqual (trailing, info.TrailingFrames, "Wrong TrailingFrames value."); + Assert.That (info.LeadingFrames, Is.EqualTo (leading), "Wrong LeadingFrames value."); + Assert.That (info.TrailingFrames, Is.EqualTo (trailing), "Wrong TrailingFrames value."); } [Test] @@ -25,9 +25,9 @@ public void AreEqualTrueTest () var info1 = new AVAudioConverterPrimeInfo (leading, trainling); var info2 = new AVAudioConverterPrimeInfo (leading, trainling); - Assert.True (info1 == info2, "info1 == info2"); - Assert.True (info1.Equals (info2), "info1.Equals (info2)"); - Assert.False (info1 != info2, "info1 != info2"); + Assert.That (info1 == info2, Is.True, "info1 == info2"); + Assert.That (info1.Equals (info2), Is.True, "info1.Equals (info2)"); + Assert.That (info1 != info2, Is.False, "info1 != info2"); } [Test] @@ -35,9 +35,9 @@ public void AreEqualFalseTest () { var info1 = new AVAudioConverterPrimeInfo (2, 30); var info2 = new AVAudioConverterPrimeInfo (info1.LeadingFrames * 2, info1.TrailingFrames * 2); - Assert.False (info1 == info2, "info1 == info2"); - Assert.False (info1.Equals (info2), "info1.Equals (info2)"); - Assert.True (info1 != info2, "info1 != info2"); + Assert.That (info1 == info2, Is.False, "info1 == info2"); + Assert.That (info1.Equals (info2), Is.False, "info1.Equals (info2)"); + Assert.That (info1 != info2, Is.True, "info1 != info2"); } [Test] @@ -45,7 +45,7 @@ public void AreEqualDiffType () { var info = new AVAudioConverterPrimeInfo (2, 20); var str = new NSString ("Foo"); - Assert.False (info.Equals ((object) str)); + Assert.That (info.Equals ((object) str), Is.False); } } } diff --git a/tests/monotouch-test/AVFoundation/AVAudioFormatTest.cs b/tests/monotouch-test/AVFoundation/AVAudioFormatTest.cs index f03f7a517c2a..2db586e09aed 100644 --- a/tests/monotouch-test/AVFoundation/AVAudioFormatTest.cs +++ b/tests/monotouch-test/AVFoundation/AVAudioFormatTest.cs @@ -25,7 +25,7 @@ public void TestEqualOperatorSameInstace () { using (var format = new AVAudioFormat ()) #pragma warning disable CS1718 // warning CS1718: Comparison made to same variable; did you mean to compare something else? - Assert.IsTrue (format == format, "format == format"); + Assert.That (format == format, Is.True, "format == format"); #pragma warning restore } @@ -33,12 +33,12 @@ public void TestEqualOperatorSameInstace () public void TestEqualOperatorNull () { using (var format = new AVAudioFormat ()) { - Assert.IsFalse (format == null, "format == null"); - Assert.IsFalse (null == format, "null == format"); + Assert.That (format == null, Is.False, "format == null"); + Assert.That (null == format, Is.False, "null == format"); } using (AVAudioFormat nullFormat = null) { - Assert.IsTrue (nullFormat == null, "nullFormat == null"); - Assert.IsTrue (null == nullFormat, "null == nullFormat"); + Assert.That (nullFormat == null, Is.True, "nullFormat == null"); + Assert.That (null == nullFormat, Is.True, "null == nullFormat"); } } @@ -46,12 +46,12 @@ public void TestEqualOperatorNull () public void TestNotEqualOperatorNull () { using (var format = new AVAudioFormat ()) { - Assert.IsTrue (format != null, "format != null"); - Assert.IsTrue (null != format, "null != format"); + Assert.That (format != null, Is.True, "format != null"); + Assert.That (null != format, Is.True, "null != format"); } using (AVAudioFormat nullFormat = null) { - Assert.IsFalse (nullFormat != null, "nullFormat != null"); - Assert.IsFalse (null != nullFormat, "null != nullFormat"); + Assert.That (nullFormat != null, Is.False, "nullFormat != null"); + Assert.That (null != nullFormat, Is.False, "null != nullFormat"); } } @@ -61,14 +61,14 @@ public void StreamDescription () { var format = new AVAudioFormat (AVAudioCommonFormat.PCMFloat32, 44100.0, 2, true); var desc = format.StreamDescription; - Assert.AreEqual (AudioFormatType.LinearPCM, desc.Format, "Format"); - Assert.AreEqual (AudioFormatFlags.LinearPCMIsFloat | AudioFormatFlags.LinearPCMIsPacked, desc.FormatFlags, "FormatFlags"); - Assert.AreEqual (8, desc.BytesPerPacket, "BytesPerPacket"); - Assert.AreEqual (1, desc.FramesPerPacket, "FramesPerPacket"); - Assert.AreEqual (8, desc.BytesPerFrame, "BytesPerFrame"); - Assert.AreEqual (2, desc.ChannelsPerFrame, "ChannelsPerFrame"); - Assert.AreEqual (32, desc.BitsPerChannel, "BitsPerChannel"); - Assert.AreEqual (0, desc.Reserved, "Reserved"); + Assert.That (desc.Format, Is.EqualTo (AudioFormatType.LinearPCM), "Format"); + Assert.That (desc.FormatFlags, Is.EqualTo (AudioFormatFlags.LinearPCMIsFloat | AudioFormatFlags.LinearPCMIsPacked), "FormatFlags"); + Assert.That (desc.BytesPerPacket, Is.EqualTo (8), "BytesPerPacket"); + Assert.That (desc.FramesPerPacket, Is.EqualTo (1), "FramesPerPacket"); + Assert.That (desc.BytesPerFrame, Is.EqualTo (8), "BytesPerFrame"); + Assert.That (desc.ChannelsPerFrame, Is.EqualTo (2), "ChannelsPerFrame"); + Assert.That (desc.BitsPerChannel, Is.EqualTo (32), "BitsPerChannel"); + Assert.That (desc.Reserved, Is.EqualTo (0), "Reserved"); } } } diff --git a/tests/monotouch-test/AVFoundation/AVAudioSinkNodeTest.cs b/tests/monotouch-test/AVFoundation/AVAudioSinkNodeTest.cs index e0b19becf97a..09cf580a7f01 100644 --- a/tests/monotouch-test/AVFoundation/AVAudioSinkNodeTest.cs +++ b/tests/monotouch-test/AVFoundation/AVAudioSinkNodeTest.cs @@ -61,13 +61,13 @@ void SinkNodeCallbackTest (ManualResetEvent callbackEvent, Func Assert.Ignore ("The current system doesn't have a microphone."); session.SetCategory (AVAudioSessionCategory.PlayAndRecord, AVAudioSessionCategoryOptions.DefaultToSpeaker, out var categoryError); - Assert.IsNull (categoryError, "Category Error"); + Assert.That (categoryError, Is.Null, "Category Error"); session.SetPreferredSampleRate (48000, out var sampleRateError); - Assert.IsNull (sampleRateError, "Sample Rate Error"); + Assert.That (sampleRateError, Is.Null, "Sample Rate Error"); if (session.MaximumInputNumberOfChannels == 0) Assert.Ignore ("The current system doesn't support any input channels"); session.SetPreferredInputNumberOfChannels (1, out var inputChannelCountError); - Assert.IsNull (inputChannelCountError, "Input Channel Count Error"); + Assert.That (inputChannelCountError, Is.Null, "Input Channel Count Error"); session.SetActive (true); #endif // __MACOS__ @@ -83,8 +83,8 @@ void SinkNodeCallbackTest (ManualResetEvent callbackEvent, Func engine.Connect (inputNode, sinkNode, inputFormat); engine.StartAndReturnError (out var error); - Assert.IsNull (error, "Start error"); - Assert.True (callbackEvent.WaitOne (TimeSpan.FromSeconds (5)), "Called back"); + Assert.That (error, Is.Null, "Start error"); + Assert.That (callbackEvent.WaitOne (TimeSpan.FromSeconds (5)), Is.True, "Called back"); } finally { engine.Stop (); } diff --git a/tests/monotouch-test/AVFoundation/AVAudioSourceNodeTest.cs b/tests/monotouch-test/AVFoundation/AVAudioSourceNodeTest.cs index 34a013101784..81f0ad7c6d62 100644 --- a/tests/monotouch-test/AVFoundation/AVAudioSourceNodeTest.cs +++ b/tests/monotouch-test/AVFoundation/AVAudioSourceNodeTest.cs @@ -61,13 +61,13 @@ void SourceNodeCallbackTest (TaskCompletionSource callbackEvent, Func callbackEvent, Func callbackEvent, Func evt) { try { - Assert.AreEqual (1, outputData.Count, "Count"); + Assert.That (outputData.Count, Is.EqualTo (1), "Count"); Assert.That (((IntPtr) outputData.Handle).ToInt64 (), Is.GreaterThan (1024), "Valid handle"); Assert.That (outputData [0].DataByteSize, Is.GreaterThan (1023), "Valid data size"); Assert.That (outputData [0].NumberChannels, Is.GreaterThan (0), "NumberChannels"); diff --git a/tests/monotouch-test/AVFoundation/AVAudioVoiceProcessingOtherAudioDuckingConfigurationTest.cs b/tests/monotouch-test/AVFoundation/AVAudioVoiceProcessingOtherAudioDuckingConfigurationTest.cs index d55e05afc0d9..d281ee9181b2 100644 --- a/tests/monotouch-test/AVFoundation/AVAudioVoiceProcessingOtherAudioDuckingConfigurationTest.cs +++ b/tests/monotouch-test/AVFoundation/AVAudioVoiceProcessingOtherAudioDuckingConfigurationTest.cs @@ -18,28 +18,28 @@ public class AVAudioVoiceProcessingOtherAudioDuckingConfigurationTest { public void Properties () { var s = new AVAudioVoiceProcessingOtherAudioDuckingConfiguration (); - Assert.IsFalse (s.EnableAdvancedDucking, "EnableAdvancedDucking"); - Assert.AreEqual ((AVAudioVoiceProcessingOtherAudioDuckingLevel) 0, s.DuckingLevel, "DuckingLevel"); + Assert.That (s.EnableAdvancedDucking, Is.False, "EnableAdvancedDucking"); + Assert.That (s.DuckingLevel, Is.EqualTo ((AVAudioVoiceProcessingOtherAudioDuckingLevel) 0), "DuckingLevel"); s.EnableAdvancedDucking = true; - Assert.IsTrue (s.EnableAdvancedDucking, "EnableAdvancedDucking 2"); - Assert.AreEqual ((AVAudioVoiceProcessingOtherAudioDuckingLevel) 0, s.DuckingLevel, "DuckingLevel 2"); + Assert.That (s.EnableAdvancedDucking, Is.True, "EnableAdvancedDucking 2"); + Assert.That (s.DuckingLevel, Is.EqualTo ((AVAudioVoiceProcessingOtherAudioDuckingLevel) 0), "DuckingLevel 2"); s.EnableAdvancedDucking = false; - Assert.IsFalse (s.EnableAdvancedDucking, "EnableAdvancedDucking 3"); - Assert.AreEqual ((AVAudioVoiceProcessingOtherAudioDuckingLevel) 0, s.DuckingLevel, "DuckingLevel 3"); + Assert.That (s.EnableAdvancedDucking, Is.False, "EnableAdvancedDucking 3"); + Assert.That (s.DuckingLevel, Is.EqualTo ((AVAudioVoiceProcessingOtherAudioDuckingLevel) 0), "DuckingLevel 3"); s.DuckingLevel = AVAudioVoiceProcessingOtherAudioDuckingLevel.Min; - Assert.IsFalse (s.EnableAdvancedDucking, "EnableAdvancedDucking 4"); - Assert.AreEqual (AVAudioVoiceProcessingOtherAudioDuckingLevel.Min, s.DuckingLevel, "DuckingLevel 4"); + Assert.That (s.EnableAdvancedDucking, Is.False, "EnableAdvancedDucking 4"); + Assert.That (s.DuckingLevel, Is.EqualTo (AVAudioVoiceProcessingOtherAudioDuckingLevel.Min), "DuckingLevel 4"); s.DuckingLevel = (AVAudioVoiceProcessingOtherAudioDuckingLevel) 314; - Assert.IsFalse (s.EnableAdvancedDucking, "EnableAdvancedDucking 5"); - Assert.AreEqual ((AVAudioVoiceProcessingOtherAudioDuckingLevel) 314, s.DuckingLevel, "DuckingLevel 5"); + Assert.That (s.EnableAdvancedDucking, Is.False, "EnableAdvancedDucking 5"); + Assert.That (s.DuckingLevel, Is.EqualTo ((AVAudioVoiceProcessingOtherAudioDuckingLevel) 314), "DuckingLevel 5"); s.DuckingLevel = AVAudioVoiceProcessingOtherAudioDuckingLevel.Default; - Assert.IsFalse (s.EnableAdvancedDucking, "EnableAdvancedDucking 6"); - Assert.AreEqual (AVAudioVoiceProcessingOtherAudioDuckingLevel.Default, s.DuckingLevel, "DuckingLevel 6"); + Assert.That (s.EnableAdvancedDucking, Is.False, "EnableAdvancedDucking 6"); + Assert.That (s.DuckingLevel, Is.EqualTo (AVAudioVoiceProcessingOtherAudioDuckingLevel.Default), "DuckingLevel 6"); } } } diff --git a/tests/monotouch-test/AVFoundation/AVBeatRangeTest.cs b/tests/monotouch-test/AVFoundation/AVBeatRangeTest.cs index 924989a628f2..c4fcd65791e9 100644 --- a/tests/monotouch-test/AVFoundation/AVBeatRangeTest.cs +++ b/tests/monotouch-test/AVFoundation/AVBeatRangeTest.cs @@ -13,8 +13,8 @@ public void ConstructorTest () var range = new AVBeatRange (start, length); - Assert.AreEqual (start, range.Start, "Wrong Start value."); - Assert.AreEqual (length, range.Length, "Wrong Length value."); + Assert.That (range.Start, Is.EqualTo (start), "Wrong Start value."); + Assert.That (range.Length, Is.EqualTo (length), "Wrong Length value."); } [Test] @@ -25,9 +25,9 @@ public void AreEqualTrueTest () var range1 = new AVBeatRange (start, length); var range2 = new AVBeatRange (start, length); - Assert.True (range1 == range2, "range1 == range2"); - Assert.True (range1.Equals (range2), "range1.Equals (range1)"); - Assert.False (range1 != range2, "range1 != range2"); + Assert.That (range1 == range2, Is.True, "range1 == range2"); + Assert.That (range1.Equals (range2), Is.True, "range1.Equals (range1)"); + Assert.That (range1 != range2, Is.False, "range1 != range2"); } [Test] @@ -35,9 +35,9 @@ public void AreEqualFalseTest () { var range1 = new AVBeatRange (90, 12); var range2 = new AVBeatRange (range1.Start * 2, range1.Length * 2); - Assert.False (range1 == range2, "range1 == range2"); - Assert.False (range1.Equals (range2), "range1.Equals (range2)"); - Assert.True (range1 != range2, "range1 != range2"); + Assert.That (range1 == range2, Is.False, "range1 == range2"); + Assert.That (range1.Equals (range2), Is.False, "range1.Equals (range2)"); + Assert.That (range1 != range2, Is.True, "range1 != range2"); } [Test] @@ -45,7 +45,7 @@ public void AreEqualDiffType () { var range = new AVBeatRange (90, 12); var str = new NSString ("Foo"); - Assert.False (range.Equals ((object) str)); + Assert.That (range.Equals ((object) str), Is.False); } } } diff --git a/tests/monotouch-test/AVFoundation/AVCaptionDimensionTest.cs b/tests/monotouch-test/AVFoundation/AVCaptionDimensionTest.cs index fec6187991ea..817ca60a2933 100644 --- a/tests/monotouch-test/AVFoundation/AVCaptionDimensionTest.cs +++ b/tests/monotouch-test/AVFoundation/AVCaptionDimensionTest.cs @@ -21,8 +21,8 @@ public void CreateTest () nfloat val = 10; var units = AVCaptionUnitsType.Cells; var dimension = AVCaptionDimension.Create (val, units); - Assert.AreEqual (val, dimension.Value, "Value"); - Assert.AreEqual (units, dimension.Units); + Assert.That (dimension.Value, Is.EqualTo (val), "Value"); + Assert.That (dimension.Units, Is.EqualTo (units)); } } } diff --git a/tests/monotouch-test/AVFoundation/AVCaptionPointTest.cs b/tests/monotouch-test/AVFoundation/AVCaptionPointTest.cs index c0c33c7814bf..5eb878d8e125 100644 --- a/tests/monotouch-test/AVFoundation/AVCaptionPointTest.cs +++ b/tests/monotouch-test/AVFoundation/AVCaptionPointTest.cs @@ -23,8 +23,8 @@ public void CreateTest () var secondDimension = AVCaptionDimension.Create (val, units); var point = AVCaptionPoint.Create (firstDimension, secondDimension); - Assert.AreEqual (val, point.X.Value, "X"); - Assert.AreEqual (val, point.Y.Value, "Y"); + Assert.That (point.X.Value, Is.EqualTo (val), "X"); + Assert.That (point.Y.Value, Is.EqualTo (val), "Y"); } } } diff --git a/tests/monotouch-test/AVFoundation/AVCaptionSizeTest.cs b/tests/monotouch-test/AVFoundation/AVCaptionSizeTest.cs index 7d615951c51f..d56c220a7d8c 100644 --- a/tests/monotouch-test/AVFoundation/AVCaptionSizeTest.cs +++ b/tests/monotouch-test/AVFoundation/AVCaptionSizeTest.cs @@ -23,8 +23,8 @@ public void CreateTest () var secondDimension = AVCaptionDimension.Create (val, units); var size = AVCaptionSize.Create (firstDimension, secondDimension); - Assert.AreEqual (val, size.Width.Value, "Width"); - Assert.AreEqual (val, size.Height.Value, "Height"); + Assert.That (size.Width.Value, Is.EqualTo (val), "Width"); + Assert.That (size.Height.Value, Is.EqualTo (val), "Height"); } } } diff --git a/tests/monotouch-test/AVFoundation/AVCaptureReactionTypeTest.cs b/tests/monotouch-test/AVFoundation/AVCaptureReactionTypeTest.cs index 215435084bec..1841d19a4d93 100644 --- a/tests/monotouch-test/AVFoundation/AVCaptureReactionTypeTest.cs +++ b/tests/monotouch-test/AVFoundation/AVCaptureReactionTypeTest.cs @@ -14,7 +14,7 @@ public class AVCaptureReactionTypeTest { public void GetSystemImage () { TestRuntime.AssertXcodeVersion (15, 0); - Assert.IsNotNull (AVCaptureReactionType.ThumbsUp.GetSystemImage (), "GetSystemImage"); + Assert.That (AVCaptureReactionType.ThumbsUp.GetSystemImage (), Is.Not.Null, "GetSystemImage"); } } } diff --git a/tests/monotouch-test/AVFoundation/AVCaptureTimecodeTests.cs b/tests/monotouch-test/AVFoundation/AVCaptureTimecodeTests.cs index 6ef6f383c671..7b4b5a48fe14 100644 --- a/tests/monotouch-test/AVFoundation/AVCaptureTimecodeTests.cs +++ b/tests/monotouch-test/AVFoundation/AVCaptureTimecodeTests.cs @@ -17,8 +17,8 @@ public void EqualityOperator_TrueForIdenticalValues () { var t1 = new AVCaptureTimecode (1, 2, 3, 4, 5, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); var t2 = new AVCaptureTimecode (1, 2, 3, 4, 5, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); - Assert.True (t1 == t2); - Assert.False (t1 != t2); + Assert.That (t1 == t2, Is.True); + Assert.That (t1 != t2, Is.False); } [Test] @@ -26,8 +26,8 @@ public void EqualityOperator_FalseForDifferentValues () { var t1 = new AVCaptureTimecode (1, 2, 3, 4, 5, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); var t2 = new AVCaptureTimecode (9, 2, 3, 4, 5, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); - Assert.False (t1 == t2); - Assert.True (t1 != t2); + Assert.That (t1 == t2, Is.False); + Assert.That (t1 != t2, Is.True); } [Test] @@ -35,8 +35,8 @@ public void EqualsMethod_TrueForIdenticalValues () { var t1 = new AVCaptureTimecode (1, 2, 3, 4, 5, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); var t2 = new AVCaptureTimecode (1, 2, 3, 4, 5, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); - Assert.True (t1.Equals (t2)); - Assert.True (t1.Equals ((object) t2)); + Assert.That (t1.Equals (t2), Is.True); + Assert.That (t1.Equals ((object) t2), Is.True); } [Test] @@ -44,8 +44,8 @@ public void EqualsMethod_FalseForDifferentValues () { var t1 = new AVCaptureTimecode (1, 2, 3, 4, 5, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); var t2 = new AVCaptureTimecode (1, 2, 3, 4, 6, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); - Assert.False (t1.Equals (t2)); - Assert.False (t1.Equals ((object) t2)); + Assert.That (t1.Equals (t2), Is.False); + Assert.That (t1.Equals ((object) t2), Is.False); } [Test] @@ -53,7 +53,7 @@ public void GetHashCode_EqualForIdenticalValues () { var t1 = new AVCaptureTimecode (1, 2, 3, 4, 5, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); var t2 = new AVCaptureTimecode (1, 2, 3, 4, 5, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); - Assert.AreEqual (t1.GetHashCode (), t2.GetHashCode ()); + Assert.That (t2.GetHashCode (), Is.EqualTo (t1.GetHashCode ())); } [Test] @@ -61,7 +61,7 @@ public void GetHashCode_NotEqualForDifferentValues () { var t1 = new AVCaptureTimecode (1, 2, 3, 4, 5, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); var t2 = new AVCaptureTimecode (1, 2, 3, 4, 6, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); - Assert.AreNotEqual (t1.GetHashCode (), t2.GetHashCode ()); + Assert.That (t2.GetHashCode (), Is.Not.EqualTo (t1.GetHashCode ())); } [Test] @@ -69,7 +69,7 @@ public void AddFramesTest () { var t1 = new AVCaptureTimecode (1, 2, 3, 4, 5, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); var t2 = t1.AddFrames (10); - Assert.True (t1 != t2); + Assert.That (t1 != t2, Is.True); } [Test] @@ -77,14 +77,14 @@ public void MetadataSampleBufferTest () { var t1 = new AVCaptureTimecode (1, 2, 3, 4, 5, new CMTime (60, 30), AVCaptureTimecodeSourceType.FrameCount); using var sampleBuffer = t1.CreateMetadataSampleBufferAssociatedWithPresentationTimeStamp (new CMTime (60, 60)); - Assert.IsNotNull (sampleBuffer, "sampleBuffer"); - Assert.IsTrue (sampleBuffer.IsValid, "IsValid"); - Assert.IsTrue (1 == sampleBuffer.NumSamples, "NumSamples"); + Assert.That (sampleBuffer, Is.Not.Null, "sampleBuffer"); + Assert.That (sampleBuffer.IsValid, Is.True, "IsValid"); + Assert.That (1 == sampleBuffer.NumSamples, Is.True, "NumSamples"); using var sampleBuffer2 = t1.CreateMetadataSampleBufferForDuration (new CMTime (60, 60)); - Assert.IsNotNull (sampleBuffer2, "sampleBuffer2"); - Assert.IsTrue (sampleBuffer2.IsValid, "IsValid"); - Assert.IsTrue (1 == sampleBuffer2.NumSamples, "NumSamples"); + Assert.That (sampleBuffer2, Is.Not.Null, "sampleBuffer2"); + Assert.That (sampleBuffer2.IsValid, Is.True, "IsValid"); + Assert.That (1 == sampleBuffer2.NumSamples, Is.True, "NumSamples"); } } } diff --git a/tests/monotouch-test/AVFoundation/AVCaptureWhiteBalanceGainsTest.cs b/tests/monotouch-test/AVFoundation/AVCaptureWhiteBalanceGainsTest.cs index 474de9bfacf5..f2b8b47bd6be 100644 --- a/tests/monotouch-test/AVFoundation/AVCaptureWhiteBalanceGainsTest.cs +++ b/tests/monotouch-test/AVFoundation/AVCaptureWhiteBalanceGainsTest.cs @@ -14,9 +14,9 @@ public void ConstructorTest () var gains = new AVCaptureWhiteBalanceGains (red, green, blue); - Assert.AreEqual (red, gains.RedGain, "Wrong RedGain value."); - Assert.AreEqual (green, gains.GreenGain, "Wrong GreenGain value."); - Assert.AreEqual (blue, gains.BlueGain, "Wrong BlueGain value."); + Assert.That (gains.RedGain, Is.EqualTo (red), "Wrong RedGain value."); + Assert.That (gains.GreenGain, Is.EqualTo (green), "Wrong GreenGain value."); + Assert.That (gains.BlueGain, Is.EqualTo (blue), "Wrong BlueGain value."); } [Test] @@ -29,9 +29,9 @@ public void AreEqualTrueTest () var gains1 = new AVCaptureWhiteBalanceGains (red, green, blue); var gains2 = new AVCaptureWhiteBalanceGains (red, green, blue); - Assert.True (gains1 == gains2, "gains1 == gains2"); - Assert.True (gains1.Equals (gains2), "gains1.Equals (gains2)"); - Assert.False (gains1 != gains2, "gains1 != gains2"); + Assert.That (gains1 == gains2, Is.True, "gains1 == gains2"); + Assert.That (gains1.Equals (gains2), Is.True, "gains1.Equals (gains2)"); + Assert.That (gains1 != gains2, Is.False, "gains1 != gains2"); } [Test] @@ -39,9 +39,9 @@ public void AreEqualFalseTest () { var gains1 = new AVCaptureWhiteBalanceGains (2.3f, 3f, 90f); var gains2 = new AVCaptureWhiteBalanceGains (gains1.RedGain * 2, gains1.GreenGain * 2, gains1.BlueGain * 2); - Assert.False (gains1 == gains2, "gains1 == gains2"); - Assert.False (gains1.Equals (gains2), "gains1.Equals (gains2)"); - Assert.True (gains1 != gains2, "gains1 != gains2"); + Assert.That (gains1 == gains2, Is.False, "gains1 == gains2"); + Assert.That (gains1.Equals (gains2), Is.False, "gains1.Equals (gains2)"); + Assert.That (gains1 != gains2, Is.True, "gains1 != gains2"); } [Test] @@ -49,7 +49,7 @@ public void AreEqualDiffType () { var gains = new AVCaptureWhiteBalanceGains (2.3f, 3f, 90f); var str = new NSString ("Foo"); - Assert.False (gains.Equals ((object) str)); + Assert.That (gains.Equals ((object) str), Is.False); } } } diff --git a/tests/monotouch-test/AVFoundation/AVDepthDataTests.cs b/tests/monotouch-test/AVFoundation/AVDepthDataTests.cs index 573d561e498c..40268640ac65 100644 --- a/tests/monotouch-test/AVFoundation/AVDepthDataTests.cs +++ b/tests/monotouch-test/AVFoundation/AVDepthDataTests.cs @@ -27,21 +27,21 @@ public void AvailableDepthDataTypesTest () // xamarinmonkey.heic is the new photo format, also this one includes depth data var imgdata = NSData.FromUrl (NSBundle.MainBundle.GetUrlForResource ("xamarinmonkey", "heic", "CoreImage")); - Assert.NotNull (imgdata, "imgdata"); + Assert.That (imgdata, Is.Not.Null, "imgdata"); var imageSource = CGImageSource.FromData (imgdata); - Assert.NotNull (imageSource, "imageSource"); + Assert.That (imageSource, Is.Not.Null, "imageSource"); // fetching the image count works around a crash in CopyAuxiliaryDataInfo on macOS 10.15 (https://github.com/xamarin/maccore/issues/1802). - Assert.AreNotEqual (0, imageSource.ImageCount, "ImageCount"); + Assert.That (imageSource.ImageCount, Is.Not.EqualTo (0), "ImageCount"); var info = imageSource.CopyAuxiliaryDataInfo (0, CGImageAuxiliaryDataType.Disparity); - Assert.NotNull (info, "info"); + Assert.That (info, Is.Not.Null, "info"); NSError err; var depthData = AVDepthData.Create (info, out err); - Assert.NotNull (depthData, "depthData"); - Assert.NotNull (depthData.AvailableDepthDataTypes, "AvailableDepthDataTypes"); + Assert.That (depthData, Is.Not.Null, "depthData"); + Assert.That (depthData.AvailableDepthDataTypes, Is.Not.Null, "AvailableDepthDataTypes"); } } } diff --git a/tests/monotouch-test/AVFoundation/AVPlayerLayerTest.cs b/tests/monotouch-test/AVFoundation/AVPlayerLayerTest.cs index d8fa4085e402..b24a77b6a79c 100644 --- a/tests/monotouch-test/AVFoundation/AVPlayerLayerTest.cs +++ b/tests/monotouch-test/AVFoundation/AVPlayerLayerTest.cs @@ -13,7 +13,7 @@ public class AVPlayerLayerTests { public void AVPlayerLayer_VideoGravity () { AVPlayerLayer layer = new AVPlayerLayer (); - Assert.IsNotNull (layer.VideoGravity); + Assert.That (layer.VideoGravity, Is.Not.Null); } } } diff --git a/tests/monotouch-test/AVFoundation/AVSpeechSynthesisMarkerTest.cs b/tests/monotouch-test/AVFoundation/AVSpeechSynthesisMarkerTest.cs index ce63130e258b..3ac15cdeb791 100644 --- a/tests/monotouch-test/AVFoundation/AVSpeechSynthesisMarkerTest.cs +++ b/tests/monotouch-test/AVFoundation/AVSpeechSynthesisMarkerTest.cs @@ -20,27 +20,27 @@ public void NSRangeCtor () Assert.Multiple (() => { { using var marker = new AVSpeechSynthesisMarker (range, byteOffset, AVSpeechSynthesisMarkerRangeOption.Word); - Assert.AreEqual (range, marker.TextRange, "TextRange W"); - Assert.AreEqual (byteOffset, (nint) marker.ByteSampleOffset, "ByteSampleOffset W"); - Assert.AreEqual (AVSpeechSynthesisMarkerMark.Word, marker.Mark, "AVSpeechSynthesisMarkerMark W"); - Assert.IsNull (marker.BookmarkName, "BookmarkName W"); - Assert.IsNull (marker.Phoneme, "Phoneme W"); + Assert.That (marker.TextRange, Is.EqualTo (range), "TextRange W"); + Assert.That ((nint) marker.ByteSampleOffset, Is.EqualTo (byteOffset), "ByteSampleOffset W"); + Assert.That (marker.Mark, Is.EqualTo (AVSpeechSynthesisMarkerMark.Word), "AVSpeechSynthesisMarkerMark W"); + Assert.That (marker.BookmarkName, Is.Null, "BookmarkName W"); + Assert.That (marker.Phoneme, Is.Null, "Phoneme W"); } { using var marker = new AVSpeechSynthesisMarker (range, byteOffset, AVSpeechSynthesisMarkerRangeOption.Sentence); - Assert.AreEqual (range, marker.TextRange, "TextRange S"); - Assert.AreEqual (byteOffset, (nint) marker.ByteSampleOffset, "ByteSampleOffset S"); - Assert.AreEqual (AVSpeechSynthesisMarkerMark.Sentence, marker.Mark, "AVSpeechSynthesisMarkerMark S"); - Assert.IsNull (marker.BookmarkName, "BookmarkName S"); - Assert.IsNull (marker.Phoneme, "Phoneme S"); + Assert.That (marker.TextRange, Is.EqualTo (range), "TextRange S"); + Assert.That ((nint) marker.ByteSampleOffset, Is.EqualTo (byteOffset), "ByteSampleOffset S"); + Assert.That (marker.Mark, Is.EqualTo (AVSpeechSynthesisMarkerMark.Sentence), "AVSpeechSynthesisMarkerMark S"); + Assert.That (marker.BookmarkName, Is.Null, "BookmarkName S"); + Assert.That (marker.Phoneme, Is.Null, "Phoneme S"); } { using var marker = new AVSpeechSynthesisMarker (range, byteOffset, AVSpeechSynthesisMarkerRangeOption.Paragraph); - Assert.AreEqual (range, marker.TextRange, "TextRange P"); - Assert.AreEqual (byteOffset, (nint) marker.ByteSampleOffset, "ByteSampleOffset P"); - Assert.AreEqual (AVSpeechSynthesisMarkerMark.Paragraph, marker.Mark, "AVSpeechSynthesisMarkerMark P"); - Assert.IsNull (marker.BookmarkName, "BookmarkName P"); - Assert.IsNull (marker.Phoneme, "Phoneme P"); + Assert.That (marker.TextRange, Is.EqualTo (range), "TextRange P"); + Assert.That ((nint) marker.ByteSampleOffset, Is.EqualTo (byteOffset), "ByteSampleOffset P"); + Assert.That (marker.Mark, Is.EqualTo (AVSpeechSynthesisMarkerMark.Paragraph), "AVSpeechSynthesisMarkerMark P"); + Assert.That (marker.BookmarkName, Is.Null, "BookmarkName P"); + Assert.That (marker.Phoneme, Is.Null, "Phoneme P"); } }); } @@ -56,18 +56,18 @@ public void StringCtor () Assert.Multiple (() => { { using var marker = new AVSpeechSynthesisMarker (value, byteOffset, AVSpeechSynthesisMarkerStringOption.Phoneme); - Assert.AreEqual (range, marker.TextRange, "TextRange P"); - Assert.AreEqual (byteOffset, (nint) marker.ByteSampleOffset, "ByteSampleOffset P"); - Assert.AreEqual (AVSpeechSynthesisMarkerMark.Phoneme, marker.Mark, "AVSpeechSynthesisMarkerMark P"); - Assert.IsNull (marker.BookmarkName, "BookmarkName P"); - Assert.AreEqual (value, marker.Phoneme, "Phoneme P"); + Assert.That (marker.TextRange, Is.EqualTo (range), "TextRange P"); + Assert.That ((nint) marker.ByteSampleOffset, Is.EqualTo (byteOffset), "ByteSampleOffset P"); + Assert.That (marker.Mark, Is.EqualTo (AVSpeechSynthesisMarkerMark.Phoneme), "AVSpeechSynthesisMarkerMark P"); + Assert.That (marker.BookmarkName, Is.Null, "BookmarkName P"); + Assert.That (marker.Phoneme, Is.EqualTo (value), "Phoneme P"); } { using var marker = new AVSpeechSynthesisMarker (value, byteOffset, AVSpeechSynthesisMarkerStringOption.Bookmark); - Assert.AreEqual (range, marker.TextRange, "TextRange B"); - Assert.AreEqual (byteOffset, (nint) marker.ByteSampleOffset, "ByteSampleOffset B"); - Assert.AreEqual (AVSpeechSynthesisMarkerMark.Bookmark, marker.Mark, "AVSpeechSynthesisMarkerMark B"); - Assert.IsNull (marker.Phoneme, "Phoneme B"); + Assert.That (marker.TextRange, Is.EqualTo (range), "TextRange B"); + Assert.That ((nint) marker.ByteSampleOffset, Is.EqualTo (byteOffset), "ByteSampleOffset B"); + Assert.That (marker.Mark, Is.EqualTo (AVSpeechSynthesisMarkerMark.Bookmark), "AVSpeechSynthesisMarkerMark B"); + Assert.That (marker.Phoneme, Is.Null, "Phoneme B"); } }); } diff --git a/tests/monotouch-test/AVFoundation/AVSpeechUtteranceTest.cs b/tests/monotouch-test/AVFoundation/AVSpeechUtteranceTest.cs index 247de454fb9a..a3e21e4bae75 100644 --- a/tests/monotouch-test/AVFoundation/AVSpeechUtteranceTest.cs +++ b/tests/monotouch-test/AVFoundation/AVSpeechUtteranceTest.cs @@ -14,14 +14,14 @@ public class AVSpeechUtteranceTest { public void StringCtor () { using var utterance = new AVSpeechUtterance ("hello world"); - Assert.AreEqual (utterance.SpeechString, "hello world", "SpeechString"); + Assert.That (utterance.SpeechString, Is.EqualTo ("hello world"), "SpeechString"); } [Test] public void StringOptionCtor_PlainText () { using var utterance = new AVSpeechUtterance ("hello world", AVSpeechUtteranceInitializationOption.PlainText); - Assert.AreEqual (utterance.SpeechString, "hello world", "SpeechString"); + Assert.That (utterance.SpeechString, Is.EqualTo ("hello world"), "SpeechString"); } [Test] @@ -31,7 +31,7 @@ public void StringOptionCtor_Ssml () var ssml = $"""Hello World"""; using var utterance = new AVSpeechUtterance (ssml, AVSpeechUtteranceInitializationOption.SsmlRepresentation); - Assert.AreEqual (utterance.SpeechString, "Hello World", "SpeechString"); + Assert.That (utterance.SpeechString, Is.EqualTo ("Hello World"), "SpeechString"); } } } diff --git a/tests/monotouch-test/AVFoundation/AudioPlayerTest.cs b/tests/monotouch-test/AVFoundation/AudioPlayerTest.cs index c6e342276eab..60521e0d440c 100644 --- a/tests/monotouch-test/AVFoundation/AudioPlayerTest.cs +++ b/tests/monotouch-test/AVFoundation/AudioPlayerTest.cs @@ -22,11 +22,11 @@ public class AudioPlayerTest { public void FromUrl () { string file = Path.Combine (NSBundle.MainBundle.ResourcePath, "Hand.wav"); - Assert.True (File.Exists (file), file); + Assert.That (File.Exists (file), Is.True, file); using (NSUrl url = new (file, false)) using (AVAudioPlayer ap = AVAudioPlayer.FromUrl (url, out NSError error)) { - Assert.NotNull (ap, "AVAudioPlayer"); - Assert.Null (error, "NSError"); + Assert.That (ap, Is.Not.Null, "AVAudioPlayer"); + Assert.That (error, Is.Null, "NSError"); } } @@ -35,8 +35,8 @@ public void FromUrlWithInvalidUrl () { Assert.DoesNotThrow (() => { using (AVAudioPlayer player = AVAudioPlayer.FromUrl (NSUrl.FromString ("sdf"), out NSError error)) { - Assert.Null (player, "AVAudioPlayer"); - Assert.NotNull (error, "NSError"); + Assert.That (player, Is.Null, "AVAudioPlayer"); + Assert.That (error, Is.Not.Null, "NSError"); } }); } @@ -45,17 +45,17 @@ public void FromUrlWithInvalidUrl () public void FromUrlWithHint () { var file = Path.Combine (NSBundle.MainBundle.ResourcePath, "Hand.wav"); - Assert.True (File.Exists (file), file); + Assert.That (File.Exists (file), Is.True, file); using var url = new NSUrl (file, false); { using var ap = AVAudioPlayer.FromUrl (url, AVFileTypes.Wave, out var error); - Assert.NotNull (ap, "AVAudioPlayer"); - Assert.Null (error, "NSError"); + Assert.That (ap, Is.Not.Null, "AVAudioPlayer"); + Assert.That (error, Is.Null, "NSError"); } { using var ap = AVAudioPlayer.FromUrl (url, AVFileTypes.Wave.GetConstant (), out var error); - Assert.NotNull (ap, "AVAudioPlayer 2"); - Assert.Null (error, "NSError 2"); + Assert.That (ap, Is.Not.Null, "AVAudioPlayer 2"); + Assert.That (error, Is.Null, "NSError 2"); } } @@ -65,13 +65,13 @@ public void FromInvalidUrlWithHint () using var url = new NSUrl ("sdf", false); { using var ap = AVAudioPlayer.FromUrl (url, AVFileTypes.Wave, out var error); - Assert.Null (ap, "AVAudioPlayer"); - Assert.NotNull (error, "NSError"); + Assert.That (ap, Is.Null, "AVAudioPlayer"); + Assert.That (error, Is.Not.Null, "NSError"); } { using var ap = AVAudioPlayer.FromUrl (url, AVFileTypes.Wave.GetConstant (), out var error); - Assert.Null (ap, "AVAudioPlayer 2"); - Assert.NotNull (error, "NSError 2"); + Assert.That (ap, Is.Null, "AVAudioPlayer 2"); + Assert.That (error, Is.Not.Null, "NSError 2"); } } @@ -80,8 +80,8 @@ public void FromData () { using (NSData data = NSData.FromFile (NSBundle.MainBundle.PathForResource ("Hand", "wav"))) using (AVAudioPlayer player = AVAudioPlayer.FromData (data, out NSError error)) { - Assert.NotNull (player, "AVAudioPlayer"); - Assert.Null (error, "NSError"); + Assert.That (player, Is.Not.Null, "AVAudioPlayer"); + Assert.That (error, Is.Null, "NSError"); } } @@ -91,13 +91,13 @@ public void FromDataWithHint () using var data = NSData.FromFile (NSBundle.MainBundle.PathForResource ("Hand", "wav")); { using var player = AVAudioPlayer.FromData (data, AVFileTypes.Wave, out var error); - Assert.NotNull (player, "AVAudioPlayer"); - Assert.Null (error, "NSError"); + Assert.That (player, Is.Not.Null, "AVAudioPlayer"); + Assert.That (error, Is.Null, "NSError"); } { using var player = AVAudioPlayer.FromData (data, AVFileTypes.Wave.GetConstant (), out var error); - Assert.NotNull (player, "AVAudioPlayer 2"); - Assert.Null (error, "NSError 2"); + Assert.That (player, Is.Not.Null, "AVAudioPlayer 2"); + Assert.That (error, Is.Null, "NSError 2"); } } @@ -106,8 +106,8 @@ public void FromDataWithNullData () { Assert.Throws (() => { using (var player = AVAudioPlayer.FromData (null, out NSError error)) { - Assert.Null (player, "AVAudioPlayer"); - Assert.NotNull (error, "NSError"); + Assert.That (player, Is.Null, "AVAudioPlayer"); + Assert.That (error, Is.Not.Null, "NSError"); } }); } diff --git a/tests/monotouch-test/AVFoundation/AudioRecorderTest.cs b/tests/monotouch-test/AVFoundation/AudioRecorderTest.cs index 6f02236258e8..b448b6f46fe0 100644 --- a/tests/monotouch-test/AVFoundation/AudioRecorderTest.cs +++ b/tests/monotouch-test/AVFoundation/AudioRecorderTest.cs @@ -37,8 +37,8 @@ public void Create () var audioSettings = new AudioSettings (NSDictionary.FromObjectsAndKeys (Values, Keys)); using (var recorder = AVAudioRecorder.Create (url, audioSettings, out error)) { - Assert.NotNull (recorder); - Assert.Null (error); + Assert.That (recorder, Is.Not.Null); + Assert.That (error, Is.Null); } } [Test] @@ -50,8 +50,8 @@ public void CreateWithError () NSError error; var audioSettings = new AudioSettings (NSDictionary.FromObjectsAndKeys (Values, Keys)); using (var recorder = AVAudioRecorder.Create (url, audioSettings, out error)) { - Assert.Null (recorder); - Assert.NotNull (error); + Assert.That (recorder, Is.Null); + Assert.That (error, Is.Not.Null); } } diff --git a/tests/monotouch-test/AVFoundation/CMTagCollectionVideoOutputPresetTest.cs b/tests/monotouch-test/AVFoundation/CMTagCollectionVideoOutputPresetTest.cs index 19d26abcc5f2..cead743b250b 100644 --- a/tests/monotouch-test/AVFoundation/CMTagCollectionVideoOutputPresetTest.cs +++ b/tests/monotouch-test/AVFoundation/CMTagCollectionVideoOutputPresetTest.cs @@ -16,8 +16,8 @@ public void Create () { TestRuntime.AssertXcodeVersion (16, 0); using var tagCollection = CMTagCollectionVideoOutputPreset.Monoscopic.Create (out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status"); - Assert.IsNotNull (tagCollection, "TagCollection"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status"); + Assert.That (tagCollection, Is.Not.Null, "TagCollection"); } } } diff --git a/tests/monotouch-test/AVFoundation/CaptureMetadataOutputTest.cs b/tests/monotouch-test/AVFoundation/CaptureMetadataOutputTest.cs index 5932a5c71724..89b10611d491 100644 --- a/tests/monotouch-test/AVFoundation/CaptureMetadataOutputTest.cs +++ b/tests/monotouch-test/AVFoundation/CaptureMetadataOutputTest.cs @@ -24,21 +24,21 @@ public class CaptureMetadataOutputTest { public void Defaults () { using (var obj = new AVCaptureMetadataOutput ()) { - Assert.AreEqual (AVMetadataObjectType.None, obj.AvailableMetadataObjectTypes, "AvailableMetadataObjectTypes"); - Assert.AreEqual (AVMetadataObjectType.None, obj.MetadataObjectTypes, "MetadataObjectTypes"); + Assert.That (obj.AvailableMetadataObjectTypes, Is.EqualTo (AVMetadataObjectType.None), "AvailableMetadataObjectTypes"); + Assert.That (obj.MetadataObjectTypes, Is.EqualTo (AVMetadataObjectType.None), "MetadataObjectTypes"); - Assert.IsNotNull (obj.WeakAvailableMetadataObjectTypes, "WeakAvailableMetadataObjectTypes"); - Assert.AreEqual (0, obj.WeakAvailableMetadataObjectTypes.Length, "WeakAvailableMetadataObjectTypes#"); - Assert.IsNotNull (obj.WeakMetadataObjectTypes, "WeakMetadataObjectTypes"); - Assert.AreEqual (0, obj.WeakMetadataObjectTypes.Length, "WeakMetadataObjectTypes#"); + Assert.That (obj.WeakAvailableMetadataObjectTypes, Is.Not.Null, "WeakAvailableMetadataObjectTypes"); + Assert.That (obj.WeakAvailableMetadataObjectTypes.Length, Is.EqualTo (0), "WeakAvailableMetadataObjectTypes#"); + Assert.That (obj.WeakMetadataObjectTypes, Is.Not.Null, "WeakMetadataObjectTypes"); + Assert.That (obj.WeakMetadataObjectTypes.Length, Is.EqualTo (0), "WeakMetadataObjectTypes#"); if (TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false)) - Assert.AreEqual (new CGRect (0, 0, 1, 1), obj.RectOfInterest, "RectOfInterest"); + Assert.That (obj.RectOfInterest, Is.EqualTo (new CGRect (0, 0, 1, 1)), "RectOfInterest"); if (TestRuntime.CheckXcodeVersion (13, 0)) { obj.WeakMetadataObjectTypes = null; - Assert.AreEqual (AVMetadataObjectType.None, obj.MetadataObjectTypes, "MetadataObjectTypes"); + Assert.That (obj.MetadataObjectTypes, Is.EqualTo (AVMetadataObjectType.None), "MetadataObjectTypes"); obj.MetadataObjectTypes = AVMetadataObjectType.None; - Assert.AreEqual (AVMetadataObjectType.None, obj.MetadataObjectTypes, "MetadataObjectTypes"); + Assert.That (obj.MetadataObjectTypes, Is.EqualTo (AVMetadataObjectType.None), "MetadataObjectTypes"); obj.SetDelegate (null, null); } } @@ -50,7 +50,7 @@ public void Flags () // single var flags = AVMetadataObjectType.Face; var result = AVMetadataObjectTypeExtensions.ToFlags (new NSString [] { flags.GetConstant () }); - Assert.AreEqual (flags, result, "a2e 1"); + Assert.That (result, Is.EqualTo (flags), "a2e 1"); var back = result.ToArray (); Assert.That (back.Length, Is.EqualTo (1), "l 1"); @@ -66,7 +66,7 @@ public void Flags () AVMetadataObjectType.HumanBody.GetConstant () }; result = AVMetadataObjectTypeExtensions.ToFlags (array); - Assert.AreEqual (flags, result, "a2e 3"); + Assert.That (result, Is.EqualTo (flags), "a2e 3"); back = result.ToArray (); Assert.That (back.Length, Is.EqualTo (3), "l 3"); Assert.That (back [0], Is.EqualTo (array [0]), "e2a 3a"); @@ -127,10 +127,10 @@ public void MetadataObjectTypesTest () } metadataOutput.MetadataObjectTypes = val; all |= val; - Assert.AreEqual (val, metadataOutput.MetadataObjectTypes, val.ToString ()); + Assert.That (metadataOutput.MetadataObjectTypes, Is.EqualTo (val), val.ToString ()); } metadataOutput.MetadataObjectTypes = all; - Assert.AreEqual (all, metadataOutput.MetadataObjectTypes, all.ToString ()); + Assert.That (metadataOutput.MetadataObjectTypes, Is.EqualTo (all), all.ToString ()); } } } diff --git a/tests/monotouch-test/AVFoundation/MetadataObjectTest.cs b/tests/monotouch-test/AVFoundation/MetadataObjectTest.cs index 31bc87d319ee..9477f4e082a1 100644 --- a/tests/monotouch-test/AVFoundation/MetadataObjectTest.cs +++ b/tests/monotouch-test/AVFoundation/MetadataObjectTest.cs @@ -25,21 +25,21 @@ public void Defaults () TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 10, 10, throwIfOtherPlatform: false); using (var obj = new AVMetadataFaceObject ()) { - Assert.AreEqual ((nint) 0, obj.FaceID, "FaceID"); - Assert.AreEqual (false, obj.HasRollAngle, "HasRollAngle"); - Assert.AreEqual (false, obj.HasYawAngle, "HasYawAngle"); + Assert.That (obj.FaceID, Is.EqualTo ((nint) 0), "FaceID"); + Assert.That (obj.HasRollAngle, Is.EqualTo (false), "HasRollAngle"); + Assert.That (obj.HasYawAngle, Is.EqualTo (false), "HasYawAngle"); #if !MONOMAC // No Type property for Mac - Assert.AreEqual (AVMetadataObjectType.Face, obj.Type, "Type"); + Assert.That (obj.Type, Is.EqualTo (AVMetadataObjectType.Face), "Type"); #endif } #if !MONOMAC // iOS only using (var obj = new AVMetadataMachineReadableCodeObject ()) { - Assert.IsNotNull (obj.Corners, "Corners"); - Assert.AreEqual (0, obj.Corners.Length, "Corners"); - Assert.IsNull (obj.StringValue, "StringValue"); - Assert.AreEqual (AVMetadataObjectType.None, obj.Type, "Type"); - Assert.IsNull (obj.WeakType, "WeakType"); + Assert.That (obj.Corners, Is.Not.Null, "Corners"); + Assert.That (obj.Corners.Length, Is.EqualTo (0), "Corners"); + Assert.That (obj.StringValue, Is.Null, "StringValue"); + Assert.That (obj.Type, Is.EqualTo (AVMetadataObjectType.None), "Type"); + Assert.That (obj.WeakType, Is.Null, "WeakType"); } #endif } diff --git a/tests/monotouch-test/AVFoundation/PlayerItemTest.cs b/tests/monotouch-test/AVFoundation/PlayerItemTest.cs index 2417f88695c0..6fc574d6cd82 100644 --- a/tests/monotouch-test/AVFoundation/PlayerItemTest.cs +++ b/tests/monotouch-test/AVFoundation/PlayerItemTest.cs @@ -25,10 +25,10 @@ public void FromAssert_Null () { TestRuntime.AssertXcodeVersion (5, 1); // Apple's AVCustomEdit samples calls this with `nil` - Assert.Null (AVPlayerItem.FromAsset (null), "1"); + Assert.That (AVPlayerItem.FromAsset (null), Is.Null, "1"); if (TestRuntime.CheckXcodeVersion (5, 0, 1)) - Assert.Null (AVPlayerItem.FromAsset (null, null), "2"); + Assert.That (AVPlayerItem.FromAsset (null, null), Is.Null, "2"); } } } diff --git a/tests/monotouch-test/AVFoundation/SpeechSynthesisVoiceTest.cs b/tests/monotouch-test/AVFoundation/SpeechSynthesisVoiceTest.cs index 1c84a7aaac46..dfb7fd2fd364 100644 --- a/tests/monotouch-test/AVFoundation/SpeechSynthesisVoiceTest.cs +++ b/tests/monotouch-test/AVFoundation/SpeechSynthesisVoiceTest.cs @@ -34,16 +34,16 @@ public void Default () { // it's not clear that `init` should be called... it works (as it does not crash) but you can't set anything using (var ssv = new AVSpeechSynthesisVoice ()) { - Assert.Null (ssv.Language, "Language"); + Assert.That (ssv.Language, Is.Null, "Language"); } } [Test] public void Static () { - Assert.NotNull (AVSpeechSynthesisVoice.CurrentLanguageCode, "CurrentLanguageCode"); + Assert.That (AVSpeechSynthesisVoice.CurrentLanguageCode, Is.Not.Null, "CurrentLanguageCode"); foreach (var ssv in AVSpeechSynthesisVoice.GetSpeechVoices ()) { - Assert.NotNull (ssv.Language, ssv.Language); + Assert.That (ssv.Language, Is.Not.Null, ssv.Language); } } } diff --git a/tests/monotouch-test/AVFoundation/UtilitiesTest.cs b/tests/monotouch-test/AVFoundation/UtilitiesTest.cs index 63b8597f919d..be5d5608d502 100644 --- a/tests/monotouch-test/AVFoundation/UtilitiesTest.cs +++ b/tests/monotouch-test/AVFoundation/UtilitiesTest.cs @@ -26,7 +26,7 @@ public class UtilitiesTest { public void AspectRatio () { var r = CGRect.Empty.WithAspectRatio (CGSize.Empty); - Assert.True (nfloat.IsNaN (r.Top), "Top"); + Assert.That (nfloat.IsNaN (r.Top), Is.True, "Top"); Assert.That (nfloat.IsNaN (r.Left), "Left"); Assert.That (nfloat.IsNaN (r.Width), "Width"); Assert.That (nfloat.IsNaN (r.Height), "Height"); diff --git a/tests/monotouch-test/AVFoundation/VideoCompositionInstructionTest.cs b/tests/monotouch-test/AVFoundation/VideoCompositionInstructionTest.cs index b20ac786e010..72495f389817 100644 --- a/tests/monotouch-test/AVFoundation/VideoCompositionInstructionTest.cs +++ b/tests/monotouch-test/AVFoundation/VideoCompositionInstructionTest.cs @@ -25,11 +25,11 @@ public class VideoCompositionInstructionTest { public void Defaults () { using (var i = new AVVideoCompositionInstruction ()) { - Assert.Null (i.BackgroundColor, "BackgroundColor"); - Assert.True (i.EnablePostProcessing, "EnablePostProcessing"); - Assert.Null (i.LayerInstructions, "LayerInstructions"); - Assert.True (i.TimeRange.Start.IsInvalid, "TimeRange.Start"); - Assert.True (i.TimeRange.Duration.IsInvalid, "TimeRange.Duration"); + Assert.That (i.BackgroundColor, Is.Null, "BackgroundColor"); + Assert.That (i.EnablePostProcessing, Is.True, "EnablePostProcessing"); + Assert.That (i.LayerInstructions, Is.Null, "LayerInstructions"); + Assert.That (i.TimeRange.Start.IsInvalid, Is.True, "TimeRange.Start"); + Assert.That (i.TimeRange.Duration.IsInvalid, Is.True, "TimeRange.Duration"); } } @@ -39,7 +39,7 @@ public void Seven () TestRuntime.AssertXcodeVersion (5, 0, 1); using (var i = new AVVideoCompositionInstruction ()) { - Assert.False (i.ContainsTweening, "ContainsTweening"); + Assert.That (i.ContainsTweening, Is.False, "ContainsTweening"); Assert.That (i.PassthroughTrackID, Is.EqualTo (0), "PassthroughTrackID"); Assert.That (i.RequiredSourceTrackIDs.Length, Is.EqualTo (0), "RequiredSourceTrackIDs"); } diff --git a/tests/monotouch-test/Accessibility/AXSettings.cs b/tests/monotouch-test/Accessibility/AXSettings.cs index ba7b854d1c50..8a77df4c6663 100644 --- a/tests/monotouch-test/Accessibility/AXSettings.cs +++ b/tests/monotouch-test/Accessibility/AXSettings.cs @@ -35,8 +35,8 @@ public void OpenSettingsFeature () e = error; didComplete.TrySetResult (true); }); - Assert.IsTrue (TestRuntime.RunAsync (TimeSpan.FromSeconds (30), didComplete.Task), "Timed out"); - Assert.IsNull (error); + Assert.That (TestRuntime.RunAsync (TimeSpan.FromSeconds (30), didComplete.Task), Is.True, "Timed out"); + Assert.That (error, Is.Null); } } } diff --git a/tests/monotouch-test/AdSupport/IdentifierManagerTest.cs b/tests/monotouch-test/AdSupport/IdentifierManagerTest.cs index aa1055a0cf5f..5fc4bbaada56 100644 --- a/tests/monotouch-test/AdSupport/IdentifierManagerTest.cs +++ b/tests/monotouch-test/AdSupport/IdentifierManagerTest.cs @@ -22,7 +22,7 @@ public class IdentifierManagerTest { public void SharedManager () { // IsAdvertisingTrackingEnabled - device specific config - Assert.NotNull (ASIdentifierManager.SharedManager.AdvertisingIdentifier, "AdvertisingIdentifier"); + Assert.That (ASIdentifierManager.SharedManager.AdvertisingIdentifier, Is.Not.Null, "AdvertisingIdentifier"); } } } diff --git a/tests/monotouch-test/AddressBook/AddressBookTest.cs b/tests/monotouch-test/AddressBook/AddressBookTest.cs index b08aa4670c46..a25527bfbccc 100644 --- a/tests/monotouch-test/AddressBook/AddressBookTest.cs +++ b/tests/monotouch-test/AddressBook/AddressBookTest.cs @@ -46,7 +46,7 @@ public void GetDefaultSource () { TestRuntime.CheckAddressBookPermission (); ABAddressBook ab = new ABAddressBook (); - Assert.NotNull (ab.GetDefaultSource (), "GetDefaultSource"); + Assert.That (ab.GetDefaultSource (), Is.Not.Null, "GetDefaultSource"); } [Test] @@ -54,9 +54,9 @@ public void GetSource () { TestRuntime.CheckAddressBookPermission (); ABAddressBook ab = new ABAddressBook (); - Assert.Null (ab.GetSource (-1), "-1"); + Assert.That (ab.GetSource (-1), Is.Null, "-1"); // GetSource(0) is not reliable across device/simulator and iOS versions - Assert.Null (ab.GetSource (Int32.MaxValue), "MaxValue"); + Assert.That (ab.GetSource (Int32.MaxValue), Is.Null, "MaxValue"); } [Test] @@ -65,7 +65,7 @@ public void LocalizedLabel () TestRuntime.CheckAddressBookPermission (); var label = ABPersonPhoneLabel.Mobile; var result = ABAddressBook.LocalizedLabel (label); - Assert.NotNull (result, "result"); + Assert.That (result, Is.Not.Null, "result"); Assert.That (result.Length, Is.GreaterThan (0), "Length"); } } diff --git a/tests/monotouch-test/AddressBook/PersonTest.cs b/tests/monotouch-test/AddressBook/PersonTest.cs index c34b5568bbce..d0779b5ff4fb 100644 --- a/tests/monotouch-test/AddressBook/PersonTest.cs +++ b/tests/monotouch-test/AddressBook/PersonTest.cs @@ -37,7 +37,7 @@ public void UpdateAddressLine () NSError err; var ab = ABAddressBook.Create (out err); - Assert.IsNotNull (ab, "#1"); + Assert.That (ab, Is.Not.Null, "#1"); var people = ab.GetPeople (); if (people.Length < 1) { @@ -60,7 +60,7 @@ public void UpdateAddressLine () multi.Value = addr; p.SetAddresses (mutable); - Assert.IsTrue (ab.HasUnsavedChanges); + Assert.That (ab.HasUnsavedChanges, Is.True); ab.Save (); } @@ -69,7 +69,7 @@ public void LocalizedPropertyName () { TestRuntime.CheckAddressBookPermission (); var name = ABPerson.LocalizedPropertyName (ABPersonProperty.FirstName); - Assert.NotNull (name, "name"); + Assert.That (name, Is.Not.Null, "name"); Assert.That (name.Length, Is.GreaterThan (0), "Length"); } @@ -79,7 +79,7 @@ public void LocalizedPropertyName_Int () TestRuntime.CheckAddressBookPermission (); // Use the underlying integer ID for ABPersonProperty.LastName (1) var name = ABPerson.LocalizedPropertyName (1); - Assert.NotNull (name, "name"); + Assert.That (name, Is.Not.Null, "name"); Assert.That (name.Length, Is.GreaterThan (0), "Length"); } @@ -91,7 +91,7 @@ public void PersonToString () person.FirstName = "Test"; person.LastName = "Person"; var str = person.ToString (); - Assert.NotNull (str, "ToString"); + Assert.That (str, Is.Not.Null, "ToString"); } } @@ -100,9 +100,9 @@ public void GetImage_NoImage () { TestRuntime.CheckAddressBookPermission (); using (var person = new ABPerson ()) { - Assert.IsFalse (person.HasImage, "HasImage"); - Assert.IsNull (person.Image, "Image"); - Assert.IsNull (person.GetImage (ABPersonImageFormat.Thumbnail), "GetImage"); + Assert.That (person.HasImage, Is.False, "HasImage"); + Assert.That (person.Image, Is.Null, "Image"); + Assert.That (person.GetImage (ABPersonImageFormat.Thumbnail), Is.Null, "GetImage"); } } @@ -113,7 +113,7 @@ public void GetLinkedPeople () using (var person = new ABPerson ()) { var linked = person.GetLinkedPeople (); // A new person not in the address book may return null or empty - Assert.IsTrue (linked is null || linked.Length >= 0, "GetLinkedPeople"); + Assert.That (linked is null || linked.Length >= 0, Is.True, "GetLinkedPeople"); } } @@ -124,7 +124,7 @@ public void CreateFromVCard () var vcard = "BEGIN:VCARD\nVERSION:3.0\nFN:Test Person\nN:Person;Test;;;\nEND:VCARD\n"; using (var data = NSData.FromString (vcard)) { var people = ABPerson.CreateFromVCard (null, data); - Assert.NotNull (people, "people"); + Assert.That (people, Is.Not.Null, "people"); Assert.That (people.Length, Is.GreaterThan (0), "Length"); } } @@ -135,7 +135,7 @@ public void PropertyToString_FirstName () TestRuntime.CheckAddressBookPermission (); using (var person = new ABPerson ()) { person.FirstName = "TestFirst"; - Assert.AreEqual ("TestFirst", person.FirstName, "FirstName"); + Assert.That (person.FirstName, Is.EqualTo ("TestFirst"), "FirstName"); } } @@ -150,7 +150,7 @@ public void MultiValueLabel () var allPhones = person.GetPhones (); Assert.That (allPhones.Count, Is.GreaterThan (0), "Count"); - Assert.NotNull (allPhones [0].Label, "Label"); + Assert.That (allPhones [0].Label, Is.Not.Null, "Label"); } } @@ -166,7 +166,7 @@ public void MultiValueGetValues () var allPhones = person.GetPhones (); var values = allPhones.GetValues (); - Assert.NotNull (values, "values"); + Assert.That (values, Is.Not.Null, "values"); Assert.That (values.Length, Is.EqualTo (2), "Length"); } } diff --git a/tests/monotouch-test/AddressBook/SourceTest.cs b/tests/monotouch-test/AddressBook/SourceTest.cs index 8cc76aaf1828..77bb5091a461 100644 --- a/tests/monotouch-test/AddressBook/SourceTest.cs +++ b/tests/monotouch-test/AddressBook/SourceTest.cs @@ -37,7 +37,7 @@ public void Default () // we assume the simulator defaults (e.g. after a reset) ABSource source = new ABAddressBook ().GetDefaultSource (); - Assert.Null (source.Name, "Name"); + Assert.That (source.Name, Is.Null, "Name"); Assert.That (source.SourceType, Is.EqualTo (ABSourceType.Local), "SourceType"); // ABRecord diff --git a/tests/monotouch-test/AppKit/DerivedEventTest.cs b/tests/monotouch-test/AppKit/DerivedEventTest.cs index 8a8776cf1f2e..b0db947afc5d 100644 --- a/tests/monotouch-test/AppKit/DerivedEventTest.cs +++ b/tests/monotouch-test/AppKit/DerivedEventTest.cs @@ -30,16 +30,16 @@ public void DerivedEvents_DontStompEachOther () void TestDelegates (NSComboBox b) { NSTextField f = (NSTextField) b; - Assert.IsNotNull (b.Delegate, "NSComboBox delegate null"); - Assert.IsNotNull (f.Delegate, "NSTextField delegate null"); - Assert.AreEqual (b.Delegate.GetHashCode (), f.Delegate.GetHashCode (), "Delegates are not equal"); + Assert.That (b.Delegate, Is.Not.Null, "NSComboBox delegate null"); + Assert.That (f.Delegate, Is.Not.Null, "NSTextField delegate null"); + Assert.That (f.Delegate.GetHashCode (), Is.EqualTo (b.Delegate.GetHashCode ()), "Delegates are not equal"); } [Test] public void DerivedEvents_OverwriteThrows () { #if RELEASE - var checkTrimmedAway = TestRuntime.IsLinkAll; + var checkTrimmedAway = TestRuntime.IsLinkAny; #else var checkTrimmedAway = false; #endif @@ -72,7 +72,7 @@ void TestOverrideThrow (bool eventFirst, bool shouldThrow) didThrow = true; } if (shouldThrow != didThrow) - Assert.Fail ("TestOverrideThrow ({0}, {1}) did not have expected thrown status", eventFirst, shouldThrow); + Assert.Fail ($"TestOverrideThrow ({eventFirst}, {shouldThrow}) did not have expected thrown status"); } } } diff --git a/tests/monotouch-test/AppKit/NSAppearance.cs b/tests/monotouch-test/AppKit/NSAppearance.cs index 08db5f6ed405..666e8d8c9fd3 100644 --- a/tests/monotouch-test/AppKit/NSAppearance.cs +++ b/tests/monotouch-test/AppKit/NSAppearance.cs @@ -10,8 +10,8 @@ public class NSAppearanceTests { public void NSAppearanceShouldLoadAppearanceNamed () { var appearance = NSAppearance.GetAppearance (NSAppearance.NameVibrantDark); - Assert.IsNotNull (appearance, "NSAppearanceShouldLoadAppearanceNamed - Failed to initialize appearance VibrantDark"); - Assert.AreEqual (appearance.Name, NSAppearance.NameVibrantDark.ToString (), "NSAppearanceShouldLoadAppearanceNamed - Appearance initialized with incorrect name."); + Assert.That (appearance, Is.Not.Null, "NSAppearanceShouldLoadAppearanceNamed - Failed to initialize appearance VibrantDark"); + Assert.That (NSAppearance.NameVibrantDark.ToString (), Is.EqualTo (appearance.Name), "NSAppearanceShouldLoadAppearanceNamed - Appearance initialized with incorrect name."); } #if FALSE // Test failing, exception doesn't appear to be thrown during test, throw correctly running in an app. @@ -26,7 +26,7 @@ public void NSAppearanceConstructorShouldFailWithInvalidName () exceptionHit = true; } - Assert.IsTrue (exceptionHit, "NSAppearanceConstructorShouldFailWithInvalidName - No exception thrown while initializing appearance with invalid name."); + Assert.That (exceptionHit, Is.True, "NSAppearanceConstructorShouldFailWithInvalidName - No exception thrown while initializing appearance with invalid name."); } #endif @@ -37,7 +37,7 @@ public void NSAppearanceShouldChangeCurrentAppearance () NSAppearance.CurrentAppearance = NSAppearance.GetAppearance (NSAppearance.NameVibrantDark); - Assert.AreNotEqual (appearance, NSAppearance.CurrentAppearance, "NSAppearanceShouldChangeCurrentAppearance - Failed to change appearance."); + Assert.That (NSAppearance.CurrentAppearance, Is.Not.EqualTo (appearance), "NSAppearanceShouldChangeCurrentAppearance - Failed to change appearance."); } [Test] diff --git a/tests/monotouch-test/AppKit/NSCellTest.cs b/tests/monotouch-test/AppKit/NSCellTest.cs index c4a6a5b3e2ee..d61181496817 100644 --- a/tests/monotouch-test/AppKit/NSCellTest.cs +++ b/tests/monotouch-test/AppKit/NSCellTest.cs @@ -25,15 +25,15 @@ void Check (IntPtr cell_handle) var clone_ptr = IntPtr_objc_msgSend (cell_handle, Selector.GetHandle ("copyWithZone:"), IntPtr.Zero); // Console.WriteLine ("Created cell 0x{0} (GCHandle: 0x{2}) with clone 0x{1} (GCHandle: 0x{3})", cell_handle.ToString ("x"), clone_ptr.ToString ("x"), GetGCHandle (cell_handle).ToString ("x"), GetGCHandle (clone_ptr).ToString ("x")); - Assert.AreNotEqual (GetGCHandle (cell_handle), GetGCHandle (clone_ptr), "gchandle #1"); + Assert.That (GetGCHandle (clone_ptr), Is.Not.EqualTo (GetGCHandle (cell_handle)), "gchandle #1"); CustomCell.expectedHandle = cell_handle; objc_msgSend (Class.GetHandle (typeof (CustomCell)), Selector.GetHandle ("foo:"), cell_handle); - Assert.AreNotEqual (GetGCHandle (cell_handle), GetGCHandle (clone_ptr), "gchandle #2"); + Assert.That (GetGCHandle (clone_ptr), Is.Not.EqualTo (GetGCHandle (cell_handle)), "gchandle #2"); CustomCell.expectedHandle = clone_ptr; objc_msgSend (Class.GetHandle (typeof (CustomCell)), Selector.GetHandle ("foo:"), clone_ptr); - Assert.AreNotEqual (GetGCHandle (cell_handle), GetGCHandle (clone_ptr), "gchandle #3"); + Assert.That (GetGCHandle (clone_ptr), Is.Not.EqualTo (GetGCHandle (cell_handle)), "gchandle #3"); objc_msgSend (clone_ptr, Selector.GetHandle ("release")); } @@ -65,7 +65,7 @@ public CustomCell () { } [Export ("foo:")] public static void Foo (CustomCell mySelf) { - Assert.AreEqual (expectedHandle, mySelf.Handle, "Handle"); + Assert.That (mySelf.Handle, Is.EqualTo (expectedHandle), "Handle"); } } diff --git a/tests/monotouch-test/AppKit/NSClipView.cs b/tests/monotouch-test/AppKit/NSClipView.cs index 3679240ef32a..32d21d89c46d 100644 --- a/tests/monotouch-test/AppKit/NSClipView.cs +++ b/tests/monotouch-test/AppKit/NSClipView.cs @@ -13,10 +13,10 @@ public void NSClipViewConstrainBoundsRect () var clipView = new NSClipView (new CGRect (0, 0, 50, 50)); var rect = clipView.ConstrainBoundsRect (new CGRect (10, 10, 30, 30)); - Assert.IsTrue (rect.X == 0, "NSClipViewConstrainBoundsRect - X value was not 0"); - Assert.IsTrue (rect.Y == 0, "NSClipViewConstrainBoundsRect - Y value was not 0"); - Assert.IsTrue (rect.Width == 30, "NSClipViewConstrainBoundsRect - Width value was not 30"); - Assert.IsTrue (rect.Height == 30, "NSClipViewConstrainBoundsRect - Height value was not 30"); + Assert.That (rect.X == 0, Is.True, "NSClipViewConstrainBoundsRect - X value was not 0"); + Assert.That (rect.Y == 0, Is.True, "NSClipViewConstrainBoundsRect - Y value was not 0"); + Assert.That (rect.Width == 30, Is.True, "NSClipViewConstrainBoundsRect - Width value was not 30"); + Assert.That (rect.Height == 30, Is.True, "NSClipViewConstrainBoundsRect - Height value was not 30"); } } } diff --git a/tests/monotouch-test/AppKit/NSColor.cs b/tests/monotouch-test/AppKit/NSColor.cs index d0efb2e77952..288a4e78964f 100644 --- a/tests/monotouch-test/AppKit/NSColor.cs +++ b/tests/monotouch-test/AppKit/NSColor.cs @@ -13,9 +13,9 @@ public void NSColor_ComponentTests () NSColor c = NSColor.Blue; nfloat [] components; c.GetComponents (out components); - Assert.IsTrue (0f == components [0], "Red"); - Assert.IsTrue (0f == components [1], "Green"); - Assert.IsTrue (1f == components [2], "Blue"); + Assert.That (0f == components [0], Is.True, "Red"); + Assert.That (0f == components [1], Is.True, "Green"); + Assert.That (1f == components [2], Is.True, "Blue"); } [Test] @@ -24,9 +24,9 @@ public void SingleComponents () var c = NSColor.Red; nfloat [] components; c.GetComponents (out components); - Assert.AreEqual (c.RedComponent, components [0], "Red"); - Assert.AreEqual (c.GreenComponent, components [1], "Green"); - Assert.AreEqual (c.BlueComponent, components [2], "Blue"); + Assert.That (components [0], Is.EqualTo (c.RedComponent), "Red"); + Assert.That (components [1], Is.EqualTo (c.GreenComponent), "Green"); + Assert.That (components [2], Is.EqualTo (c.BlueComponent), "Blue"); } [Test] @@ -36,10 +36,10 @@ public void FromColorSpace () using var color = NSColor.FromColorSpace (NSColorSpace.GenericRGBColorSpace, components); color.GetComponents (out var actualComponents); - Assert.AreEqual (components [0], actualComponents [0], "Red"); - Assert.AreEqual (components [1], actualComponents [1], "Green"); - Assert.AreEqual (components [2], actualComponents [2], "Blue"); - Assert.AreEqual (components [3], actualComponents [3], "Alpha"); + Assert.That (actualComponents [0], Is.EqualTo (components [0]), "Red"); + Assert.That (actualComponents [1], Is.EqualTo (components [1]), "Green"); + Assert.That (actualComponents [2], Is.EqualTo (components [2]), "Blue"); + Assert.That (actualComponents [3], Is.EqualTo (components [3]), "Alpha"); } } } diff --git a/tests/monotouch-test/AppKit/NSControl.cs b/tests/monotouch-test/AppKit/NSControl.cs index 1e96c6b37ed0..5eaaac003ed5 100644 --- a/tests/monotouch-test/AppKit/NSControl.cs +++ b/tests/monotouch-test/AppKit/NSControl.cs @@ -13,8 +13,8 @@ public void NSControlShouldChangeControlSize () var size = control.ControlSize; control.ControlSize = NSControlSize.Mini; - Assert.IsFalse (size == control.ControlSize); - Assert.IsTrue (control.ControlSize == NSControlSize.Mini); + Assert.That (control.ControlSize, Is.Not.EqualTo (size)); + Assert.That (control.ControlSize, Is.EqualTo (NSControlSize.Mini)); } [Test] @@ -24,7 +24,7 @@ public void NSControlShouldChangeHighlighted () var highlighted = control.Highlighted; control.Highlighted = !highlighted; - Assert.IsFalse (highlighted == control.Highlighted); + Assert.That (control.Highlighted, Is.Not.EqualTo (highlighted)); } [Test] @@ -34,8 +34,8 @@ public void NSControlShouldChangeLineBreakMode () var lineBreak = control.LineBreakMode; control.LineBreakMode = NSLineBreakMode.Clipping; - Assert.IsTrue (control.LineBreakMode == NSLineBreakMode.Clipping); - Assert.IsFalse (lineBreak == control.LineBreakMode); + Assert.That (control.LineBreakMode, Is.EqualTo (NSLineBreakMode.Clipping)); + Assert.That (control.LineBreakMode, Is.Not.EqualTo (lineBreak)); } [Test] @@ -51,8 +51,8 @@ public void NSControlShouldAddMultipleActivatedEventHandlers () control.PerformClick (control); - Assert.IsTrue (firstHitCount == 1, "NSControlShouldAddMultipleActivatedEventHandlers - Did not call first EventHandler"); - Assert.IsTrue (secondHitCount == 1, "NSControlShouldAddMultipleActivatedEventHandlers - Did not call second EventHandler"); + Assert.That (firstHitCount, Is.EqualTo (1), "NSControlShouldAddMultipleActivatedEventHandlers - Did not call first EventHandler"); + Assert.That (secondHitCount, Is.EqualTo (1), "NSControlShouldAddMultipleActivatedEventHandlers - Did not call second EventHandler"); } [Test] @@ -71,8 +71,8 @@ public void NSControlShouldRemoveAndAddActivatedEventHandlers () control.PerformClick (control); - Assert.IsTrue (firstHitCount == 0, "NSControlShouldRemoveAndAddActivatedEventHandlers - Called first EventHandler after it was removed"); - Assert.IsTrue (secondHitCount == 1, "NSControlShouldRemoveAndAddActivatedEventHandlers - Did not call second EventHandler"); + Assert.That (firstHitCount, Is.EqualTo (0), "NSControlShouldRemoveAndAddActivatedEventHandlers - Called first EventHandler after it was removed"); + Assert.That (secondHitCount, Is.EqualTo (1), "NSControlShouldRemoveAndAddActivatedEventHandlers - Did not call second EventHandler"); } } } diff --git a/tests/monotouch-test/AppKit/NSEvent.cs b/tests/monotouch-test/AppKit/NSEvent.cs index 640c31eda996..bf0abdf689ed 100644 --- a/tests/monotouch-test/AppKit/NSEvent.cs +++ b/tests/monotouch-test/AppKit/NSEvent.cs @@ -12,7 +12,7 @@ public void Create () { using var cgevent = new CGEvent (null, (ushort) 1, true); using var nsevent = NSEvent.Create (cgevent); - Assert.AreEqual ((int) cgevent.EventType, (int) nsevent.Type, "[Event]Type"); + Assert.That ((int) nsevent.Type, Is.EqualTo ((int) cgevent.EventType), "[Event]Type"); } } } diff --git a/tests/monotouch-test/AppKit/NSFont.cs b/tests/monotouch-test/AppKit/NSFont.cs index fc69e6ae01ac..7e9ccbde14e2 100644 --- a/tests/monotouch-test/AppKit/NSFont.cs +++ b/tests/monotouch-test/AppKit/NSFont.cs @@ -23,8 +23,8 @@ public void GetBoundingRect_SmokeTest () var bounding = nsFont.GetBoundingRects (glyphs); var advancement = nsFont.GetAdvancements (glyphs); - Assert.AreEqual (5, bounding.Length); - Assert.AreEqual (5, advancement.Length); + Assert.That (bounding.Length, Is.EqualTo (5)); + Assert.That (advancement.Length, Is.EqualTo (5)); } [Test] diff --git a/tests/monotouch-test/AppKit/NSGradient.cs b/tests/monotouch-test/AppKit/NSGradient.cs index f441ee5c3f0e..ed86b4f42d6f 100644 --- a/tests/monotouch-test/AppKit/NSGradient.cs +++ b/tests/monotouch-test/AppKit/NSGradient.cs @@ -11,9 +11,9 @@ public void NSGradientConstructorTests () { NSColorSpace colorSpace = NSColorSpace.GenericRGBColorSpace; NSGradient g = new NSGradient (new [] { NSColor.Black, NSColor.White, NSColor.Black }, new [] { 0f, .5f, 1.0f }, colorSpace); - Assert.IsNotNull (g); - Assert.AreEqual (colorSpace, g.ColorSpace); - Assert.AreEqual ((nint) 3, g.ColorStopsCount); + Assert.That (g, Is.Not.Null); + Assert.That (g.ColorSpace, Is.EqualTo (colorSpace)); + Assert.That (g.ColorStopsCount, Is.EqualTo ((nint) 3)); // Since we are asking for colors on a gradient, there will be some color blending, even with just black and white. const float closeEnough = .05f; @@ -25,24 +25,24 @@ public void NSGradientConstructorTests () g.GetColor (out color, out location, 0); color = color.UsingColorSpace (NSColorSpace.CalibratedRGB); - Assert.IsTrue (black.RedComponent - color.RedComponent < closeEnough); - Assert.IsTrue (black.BlueComponent - color.BlueComponent < closeEnough); - Assert.IsTrue (black.GreenComponent - color.GreenComponent < closeEnough); - Assert.AreEqual (0.0f, (float) location); + Assert.That (black.RedComponent - color.RedComponent < closeEnough, Is.True); + Assert.That (black.BlueComponent - color.BlueComponent < closeEnough, Is.True); + Assert.That (black.GreenComponent - color.GreenComponent < closeEnough, Is.True); + Assert.That ((float) location, Is.EqualTo (0.0f)); g.GetColor (out color, out location, 1); color = color.UsingColorSpace (NSColorSpace.CalibratedRGB); - Assert.IsTrue (white.RedComponent - color.RedComponent < closeEnough); - Assert.IsTrue (white.BlueComponent - color.BlueComponent < closeEnough); - Assert.IsTrue (white.GreenComponent - color.GreenComponent < closeEnough); - Assert.AreEqual (0.5f, (float) location); + Assert.That (white.RedComponent - color.RedComponent < closeEnough, Is.True); + Assert.That (white.BlueComponent - color.BlueComponent < closeEnough, Is.True); + Assert.That (white.GreenComponent - color.GreenComponent < closeEnough, Is.True); + Assert.That ((float) location, Is.EqualTo (0.5f)); g.GetColor (out color, out location, 2); color = color.UsingColorSpace (NSColorSpace.CalibratedRGB); - Assert.IsTrue (black.RedComponent - color.RedComponent < closeEnough); - Assert.IsTrue (black.BlueComponent - color.BlueComponent < closeEnough); - Assert.IsTrue (black.GreenComponent - color.GreenComponent < closeEnough); - Assert.AreEqual (1.0f, (float) location); + Assert.That (black.RedComponent - color.RedComponent < closeEnough, Is.True); + Assert.That (black.BlueComponent - color.BlueComponent < closeEnough, Is.True); + Assert.That (black.GreenComponent - color.GreenComponent < closeEnough, Is.True); + Assert.That ((float) location, Is.EqualTo (1.0f)); } } } diff --git a/tests/monotouch-test/AppKit/NSGraphics.cs b/tests/monotouch-test/AppKit/NSGraphics.cs index e2537d0c54ee..f29cd9885b25 100644 --- a/tests/monotouch-test/AppKit/NSGraphics.cs +++ b/tests/monotouch-test/AppKit/NSGraphics.cs @@ -13,8 +13,8 @@ public void BestDepth () { bool exactMatch = false; var rv = NSGraphics.BestDepth (NSColorSpace.DeviceRGB, 8, 8, false, ref exactMatch); - Assert.AreEqual (NSWindowDepth.TwentyfourBitRgb, rv, "BestDepth"); - Assert.IsTrue (exactMatch, "ExactMatch"); + Assert.That (rv, Is.EqualTo (NSWindowDepth.TwentyfourBitRgb), "BestDepth"); + Assert.That (exactMatch, Is.True, "ExactMatch"); } #endif @@ -22,8 +22,8 @@ public void BestDepth () public void GetBestDepth () { var rv = NSGraphics.GetBestDepth (NSColorSpace.DeviceRGB, 8, 8, false, out var exactMatch); - Assert.AreEqual (NSWindowDepth.TwentyfourBitRgb, rv, "GetBestDepth"); - Assert.IsTrue (exactMatch, "ExactMatch"); + Assert.That (rv, Is.EqualTo (NSWindowDepth.TwentyfourBitRgb), "GetBestDepth"); + Assert.That (exactMatch, Is.True, "ExactMatch"); } } } diff --git a/tests/monotouch-test/AppKit/NSGridViewTest.cs b/tests/monotouch-test/AppKit/NSGridViewTest.cs index 9640d05af1de..e75b3e6f3a0a 100644 --- a/tests/monotouch-test/AppKit/NSGridViewTest.cs +++ b/tests/monotouch-test/AppKit/NSGridViewTest.cs @@ -23,11 +23,11 @@ public void CreateWithNSViewArrayOfArrayCheckNSTextView () NSGridView nSGridViewArrayOfArray = NSGridView.Create (nSViewsArrayOfArray); - Assert.NotNull (nSGridViewArrayOfArray); - Assert.AreEqual ("0", ((NSTextView) (nSGridViewArrayOfArray.GetCell (0, 0)).ContentView).Value, "0,0"); - Assert.AreEqual ("1", ((NSTextView) (nSGridViewArrayOfArray.GetCell (0, 1)).ContentView).Value, "0,1"); - Assert.AreEqual ("2", ((NSTextView) (nSGridViewArrayOfArray.GetCell (0, 2)).ContentView).Value, "0,2"); - Assert.AreEqual ("3", ((NSTextView) (nSGridViewArrayOfArray.GetCell (0, 3)).ContentView).Value, "0,3"); + Assert.That (nSGridViewArrayOfArray, Is.Not.Null); + Assert.That (((NSTextView) (nSGridViewArrayOfArray.GetCell (0, 0)).ContentView).Value, Is.EqualTo ("0"), "0,0"); + Assert.That (((NSTextView) (nSGridViewArrayOfArray.GetCell (0, 1)).ContentView).Value, Is.EqualTo ("1"), "0,1"); + Assert.That (((NSTextView) (nSGridViewArrayOfArray.GetCell (0, 2)).ContentView).Value, Is.EqualTo ("2"), "0,2"); + Assert.That (((NSTextView) (nSGridViewArrayOfArray.GetCell (0, 3)).ContentView).Value, Is.EqualTo ("3"), "0,3"); } [Test] @@ -39,10 +39,10 @@ public void CreateWithNSViewArrayOfArrayCheckDifferentArrayLength () NSGridView nSGridViewArrayOfArray = NSGridView.Create (nSViewsArrayOfArray); - Assert.NotNull (nSGridViewArrayOfArray); - Assert.AreEqual ("0", ((NSTextView) (nSGridViewArrayOfArray.GetCell (0, 0)).ContentView).Value, "0,0"); - Assert.AreEqual ("1", ((NSTextView) (nSGridViewArrayOfArray.GetCell (0, 1)).ContentView).Value, "0,1"); - Assert.AreEqual ("1bis", ((NSTextView) (nSGridViewArrayOfArray.GetCell (1, 1)).ContentView).Value, "0,2"); + Assert.That (nSGridViewArrayOfArray, Is.Not.Null); + Assert.That (((NSTextView) (nSGridViewArrayOfArray.GetCell (0, 0)).ContentView).Value, Is.EqualTo ("0"), "0,0"); + Assert.That (((NSTextView) (nSGridViewArrayOfArray.GetCell (0, 1)).ContentView).Value, Is.EqualTo ("1"), "0,1"); + Assert.That (((NSTextView) (nSGridViewArrayOfArray.GetCell (1, 1)).ContentView).Value, Is.EqualTo ("1bis"), "0,2"); } [Test] @@ -56,11 +56,11 @@ public void CreateWithTwoDimensionalNSViewArrayNSTextView () NSGridView nSGridViewTwoDimensionalArray = NSGridView.Create (nSViewsTwoDim); - Assert.NotNull (nSGridViewTwoDimensionalArray); - Assert.AreEqual ("0", ((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (0, 0)).ContentView).Value, "0,0"); - Assert.AreEqual ("1", ((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (0, 1)).ContentView).Value, "0,1"); - Assert.AreEqual ("2", ((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (1, 0)).ContentView).Value, "1,0"); - Assert.AreEqual ("3", ((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (1, 1)).ContentView).Value, "1,1"); + Assert.That (nSGridViewTwoDimensionalArray, Is.Not.Null); + Assert.That (((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (0, 0)).ContentView).Value, Is.EqualTo ("0"), "0,0"); + Assert.That (((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (0, 1)).ContentView).Value, Is.EqualTo ("1"), "0,1"); + Assert.That (((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (1, 0)).ContentView).Value, Is.EqualTo ("2"), "1,0"); + Assert.That (((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (1, 1)).ContentView).Value, Is.EqualTo ("3"), "1,1"); } [Test] @@ -74,11 +74,11 @@ public void CreateWithTwoDimensionalNSViewArrayCheckDifferentDimensionSize () NSGridView nSGridViewTwoDimensionalArray = NSGridView.Create (nSViewsTwoDim); - Assert.NotNull (nSGridViewTwoDimensionalArray); - Assert.AreEqual ("0", ((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (0, 0)).ContentView).Value, "0,0"); - Assert.AreEqual ("1", ((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (0, 1)).ContentView).Value, "0,1"); - Assert.AreEqual ("2", ((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (0, 2)).ContentView).Value, "0,2"); - Assert.AreEqual ("3", ((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (0, 3)).ContentView).Value, "0,3"); + Assert.That (nSGridViewTwoDimensionalArray, Is.Not.Null); + Assert.That (((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (0, 0)).ContentView).Value, Is.EqualTo ("0"), "0,0"); + Assert.That (((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (0, 1)).ContentView).Value, Is.EqualTo ("1"), "0,1"); + Assert.That (((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (0, 2)).ContentView).Value, Is.EqualTo ("2"), "0,2"); + Assert.That (((NSTextView) (nSGridViewTwoDimensionalArray.GetCell (0, 3)).ContentView).Value, Is.EqualTo ("3"), "0,3"); } [Test] diff --git a/tests/monotouch-test/AppKit/NSImage.cs b/tests/monotouch-test/AppKit/NSImage.cs index c48003c598f9..16ad181a2e1a 100644 --- a/tests/monotouch-test/AppKit/NSImage.cs +++ b/tests/monotouch-test/AppKit/NSImage.cs @@ -13,7 +13,7 @@ public void ImageWithSize () var image = NSImage.ImageWithSize (new CGSize (50, 50), false, rect => { return true; }); - Assert.IsNotNull (image); + Assert.That (image, Is.Not.Null); } [Test] @@ -22,11 +22,11 @@ public void NSImageCapInsets () var image = new NSImage (); image.CapInsets = new NSEdgeInsets (5f, 6f, 7f, 8f); - Assert.IsNotNull (image.CapInsets); - Assert.IsTrue (image.CapInsets.Top == 5f, "NSImageCapInsets - Top value was not 5"); - Assert.IsTrue (image.CapInsets.Left == 6f, "NSImageCapInsets - Left value was not 6"); - Assert.IsTrue (image.CapInsets.Bottom == 7f, "NSImageCapInsets - Bottom value was not 7"); - Assert.IsTrue (image.CapInsets.Right == 8f, "NSImageCapInsets - Right value was not 8"); + Assert.That (image.CapInsets, Is.Not.Null); + Assert.That (image.CapInsets.Top == 5f, Is.True, "NSImageCapInsets - Top value was not 5"); + Assert.That (image.CapInsets.Left == 6f, Is.True, "NSImageCapInsets - Left value was not 6"); + Assert.That (image.CapInsets.Bottom == 7f, Is.True, "NSImageCapInsets - Bottom value was not 7"); + Assert.That (image.CapInsets.Right == 8f, Is.True, "NSImageCapInsets - Right value was not 8"); } [Test] @@ -34,8 +34,8 @@ public void NSImageResizingModeShouldChange () { var image = new NSImage (); image.ResizingMode = NSImageResizingMode.Stretch; - Assert.AreEqual (image.ResizingMode, NSImageResizingMode.Stretch, "NSImageResizingMode - Was not equal to Stretch"); - Assert.AreNotEqual (image.ResizingMode, NSImageResizingMode.Tile, "NSImageResizingMode - Was incorrectly equal to Tile"); + Assert.That (NSImageResizingMode.Stretch, Is.EqualTo (image.ResizingMode), "NSImageResizingMode - Was not equal to Stretch"); + Assert.That (NSImageResizingMode.Tile, Is.Not.EqualTo (image.ResizingMode), "NSImageResizingMode - Was incorrectly equal to Tile"); } } } diff --git a/tests/monotouch-test/AppKit/NSLayoutManagerTests.cs b/tests/monotouch-test/AppKit/NSLayoutManagerTests.cs index 6ecdf24637b4..b6f5629e9e7c 100644 --- a/tests/monotouch-test/AppKit/NSLayoutManagerTests.cs +++ b/tests/monotouch-test/AppKit/NSLayoutManagerTests.cs @@ -35,7 +35,7 @@ public void NSLayoutManager_CharacterRangeForGlyphRange () { NSRange pnt; NSRange range = manager.GetCharacterRange (new NSRange (0, 4), out pnt); - Assert.IsNotNull (range); + Assert.That (range, Is.Not.Null); } [Test] @@ -43,7 +43,7 @@ public void NSLayoutManager_GlyphRangeForCharacterRange () { NSRange pnt; NSRange range = manager.GetGlyphRange (new NSRange (0, 4), out pnt); - Assert.IsNotNull (range); + Assert.That (range, Is.Not.Null); } } } diff --git a/tests/monotouch-test/AppKit/NSOpenGLPixelFormat.cs b/tests/monotouch-test/AppKit/NSOpenGLPixelFormat.cs index 02ade0fbb44d..54a66ec87f78 100644 --- a/tests/monotouch-test/AppKit/NSOpenGLPixelFormat.cs +++ b/tests/monotouch-test/AppKit/NSOpenGLPixelFormat.cs @@ -18,7 +18,7 @@ public void NSOpenGLPixelFormatAttributesShouldPassWith0Terminate () }; NSOpenGLPixelFormat pixelFormat = new NSOpenGLPixelFormat (_attribs); - Assert.NotNull (pixelFormat); + Assert.That (pixelFormat, Is.Not.Null); } [Test] @@ -28,7 +28,7 @@ public void NSOpenGLPixelFormatAttributesShouldWorkWithEmptyAttributes () }; NSOpenGLPixelFormat pixelFormat = new NSOpenGLPixelFormat (_attribs); - Assert.NotNull (pixelFormat); + Assert.That (pixelFormat, Is.Not.Null); } [Test] diff --git a/tests/monotouch-test/AppKit/NSPasteboard.cs b/tests/monotouch-test/AppKit/NSPasteboard.cs index 1e8bcc02bf39..82455b33b237 100644 --- a/tests/monotouch-test/AppKit/NSPasteboard.cs +++ b/tests/monotouch-test/AppKit/NSPasteboard.cs @@ -129,7 +129,7 @@ public void DetectPatternTests_StronglyTyped () Assert.That (evt.WaitOne (TimeSpan.FromSeconds (1)), "StronglyTyped DetectPatterns #2 wait"); Assert.That (detectedPatterns, Is.Not.Null, "StronglyTyped DetectedPatterns #2 patterns"); Assert.That ((int) detectedPatterns.Count, Is.EqualTo (1), "StronglyTyped DetectedPatterns #2 count"); - Assert.That (detectedPatterns, Does.Contain (NSPasteboardDetectionPattern.EmailAddress), "StronglyTyped DetectedPatterns #2 email"); + Assert.That (detectedPatterns.Contains (NSPasteboardDetectionPattern.EmailAddress), "StronglyTyped DetectedPatterns #2 email"); Assert.That (error, Is.Null, "StronglyTyped DetectedPatterns #2 error"); } finally { pasteboard.ReleaseGlobally (); @@ -294,7 +294,7 @@ public void DetectValuesTests_StronglyTyped () Assert.That (evt.WaitOne (TimeSpan.FromSeconds (1)), "StronglyTyped DetectValues #2 wait"); Assert.That (detected, Is.Not.Null, "StronglyTyped DetectValues #2 patterns"); Assert.That ((int) detected.Count, Is.EqualTo (1), "StronglyTyped DetectValues #2 count"); - Assert.That (detected.Keys, Does.Contain (NSPasteboardDetectionPattern.EmailAddress), "StronglyTyped DetectValues #2 email"); + Assert.That (detected.Keys.Contains (NSPasteboardDetectionPattern.EmailAddress), "StronglyTyped DetectValues #2 email"); matches = detected.Values.First (); Assert.That (matches.Length, Is.EqualTo (1), "StronglyTyped DetectValues #2 matches.Length"); match = matches [0]; @@ -312,7 +312,7 @@ public void DetectValuesTests_StronglyTyped () Assert.That (evt.WaitOne (TimeSpan.FromSeconds (1)), "StronglyTyped DetectValues #3 wait"); Assert.That (detected, Is.Not.Null, "StronglyTyped DetectValues #3 patterns"); Assert.That ((int) detected.Count, Is.EqualTo (1), "StronglyTyped DetectValues #3 count"); - Assert.That (detected.Keys, Does.Contain (NSPasteboardDetectionPattern.EmailAddress), "StronglyTyped DetectValues #3 email"); + Assert.That (detected.Keys.Contains (NSPasteboardDetectionPattern.EmailAddress), "StronglyTyped DetectValues #3 email"); matches = detected.Values.First (); Assert.That (matches.Length, Is.EqualTo (1), "StronglyTyped DetectValues #3 matches.Length"); match = matches [0]; @@ -349,19 +349,26 @@ public void DetectMetadataTests_WeaklyTyped () detected = null; error = null; pasteboard.DetectMetadata (hashSet, callback); - Assert.That (evt.WaitOne (TimeSpan.FromSeconds (1)), "WeaklyTyped DetectMetadata #1 wait"); + Assert.That (evt.WaitOne (TimeSpan.FromSeconds (10)), "WeaklyTyped DetectMetadata #1 wait"); Assert.That (detected, Is.Not.Null, "WeaklyTyped DetectMetadata #1 patterns"); Assert.That ((int) detected.Count, Is.EqualTo (0), "WeaklyTyped DetectMetadata #1 count"); Assert.That (error, Is.Null, "WeaklyTyped DetectMetadata #1 error"); pasteboard.ClearContents (); pasteboard.SetStringForType ("file:///this/is/some/file.html", NSPasteboardType.FileUrl.GetConstant ()); - evt.Reset (); - detected = null; - error = null; - pasteboard.DetectMetadata (hashSet, callback); - Assert.That (evt.WaitOne (TimeSpan.FromSeconds (1)), "WeaklyTyped DetectMetadata #2 wait"); - Assert.That (detected, Is.Not.Null, "WeaklyTyped DetectMetadata #2 patterns"); + // The pasteboard subsystem may need time to analyze content metadata, + // so retry detection if it returns empty results. + for (int attempt = 0; attempt < 5; attempt++) { + evt.Reset (); + detected = null; + error = null; + pasteboard.DetectMetadata (hashSet, callback); + Assert.That (evt.WaitOne (TimeSpan.FromSeconds (10)), "WeaklyTyped DetectMetadata #2 wait"); + Assert.That (detected, Is.Not.Null, "WeaklyTyped DetectMetadata #2 patterns"); + if ((int) detected.Count > 0) + break; + Thread.Sleep (500); + } Assert.That ((int) detected.Count, Is.EqualTo (1), "WeaklyTyped DetectMetadata #2 count"); Assert.That (detected.Keys.First ().ToString (), Does.Contain (NSPasteboardMetadataType.ContentType.GetConstant ().ToString ()), "WeaklyTyped DetectMetadata #2 email"); Assert.That (detected.Values.First ().ToString (), Does.Contain ("public.html"), "WeaklyTyped DetectMetadata #2 value"); @@ -375,7 +382,7 @@ public void DetectMetadataTests_WeaklyTyped () detected = null; error = null; pasteboard.DetectMetadata (hashSet, callback); - Assert.That (evt.WaitOne (TimeSpan.FromSeconds (1)), "WeaklyTyped DetectMetadata #3 wait"); + Assert.That (evt.WaitOne (TimeSpan.FromSeconds (10)), "WeaklyTyped DetectMetadata #3 wait"); Assert.That (detected, Is.Not.Null, "WeaklyTyped DetectMetadata #3 patterns"); Assert.That ((int) detected.Count, Is.EqualTo (0), "WeaklyTyped DetectMetadata #3 count"); Assert.That (error, Is.Not.Null, "WeaklyTyped DetectMetadata #3 error"); @@ -406,19 +413,26 @@ public void DetectMetadataTests_SomewhatStronglyTyped () detected = null; error = null; pasteboard.DetectMetadata (hashSet, callback); - Assert.That (evt.WaitOne (TimeSpan.FromSeconds (1)), "SomewhatStronglyTyped DetectMetadata #1 wait"); + Assert.That (evt.WaitOne (TimeSpan.FromSeconds (10)), "SomewhatStronglyTyped DetectMetadata #1 wait"); Assert.That (detected, Is.Not.Null, "SomewhatStronglyTyped DetectMetadata #1 patterns"); Assert.That ((int) detected.Count, Is.EqualTo (0), "SomewhatStronglyTyped DetectMetadata #1 count"); Assert.That (error, Is.Null, "SomewhatStronglyTyped DetectMetadata #1 error"); pasteboard.ClearContents (); pasteboard.SetStringForType ("file:///this/is/some/file.html", NSPasteboardType.FileUrl.GetConstant ()); - evt.Reset (); - detected = null; - error = null; - pasteboard.DetectMetadata (hashSet, callback); - Assert.That (evt.WaitOne (TimeSpan.FromSeconds (1)), "SomewhatStronglyTyped DetectMetadata #2 wait"); - Assert.That (detected, Is.Not.Null, "SomewhatStronglyTyped DetectMetadata #2 patterns"); + // The pasteboard subsystem may need time to analyze content metadata, + // so retry detection if it returns empty results. + for (int attempt = 0; attempt < 5; attempt++) { + evt.Reset (); + detected = null; + error = null; + pasteboard.DetectMetadata (hashSet, callback); + Assert.That (evt.WaitOne (TimeSpan.FromSeconds (10)), "SomewhatStronglyTyped DetectMetadata #2 wait"); + Assert.That (detected, Is.Not.Null, "SomewhatStronglyTyped DetectMetadata #2 patterns"); + if ((int) detected.Count > 0) + break; + Thread.Sleep (500); + } Assert.That ((int) detected.Count, Is.EqualTo (1), "SomewhatStronglyTyped DetectMetadata #2 count"); Assert.That (detected.Keys.First ().ToString (), Does.Contain (NSPasteboardMetadataType.ContentType.GetConstant ().ToString ()), "SomewhatStronglyTyped DetectMetadata #2 contenttype"); Assert.That (detected.Values.First ().ToString (), Does.Contain ("public.html"), "SomewhatStronglyTyped DetectMetadata #2 value"); @@ -432,7 +446,7 @@ public void DetectMetadataTests_SomewhatStronglyTyped () detected = null; error = null; pasteboard.DetectMetadata (hashSet, callback); - Assert.That (evt.WaitOne (TimeSpan.FromSeconds (1)), "SomewhatStronglyTyped DetectMetadata #3 wait"); + Assert.That (evt.WaitOne (TimeSpan.FromSeconds (10)), "SomewhatStronglyTyped DetectMetadata #3 wait"); Assert.That (detected, Is.Not.Null, "SomewhatStronglyTyped DetectMetadata #3 patterns"); Assert.That ((int) detected.Count, Is.EqualTo (0), "SomewhatStronglyTyped DetectMetadata #3 count"); Assert.That (error, Is.Not.Null, "SomewhatStronglyTyped DetectMetadata #3 error"); @@ -463,19 +477,26 @@ public void DetectMetadataTests_StronglyTyped () detected = null; error = null; pasteboard.DetectMetadata (hashSet, callback); - Assert.That (evt.WaitOne (TimeSpan.FromSeconds (1)), "StronglyTyped DetectMetadata #1 wait"); + Assert.That (evt.WaitOne (TimeSpan.FromSeconds (10)), "StronglyTyped DetectMetadata #1 wait"); Assert.That (detected, Is.Not.Null, "StronglyTyped DetectMetadata #1 patterns"); Assert.That ((int) detected.Count, Is.EqualTo (0), "StronglyTyped DetectMetadata #1 count"); Assert.That (error, Is.Null, "StronglyTyped DetectMetadata #1 error"); pasteboard.ClearContents (); pasteboard.SetStringForType ("file:///this/is/some/file.html", NSPasteboardType.FileUrl.GetConstant ()); - evt.Reset (); - detected = null; - error = null; - pasteboard.DetectMetadata (hashSet, callback); - Assert.That (evt.WaitOne (TimeSpan.FromSeconds (1)), "StronglyTyped DetectMetadata #2 wait"); - Assert.That (detected, Is.Not.Null, "StronglyTyped DetectMetadata #2 patterns"); + // The pasteboard subsystem may need time to analyze content metadata, + // so retry detection if it returns empty results. + for (int attempt = 0; attempt < 5; attempt++) { + evt.Reset (); + detected = null; + error = null; + pasteboard.DetectMetadata (hashSet, callback); + Assert.That (evt.WaitOne (TimeSpan.FromSeconds (10)), "StronglyTyped DetectMetadata #2 wait"); + Assert.That (detected, Is.Not.Null, "StronglyTyped DetectMetadata #2 patterns"); + if ((int) detected.Count > 0) + break; + Thread.Sleep (500); + } Assert.That ((int) detected.Count, Is.EqualTo (1), "StronglyTyped DetectMetadata #2 count"); Assert.That (detected.Keys.First (), Is.EqualTo (NSPasteboardMetadataType.ContentType), "StronglyTyped DetectMetadata #2 contenttype"); Assert.That (detected.Values.First ().ToString (), Does.Contain ("public.html"), "StronglyTyped DetectMetadata #2 value"); @@ -489,7 +510,7 @@ public void DetectMetadataTests_StronglyTyped () detected = null; error = null; pasteboard.DetectMetadata (hashSet, callback); - Assert.That (evt.WaitOne (TimeSpan.FromSeconds (1)), "StronglyTyped DetectMetadata #3 wait"); + Assert.That (evt.WaitOne (TimeSpan.FromSeconds (10)), "StronglyTyped DetectMetadata #3 wait"); Assert.That (detected, Is.Not.Null, "StronglyTyped DetectMetadata #3 patterns"); Assert.That ((int) detected.Count, Is.EqualTo (0), "StronglyTyped DetectMetadata #3 count"); Assert.That (error, Is.Not.Null, "StronglyTyped DetectMetadata #3 error"); diff --git a/tests/monotouch-test/AppKit/NSPathControl.cs b/tests/monotouch-test/AppKit/NSPathControl.cs index a9fe3bd1095a..4de0f83ed4f7 100644 --- a/tests/monotouch-test/AppKit/NSPathControl.cs +++ b/tests/monotouch-test/AppKit/NSPathControl.cs @@ -13,7 +13,7 @@ public void NSPathControlShouldSetEditable () var editable = control.Editable; control.Editable = !editable; - Assert.IsTrue (control.Editable != editable, "NSPathControlShouldSetEditable - Failed to change the Editable property"); + Assert.That (control.Editable != editable, Is.True, "NSPathControlShouldSetEditable - Failed to change the Editable property"); } [Test] @@ -23,7 +23,7 @@ public void NSPathControlShouldSetAllowedTypes () var allowedTypes = control.AllowedTypes; control.AllowedTypes = new [] { (NSString) "exe", (NSString) "jpg" }; - Assert.IsTrue (control.AllowedTypes != allowedTypes, "NSPathControlShouldSetAllowedTypes - Failed to change AllowedTypes property"); + Assert.That (control.AllowedTypes != allowedTypes, Is.True, "NSPathControlShouldSetAllowedTypes - Failed to change AllowedTypes property"); } [Test] @@ -33,7 +33,7 @@ public void NSPathControlShouldSetPlaceholderString () var placeholderString = control.PlaceholderString; control.PlaceholderString = "Test Placeholder"; - Assert.IsTrue (control.PlaceholderString != placeholderString, "NSPathControlShouldSetPlaceholderString - Failed to change PlaceholderString property"); + Assert.That (control.PlaceholderString != placeholderString, Is.True, "NSPathControlShouldSetPlaceholderString - Failed to change PlaceholderString property"); } [Test] @@ -43,7 +43,7 @@ public void NSPathControlShouldSetPlaceholderAttributedString () var placeholderAttributedString = control.PlaceholderAttributedString; control.PlaceholderAttributedString = new NSAttributedString ("Test Placeholder"); - Assert.IsTrue (control.PlaceholderAttributedString != placeholderAttributedString, "NSPathControlShouldSetPlaceholderAttributedString - Failed to change PlaceholderAttributedString property"); + Assert.That (control.PlaceholderAttributedString != placeholderAttributedString, Is.True, "NSPathControlShouldSetPlaceholderAttributedString - Failed to change PlaceholderAttributedString property"); } [Test] @@ -53,7 +53,7 @@ public void NSPathControlShouldSetPathItems () var pathItems = control.PathItems; control.PathItems = new [] { new NSPathControlItem () }; - Assert.IsTrue (control.PathItems != pathItems, "NSPathControlShouldSetPathItems - Failed to set PathItems property"); + Assert.That (control.PathItems != pathItems, Is.True, "NSPathControlShouldSetPathItems - Failed to set PathItems property"); } } } diff --git a/tests/monotouch-test/AppKit/NSPathControlItem.cs b/tests/monotouch-test/AppKit/NSPathControlItem.cs index 7ab456635a38..eb183b3702e6 100644 --- a/tests/monotouch-test/AppKit/NSPathControlItem.cs +++ b/tests/monotouch-test/AppKit/NSPathControlItem.cs @@ -12,7 +12,7 @@ public void NSPathControlItemShouldSetTitle () var title = item.Title; item.Title = "Test"; - Assert.IsTrue (item.Title != title, "NSPathControlShouldSetTitle - Title value did not change."); + Assert.That (item.Title != title, Is.True, "NSPathControlShouldSetTitle - Title value did not change."); } [Test] @@ -22,7 +22,7 @@ public void NSPathControlItemShouldSetAttributedTitle () var attributedTitle = item.AttributedTitle; item.AttributedTitle = new NSAttributedString ("Test"); - Assert.IsTrue (item.AttributedTitle != attributedTitle, "NSPathControlShouldSetAttributedTitle - AttributedTitle value did not change."); + Assert.That (item.AttributedTitle != attributedTitle, Is.True, "NSPathControlShouldSetAttributedTitle - AttributedTitle value did not change."); } @@ -30,10 +30,10 @@ public void NSPathControlItemShouldSetAttributedTitle () public void NSPathControlItemShouldSetImage () { var item = new NSPathControlItem (); - Assert.IsTrue (item.Image is null, "NSPathControlItemShouldSetImage - Image did not start as null"); + Assert.That (item.Image is null, Is.True, "NSPathControlItemShouldSetImage - Image did not start as null"); item.Image = new NSImage (); - Assert.IsTrue (item.Image is not null, "NSPathControlItemShouldSetImage - Failed to set Image property"); + Assert.That (item.Image is not null, Is.True, "NSPathControlItemShouldSetImage - Failed to set Image property"); } } } diff --git a/tests/monotouch-test/AppKit/NSScreen.cs b/tests/monotouch-test/AppKit/NSScreen.cs index f2faae10f34e..6106666de9f9 100644 --- a/tests/monotouch-test/AppKit/NSScreen.cs +++ b/tests/monotouch-test/AppKit/NSScreen.cs @@ -17,8 +17,8 @@ public void ScreensNotMainThread () called.Set (); }); backgroundThread.Start (); - Assert.IsTrue (called.WaitOne (1000), "called"); - Assert.IsTrue (screensCount > 0, "screens count"); + Assert.That (called.WaitOne (1000), Is.True, "called"); + Assert.That (screensCount > 0, Is.True, "screens count"); } [Test] @@ -31,8 +31,8 @@ public void MainScreenNotMainThread () called.Set (); }); backgroundThread.Start (); - Assert.IsTrue (called.WaitOne (1000), "called"); - Assert.IsNotNull (main, "main screen"); + Assert.That (called.WaitOne (1000), Is.True, "called"); + Assert.That (main, Is.Not.Null, "main screen"); } [Test] @@ -48,9 +48,9 @@ public void DeepScreenNotMainThread () called.Set (); }); backgroundThread.Start (); - Assert.IsTrue (called.WaitOne (1000), "called"); + Assert.That (called.WaitOne (1000), Is.True, "called"); if (screenCount > 1) { - Assert.IsNotNull (deepScreen, "deep screen"); + Assert.That (deepScreen, Is.Not.Null, "deep screen"); } else { Assert.Inconclusive ("Only one screen detected."); } diff --git a/tests/monotouch-test/AppKit/NSSearchField.cs b/tests/monotouch-test/AppKit/NSSearchField.cs index 98475e0cbc19..386b8e40c016 100644 --- a/tests/monotouch-test/AppKit/NSSearchField.cs +++ b/tests/monotouch-test/AppKit/NSSearchField.cs @@ -15,7 +15,7 @@ public void NSSearchFieldShouldSetSearchMenuTemplate () var searchMenuTemplate = searchField.SearchMenuTemplate; searchField.SearchMenuTemplate = new NSMenu ("Test"); - Assert.IsTrue (searchField.SearchMenuTemplate != searchMenuTemplate, "NSSearchFieldShouldSetSearchMenuTemplate - Failed to set the SearchMenuTemplate property."); + Assert.That (searchField.SearchMenuTemplate != searchMenuTemplate, Is.True, "NSSearchFieldShouldSetSearchMenuTemplate - Failed to set the SearchMenuTemplate property."); } [Test] @@ -27,7 +27,7 @@ public void NSSearchFieldShouldSetSendsWholeSearchString () var sendsWholeSearchString = searchField.SendsWholeSearchString; searchField.SendsWholeSearchString = !sendsWholeSearchString; - Assert.IsTrue (searchField.SendsWholeSearchString != sendsWholeSearchString, "NSSearchFieldShouldSetSendsWholeSearchString - Failed to set the SendsWholeSearchString property."); + Assert.That (searchField.SendsWholeSearchString != sendsWholeSearchString, Is.True, "NSSearchFieldShouldSetSendsWholeSearchString - Failed to set the SendsWholeSearchString property."); } [Test] @@ -39,7 +39,7 @@ public void NSSearchFieldShouldSetMaximumRecents () var maximumRecents = searchField.MaximumRecents; searchField.MaximumRecents = maximumRecents + 3; - Assert.IsTrue (searchField.MaximumRecents != maximumRecents, "NSSearchFieldShouldSetMaximumRecents - Failed to set the MaximumRecents property."); + Assert.That (searchField.MaximumRecents != maximumRecents, Is.True, "NSSearchFieldShouldSetMaximumRecents - Failed to set the MaximumRecents property."); } [Test] @@ -51,7 +51,7 @@ public void NSSearchFieldShouldSetSendsSearchStringImmediately () var sendsSearchStringImmediately = searchField.SendsSearchStringImmediately; searchField.SendsSearchStringImmediately = !sendsSearchStringImmediately; - Assert.IsTrue (searchField.SendsSearchStringImmediately != sendsSearchStringImmediately, "NSSearchFieldShouldSetSendsSearchStringImmediately - Failed to set the SendsSearchStringImmediately property."); + Assert.That (searchField.SendsSearchStringImmediately != sendsSearchStringImmediately, Is.True, "NSSearchFieldShouldSetSendsSearchStringImmediately - Failed to set the SendsSearchStringImmediately property."); } } } diff --git a/tests/monotouch-test/AppKit/NSSlider.cs b/tests/monotouch-test/AppKit/NSSlider.cs index e65d154d420b..83e5d3164de6 100644 --- a/tests/monotouch-test/AppKit/NSSlider.cs +++ b/tests/monotouch-test/AppKit/NSSlider.cs @@ -15,7 +15,7 @@ public void NSSlider_VertialTests () NSSlider slider = new NSSlider (); var isVert = slider.IsVertical; slider.IsVertical = true; - Assert.IsTrue (slider.IsVertical); + Assert.That (slider.IsVertical, Is.True); } } } diff --git a/tests/monotouch-test/AppKit/NSSplitViewController.cs b/tests/monotouch-test/AppKit/NSSplitViewController.cs index 918679eff29e..1ff1e1fe2677 100644 --- a/tests/monotouch-test/AppKit/NSSplitViewController.cs +++ b/tests/monotouch-test/AppKit/NSSplitViewController.cs @@ -20,7 +20,7 @@ public void NSSplitViewControllerShouldChangeSplitView () var splitView = controller.SplitView; controller.SplitView = new NSSplitView (); - Assert.IsFalse (controller.SplitView == splitView, "NSSplitViewControllerShouldChangeSplitView - Failed to set the SplitView property"); + Assert.That (controller.SplitView == splitView, Is.False, "NSSplitViewControllerShouldChangeSplitView - Failed to set the SplitView property"); } [Test] @@ -29,7 +29,7 @@ public void NSSplitViewControllerShouldChangeSplitViewItems () var items = controller.SplitViewItems; controller.SplitViewItems = new NSSplitViewItem [] { new NSSplitViewItem { ViewController = new NSViewController () } }; - Assert.IsFalse (controller.SplitViewItems == items, "NSSplitViewControllerShouldChangeSplitViewItems - Failed to set the SplitViewItems property"); + Assert.That (controller.SplitViewItems == items, Is.False, "NSSplitViewControllerShouldChangeSplitViewItems - Failed to set the SplitViewItems property"); } [Test] @@ -38,7 +38,7 @@ public void NSSplitViewControllerShouldAddSplitViewItem () var item = new NSSplitViewItem { ViewController = new NSViewController () }; controller.AddSplitViewItem (item); - Assert.IsTrue (controller.SplitViewItems.Contains (item), "NSSplitViewControllerShouldAddSplitViewItem - Failed to add item"); + Assert.That (controller.SplitViewItems.Contains (item), Is.True, "NSSplitViewControllerShouldAddSplitViewItem - Failed to add item"); } [Test] @@ -47,11 +47,11 @@ public void NSSplitViewControllerShouldRemoveSplitViewItem () var item = new NSSplitViewItem { ViewController = new NSViewController () }; controller.AddSplitViewItem (item); - Assert.IsTrue (controller.SplitViewItems.Contains (item), "NSSplitViewControllerShouldRemoveSplitViewItem - Failed to add item"); + Assert.That (controller.SplitViewItems.Contains (item), Is.True, "NSSplitViewControllerShouldRemoveSplitViewItem - Failed to add item"); controller.RemoveSplitViewItem (item); - Assert.IsFalse (controller.SplitViewItems.Contains (item), "NSSplitViewControllerShouldRemoveSplitViewItem - Failed to remove item"); + Assert.That (controller.SplitViewItems.Contains (item), Is.False, "NSSplitViewControllerShouldRemoveSplitViewItem - Failed to remove item"); } [Test] @@ -63,8 +63,8 @@ public void NSSplitViewControllerShouldInsertSplitViewItem () var item = new NSSplitViewItem { ViewController = new NSViewController () }; controller.InsertSplitViewItem (item, 1); - Assert.IsTrue (controller.SplitViewItems [1] == item, "NSSplitViewControllerShouldInsertSplitViewItem - Failed to insert the item at the given position."); - Assert.IsFalse (controller.SplitViewItems [0] == item, "NSSplitViewControllerShouldInsertSplitViewItem - Inserted the item in the wrong position."); + Assert.That (controller.SplitViewItems [1] == item, Is.True, "NSSplitViewControllerShouldInsertSplitViewItem - Failed to insert the item at the given position."); + Assert.That (controller.SplitViewItems [0] == item, Is.False, "NSSplitViewControllerShouldInsertSplitViewItem - Inserted the item in the wrong position."); } [Test] @@ -79,7 +79,7 @@ public void NSSplitViewControllerShouldGetSplitViewItem () var retrievedItem = controller.GetSplitViewItem (viewController); - Assert.IsTrue (retrievedItem == item, "NSSplitViewControllerShouldGetSplitViewItem - Failed to get SplitViewItem from ViewController"); + Assert.That (retrievedItem == item, Is.True, "NSSplitViewControllerShouldGetSplitViewItem - Failed to get SplitViewItem from ViewController"); } } } diff --git a/tests/monotouch-test/AppKit/NSSplitViewItem.cs b/tests/monotouch-test/AppKit/NSSplitViewItem.cs index ec14bad13aad..7cb547d83ec9 100644 --- a/tests/monotouch-test/AppKit/NSSplitViewItem.cs +++ b/tests/monotouch-test/AppKit/NSSplitViewItem.cs @@ -20,8 +20,8 @@ public void NSSplitViewItemShouldCreateFromViewController () var viewController = new NSViewController (); var splitViewItem = NSSplitViewItem.FromViewController (viewController); - Assert.IsFalse (splitViewItem is null, "NSSplitViewItemShouldCreateFromViewController - Returned null"); - Assert.IsTrue (splitViewItem.ViewController == viewController, "NSSplitViewItemShouldCreateFromViewController - ViewController property not set correctly"); + Assert.That (splitViewItem is null, Is.False, "NSSplitViewItemShouldCreateFromViewController - Returned null"); + Assert.That (splitViewItem.ViewController == viewController, Is.True, "NSSplitViewItemShouldCreateFromViewController - ViewController property not set correctly"); } [Test] @@ -30,7 +30,7 @@ public void NSSplitViewItemShouldChangeViewController () var viewController = item.ViewController; item.ViewController = new NSViewController (); - Assert.IsFalse (item.ViewController == viewController, "NSSplitViewItemShouldChangeViewController - Failed to set the ViewController property"); + Assert.That (item.ViewController == viewController, Is.False, "NSSplitViewItemShouldChangeViewController - Failed to set the ViewController property"); } [Test] @@ -39,7 +39,7 @@ public void NSSplitViewItemShouldChangeCollapsed () var collapsed = item.Collapsed; item.Collapsed = !collapsed; - Assert.IsFalse (item.Collapsed == collapsed, "NSSplitViewItemShouldChangeCollapsed - Failed to set the Collapsed property"); + Assert.That (item.Collapsed == collapsed, Is.False, "NSSplitViewItemShouldChangeCollapsed - Failed to set the Collapsed property"); } [Test] @@ -48,7 +48,7 @@ public void NSSplitViewItemShouldChangeCanCollapse () var canCollapse = item.CanCollapse; item.CanCollapse = !canCollapse; - Assert.IsFalse (item.CanCollapse == canCollapse, "NSSplitViewItemShouldChangeCanCollapse - Failed to set the CanCollapse property"); + Assert.That (item.CanCollapse == canCollapse, Is.False, "NSSplitViewItemShouldChangeCanCollapse - Failed to set the CanCollapse property"); } [Test] @@ -57,7 +57,7 @@ public void NSSplitViewItemShouldChangeHoldingPriority () var holdingPriority = item.HoldingPriority; item.HoldingPriority = 0.35f; - Assert.IsFalse (item.HoldingPriority == holdingPriority, "NSSplitViewItemShouldChangeHoldingPriority - Failed to set the HoldingPriority property"); + Assert.That (item.HoldingPriority == holdingPriority, Is.False, "NSSplitViewItemShouldChangeHoldingPriority - Failed to set the HoldingPriority property"); } } } diff --git a/tests/monotouch-test/AppKit/NSStackView.cs b/tests/monotouch-test/AppKit/NSStackView.cs index 607258b7b3d6..4df388936b53 100644 --- a/tests/monotouch-test/AppKit/NSStackView.cs +++ b/tests/monotouch-test/AppKit/NSStackView.cs @@ -23,7 +23,7 @@ public void SetUp () [Test] public void NSStackViewShouldCreateWithEmptyConstructor () { - Assert.IsNotNull (view, "NSStackViewCreateWithEmptyConstructor - Failed to create view"); + Assert.That (view, Is.Not.Null, "NSStackViewCreateWithEmptyConstructor - Failed to create view"); } [Test] @@ -31,8 +31,8 @@ public void NSStackViewShouldCreateWithViews () { view = NSStackView.FromViews (new [] { first, second }); - Assert.IsNotNull (view, "NSStackViewCreateWithViews - Failed to create view"); - Assert.IsTrue (view.Views.Length == 2, "NSStackViewShouldCreateWithViews - StackView does not have 2 views"); + Assert.That (view, Is.Not.Null, "NSStackViewCreateWithViews - Failed to create view"); + Assert.That (view.Views.Length == 2, Is.True, "NSStackViewShouldCreateWithViews - StackView does not have 2 views"); } [Test] @@ -40,7 +40,7 @@ public void NSStackViewShouldAddView () { view.AddView (new NSView (), NSStackViewGravity.Bottom); - Assert.IsTrue (view.Views.Length == 1, "NSStackViewShouldAddView - Failed to add view - length was 0"); + Assert.That (view.Views.Length == 1, Is.True, "NSStackViewShouldAddView - Failed to add view - length was 0"); } [Test] @@ -51,8 +51,8 @@ public void NSStackViewShouldInsertView () view.InsertView (third, 1, NSStackViewGravity.Trailing); - Assert.IsTrue (view.Views.Length == 3, "NSStackViewShouldInsertView - Wrong number of views"); - Assert.IsTrue (view.Views [1] == third, "NSStackViewShouldInsertView - New view not inserted at the correct location"); + Assert.That (view.Views.Length == 3, Is.True, "NSStackViewShouldInsertView - Wrong number of views"); + Assert.That (view.Views [1] == third, Is.True, "NSStackViewShouldInsertView - New view not inserted at the correct location"); } [Test] @@ -62,7 +62,7 @@ public void NSStackViewShouldRemoveView () view.RemoveView (second); - Assert.IsTrue (view.Views.Length == 1, "NSStackViewShouldRemoveView - Failed to remove view"); + Assert.That (view.Views.Length == 1, Is.True, "NSStackViewShouldRemoveView - Failed to remove view"); } [Test] @@ -70,9 +70,9 @@ public void NSStackViewShouldSetViews () { view.SetViews (new [] { first, second }, NSStackViewGravity.Leading); - Assert.IsTrue (view.Views.Length == 2, "NSStackViewShouldSetViews - Views length was not 0"); - Assert.IsTrue (view.ViewsInGravity (NSStackViewGravity.Leading).Length == 2, "NSStackViewShouldSetViews - ViewsInGravity Leading was not 2"); - Assert.IsTrue (view.ViewsInGravity (NSStackViewGravity.Trailing).Length == 0, "NSStackViewShouldSetViews - ViewsInGravity Trailing was not 0"); + Assert.That (view.Views.Length == 2, Is.True, "NSStackViewShouldSetViews - Views length was not 0"); + Assert.That (view.ViewsInGravity (NSStackViewGravity.Leading).Length == 2, Is.True, "NSStackViewShouldSetViews - ViewsInGravity Leading was not 2"); + Assert.That (view.ViewsInGravity (NSStackViewGravity.Trailing).Length == 0, Is.True, "NSStackViewShouldSetViews - ViewsInGravity Trailing was not 0"); } [Test] @@ -81,7 +81,7 @@ public void NSStackViewShouldChangeAlignment () var alignment = view.Alignment; view.Alignment = NSLayoutAttribute.Right; - Assert.IsFalse (view.Alignment == alignment, "NSStackViewShouldChangeAlignment - Failed to change Alignment property"); + Assert.That (view.Alignment == alignment, Is.False, "NSStackViewShouldChangeAlignment - Failed to change Alignment property"); } [Test] @@ -90,7 +90,7 @@ public void NSStackViewShouldChangeOrientation () var orientation = view.Orientation; view.Orientation = NSUserInterfaceLayoutOrientation.Vertical; - Assert.IsFalse (view.Orientation == orientation, "NSStackViewShouldChangeOrientation - Failed to change Orientation property"); + Assert.That (view.Orientation == orientation, Is.False, "NSStackViewShouldChangeOrientation - Failed to change Orientation property"); } [Test] @@ -99,7 +99,7 @@ public void NSStackViewShouldChangeSpacing () var spacing = view.Spacing; view.Spacing = spacing + 3; - Assert.IsFalse (view.Spacing == spacing, "NSStackViewShouldChangeSpacing - Failed to change Spacing property"); + Assert.That (view.Spacing == spacing, Is.False, "NSStackViewShouldChangeSpacing - Failed to change Spacing property"); } [Test] @@ -108,10 +108,10 @@ public void NSStackViewShouldChangeEdgeInsets () var edgeInsets = view.EdgeInsets; view.EdgeInsets = new NSEdgeInsets (20, 20, 20, 20); - Assert.IsFalse (view.EdgeInsets.Left == edgeInsets.Left, "NSStackViewShouldChangeEdgeInsets - Failed to change EdgeInsets property"); - Assert.IsFalse (view.EdgeInsets.Right == edgeInsets.Right, "NSStackViewShouldChangeEdgeInsets - Failed to change EdgeInsets property"); - Assert.IsFalse (view.EdgeInsets.Top == edgeInsets.Top, "NSStackViewShouldChangeEdgeInsets - Failed to change EdgeInsets property"); - Assert.IsFalse (view.EdgeInsets.Bottom == edgeInsets.Bottom, "NSStackViewShouldChangeEdgeInsets - Failed to change EdgeInsets property"); + Assert.That (view.EdgeInsets.Left == edgeInsets.Left, Is.False, "NSStackViewShouldChangeEdgeInsets - Failed to change EdgeInsets property"); + Assert.That (view.EdgeInsets.Right == edgeInsets.Right, Is.False, "NSStackViewShouldChangeEdgeInsets - Failed to change EdgeInsets property"); + Assert.That (view.EdgeInsets.Top == edgeInsets.Top, Is.False, "NSStackViewShouldChangeEdgeInsets - Failed to change EdgeInsets property"); + Assert.That (view.EdgeInsets.Bottom == edgeInsets.Bottom, Is.False, "NSStackViewShouldChangeEdgeInsets - Failed to change EdgeInsets property"); } [Test] @@ -120,7 +120,7 @@ public void NSStackViewShouldChangeHasEqualSpacing () var hasEqualSpacing = view.HasEqualSpacing; view.HasEqualSpacing = !hasEqualSpacing; - Assert.IsFalse (view.HasEqualSpacing == hasEqualSpacing, "NSStackViewShouldChangeHasEqualSpacing - Failed to change HasEqualSpacing property"); + Assert.That (view.HasEqualSpacing == hasEqualSpacing, Is.False, "NSStackViewShouldChangeHasEqualSpacing - Failed to change HasEqualSpacing property"); } // [Test] @@ -129,7 +129,7 @@ public void NSStackViewShouldChangeHasEqualSpacing () // var view = new NSStackView (); // view.Delegate = new NSStackViewDelegate (); // - // Assert.IsNotNull (view.Delegate, "NSStackViewShouldSetDelegate - Delegate property returned null"); + // Assert.That (view.Delegate, Is.Not.Null, "NSStackViewShouldSetDelegate - Delegate property returned null"); // } [Test] @@ -138,8 +138,7 @@ public void NSStackViewShouldChangeClippingResistance () var clippingResistance = view.ClippingResistancePriorityForOrientation (NSLayoutConstraintOrientation.Vertical); view.SetClippingResistancePriority (clippingResistance + 3, NSLayoutConstraintOrientation.Vertical); - Assert.IsFalse (view.ClippingResistancePriorityForOrientation (NSLayoutConstraintOrientation.Vertical) == clippingResistance, - "NSStackViewShouldChangeClippingResistance - Failed to set ClippingResistance"); + Assert.That (view.ClippingResistancePriorityForOrientation (NSLayoutConstraintOrientation.Vertical) == clippingResistance, Is.False, "NSStackViewShouldChangeClippingResistance - Failed to set ClippingResistance"); } [Test] @@ -148,8 +147,7 @@ public void NSStackViewShouldChangeHuggingPriority () var huggingPriority = view.HuggingPriority (NSLayoutConstraintOrientation.Horizontal); view.SetHuggingPriority (huggingPriority + 10, NSLayoutConstraintOrientation.Horizontal); - Assert.IsFalse (view.HuggingPriority (NSLayoutConstraintOrientation.Horizontal) == huggingPriority, - "NSStackViewShouldChangeHuggingPriority - Failed to set HuggingPriority"); + Assert.That (view.HuggingPriority (NSLayoutConstraintOrientation.Horizontal) == huggingPriority, Is.False, "NSStackViewShouldChangeHuggingPriority - Failed to set HuggingPriority"); } [Test] @@ -161,8 +159,7 @@ public void NSStackViewShouldChangeCustomSpacing () var customSpacing = view.CustomSpacingAfterView (first); view.SetCustomSpacing (10, first); - Assert.IsFalse (view.CustomSpacingAfterView (first) == customSpacing, - "NSStackViewShouldChangeCustomSpacing - Failed to set CustomSpacing"); + Assert.That (view.CustomSpacingAfterView (first) == customSpacing, Is.False, "NSStackViewShouldChangeCustomSpacing - Failed to set CustomSpacing"); } [Test] @@ -174,8 +171,7 @@ public void NSStackViewShouldChangeVisibilityPriority () var visibilityPriority = view.VisibilityPriority (first); view.SetVisibilityPriority (10, first); - Assert.IsFalse (view.VisibilityPriority (first) == visibilityPriority, - "NSStackViewShouldChangeVisibilityPriority - Failed to set VisibilityPriority"); + Assert.That (view.VisibilityPriority (first) == visibilityPriority, Is.False, "NSStackViewShouldChangeVisibilityPriority - Failed to set VisibilityPriority"); } } } diff --git a/tests/monotouch-test/AppKit/NSStepperCell.cs b/tests/monotouch-test/AppKit/NSStepperCell.cs index aedf7405e8c3..c6da6f90d95a 100644 --- a/tests/monotouch-test/AppKit/NSStepperCell.cs +++ b/tests/monotouch-test/AppKit/NSStepperCell.cs @@ -20,7 +20,7 @@ public void NSStepperCell_ShouldSetMinValue () var minValue = cell.MinValue; cell.MinValue = 3.14159; - Assert.IsTrue (cell.MinValue != minValue, "NSStepperCell_ShouldSetMinValue - Failed to set the MinValue property"); + Assert.That (cell.MinValue != minValue, Is.True, "NSStepperCell_ShouldSetMinValue - Failed to set the MinValue property"); } [Test] @@ -29,7 +29,7 @@ public void NSStepperCell_ShouldSetMaxValue () var maxValue = cell.MaxValue; cell.MaxValue = 3.14159; - Assert.IsTrue (cell.MinValue != maxValue, "NSStepperCell_ShouldSetMaxValue - Failed to set the MaxValue property"); + Assert.That (cell.MinValue != maxValue, Is.True, "NSStepperCell_ShouldSetMaxValue - Failed to set the MaxValue property"); } [Test] public void NSStepperCell_ShouldSetIncrement () @@ -37,7 +37,7 @@ public void NSStepperCell_ShouldSetIncrement () var increment = cell.Increment; cell.Increment = 3.14159; - Assert.IsTrue (cell.Increment != increment, "NSStepperCell_ShouldSetIncrement - Failed to set the Increment property"); + Assert.That (cell.Increment != increment, Is.True, "NSStepperCell_ShouldSetIncrement - Failed to set the Increment property"); } [Test] public void NSStepperCell_ShouldSetValueWraps () @@ -45,7 +45,7 @@ public void NSStepperCell_ShouldSetValueWraps () var valueWraps = cell.ValueWraps; cell.ValueWraps = !valueWraps; - Assert.IsTrue (cell.ValueWraps != valueWraps, "NSStepperCell_ShouldSetValueWraps - Failed to set the ValueWraps property"); + Assert.That (cell.ValueWraps != valueWraps, Is.True, "NSStepperCell_ShouldSetValueWraps - Failed to set the ValueWraps property"); } [Test] public void NSStepperCell_ShouldSetAutoRepeat () @@ -53,7 +53,7 @@ public void NSStepperCell_ShouldSetAutoRepeat () var autoRepeat = cell.Autorepeat; cell.Autorepeat = !autoRepeat; - Assert.IsTrue (cell.Autorepeat != autoRepeat, "NSStepperCell_ShouldSetAutoRepeat - Failed to set the Autorepeat property"); + Assert.That (cell.Autorepeat != autoRepeat, Is.True, "NSStepperCell_ShouldSetAutoRepeat - Failed to set the Autorepeat property"); } } } diff --git a/tests/monotouch-test/AppKit/NSStoryboardSegue.cs b/tests/monotouch-test/AppKit/NSStoryboardSegue.cs index 8c072784c3d8..de226fc852a7 100644 --- a/tests/monotouch-test/AppKit/NSStoryboardSegue.cs +++ b/tests/monotouch-test/AppKit/NSStoryboardSegue.cs @@ -20,27 +20,27 @@ public void Setup () [Test] public void NSStoryboardSegueShouldCreateSegueWithConstructor () { - Assert.IsNotNull (segue, "NSStoryboardSegueShouldCreateSegueWithConstructor - Failed to create segue, value is null"); + Assert.That (segue, Is.Not.Null, "NSStoryboardSegueShouldCreateSegueWithConstructor - Failed to create segue, value is null"); } [Test] public void NSStoryboardSegueShouldGetIdentifier () { - Assert.IsFalse (string.IsNullOrEmpty (segue.Identifier), "NSStoryboardSegueShouldGetIdentifier - Identifier property was empty or null"); + Assert.That (string.IsNullOrEmpty (segue.Identifier), Is.False, "NSStoryboardSegueShouldGetIdentifier - Identifier property was empty or null"); } [Test] public void NSStoryboardSegueShouldGetSourceController () { - Assert.IsNotNull (segue.SourceController, "NSStoryboardSegueShouldGetSourceController - Source controller was null"); - Assert.IsTrue (segue.SourceController == source, "NSStoryboardSegueShouldGetSourceController - Source controller did not match the source controller passed into the segue."); + Assert.That (segue.SourceController, Is.Not.Null, "NSStoryboardSegueShouldGetSourceController - Source controller was null"); + Assert.That (segue.SourceController == source, Is.True, "NSStoryboardSegueShouldGetSourceController - Source controller did not match the source controller passed into the segue."); } [Test] public void NSStoryboardSegueShouldGetDestinationController () { - Assert.IsNotNull (segue.DestinationController, "NSStoryboardSegueShouldGetDestinationController - Destination controller was null"); - Assert.IsTrue (segue.DestinationController == destination, "NSStoryboardSegueShouldGetDestinationController - Destination controller did not mass the destination controller passed into the segue."); + Assert.That (segue.DestinationController, Is.Not.Null, "NSStoryboardSegueShouldGetDestinationController - Destination controller was null"); + Assert.That (segue.DestinationController == destination, Is.True, "NSStoryboardSegueShouldGetDestinationController - Destination controller did not mass the destination controller passed into the segue."); } #if false // Crashes when run in test from command line, works from an actual app @@ -49,7 +49,7 @@ public void NSStoryboardSegueShouldCreateSegueWithStaticMethod () { var segue = NSStoryboardSegue.FromIdentifier ("Test", new NSViewController (), new NSViewController (), () => { }); - Assert.IsNotNull (segue); + Assert.That (segue, Is.Not.Null); } #endif } diff --git a/tests/monotouch-test/AppKit/NSTabViewController.cs b/tests/monotouch-test/AppKit/NSTabViewController.cs index a5c23ba28c0a..61a36a5f2f75 100644 --- a/tests/monotouch-test/AppKit/NSTabViewController.cs +++ b/tests/monotouch-test/AppKit/NSTabViewController.cs @@ -21,7 +21,7 @@ public void NSTabViewControllerShouldChangeTabStyle () var tabStyle = controller.TabStyle; controller.TabStyle = NSTabViewControllerTabStyle.Toolbar; - Assert.IsFalse (controller.TabStyle == tabStyle, "NSTabViewControllerShouldChangeTabStyle - Failed to set the TabStyle property"); + Assert.That (controller.TabStyle == tabStyle, Is.False, "NSTabViewControllerShouldChangeTabStyle - Failed to set the TabStyle property"); } // [Test] @@ -30,7 +30,7 @@ public void NSTabViewControllerShouldChangeTabStyle () // var tabView = controller.TabView; // controller.TabView = new NSTabView (); // - // Assert.IsFalse (controller.TabView == tabView, "NSTabViewControllerShouldChangeTabView - Failed to set the TabView property"); + // Assert.That (controller.TabView == tabView, Is.False, "NSTabViewControllerShouldChangeTabView - Failed to set the TabView property"); // } [Test] @@ -39,7 +39,7 @@ public void NSTabViewControllerShouldChangeTransitionOptions () var options = controller.TransitionOptions; controller.TransitionOptions = NSViewControllerTransitionOptions.Crossfade | NSViewControllerTransitionOptions.SlideRight; - Assert.IsFalse (controller.TransitionOptions == options, "NSTabViewControllerShouldChangeTransitionOptions - Failed to set the TransitionOptions property"); + Assert.That (controller.TransitionOptions == options, Is.False, "NSTabViewControllerShouldChangeTransitionOptions - Failed to set the TransitionOptions property"); } [Test] @@ -48,7 +48,7 @@ public void NSTabViewControllerShouldChangeCanPropagateSelectedChildViewControll var canPropogate = controller.CanPropagateSelectedChildViewControllerTitle; controller.CanPropagateSelectedChildViewControllerTitle = !canPropogate; - Assert.IsFalse (controller.CanPropagateSelectedChildViewControllerTitle == canPropogate, "NSTabViewControllerShouldChangeCanPropagateSelectedChildViewControllerTitle - Failed to set the CanPropagateSelectedChildViewControllerTitle property"); + Assert.That (controller.CanPropagateSelectedChildViewControllerTitle == canPropogate, Is.False, "NSTabViewControllerShouldChangeCanPropagateSelectedChildViewControllerTitle - Failed to set the CanPropagateSelectedChildViewControllerTitle property"); } [Test] @@ -57,7 +57,7 @@ public void NSTabViewControllerShouldChangeTabViewItems () var items = controller.TabViewItems; controller.TabViewItems = new NSTabViewItem [] { new NSTabViewItem { ViewController = new NSViewController () } }; - Assert.IsFalse (controller.TabViewItems == items, "NSTabViewControllerShouldChangeTabViewItems - Failed to set the TabViewItems property"); + Assert.That (controller.TabViewItems == items, Is.False, "NSTabViewControllerShouldChangeTabViewItems - Failed to set the TabViewItems property"); } [Test] @@ -72,7 +72,7 @@ public void NSTabViewControllerShouldChangeSelectedTabViewItemIndex () var index = controller.SelectedTabViewItemIndex; controller.SelectedTabViewItemIndex = (index + 1) % 3; - Assert.IsFalse (controller.SelectedTabViewItemIndex == index, "NSTabViewControllerShouldChangeSelectedTabViewItemIndex - Failed to set the SelectedTabViewItemIndex property"); + Assert.That (controller.SelectedTabViewItemIndex == index, Is.False, "NSTabViewControllerShouldChangeSelectedTabViewItemIndex - Failed to set the SelectedTabViewItemIndex property"); } [Test] @@ -81,7 +81,7 @@ public void NSTabViewControllerShouldAddTabViewItem () var item = new NSTabViewItem { ViewController = new NSViewController () }; controller.AddTabViewItem (item); - Assert.IsTrue (controller.TabViewItems.Contains (item), "NSTabViewControllerShouldAddTabViewItem - Failed to add TabViewItem"); + Assert.That (controller.TabViewItems.Contains (item), Is.True, "NSTabViewControllerShouldAddTabViewItem - Failed to add TabViewItem"); } [Test] @@ -90,11 +90,11 @@ public void NSTabViewControllerShouldRemoveTabViewItem () var item = new NSTabViewItem { ViewController = new NSViewController () }; controller.AddTabViewItem (item); - Assert.IsTrue (controller.TabViewItems.Contains (item), "NSTabViewControllerShouldRemoveTabViewItem - Failed to add item"); + Assert.That (controller.TabViewItems.Contains (item), Is.True, "NSTabViewControllerShouldRemoveTabViewItem - Failed to add item"); controller.RemoveTabViewItem (item); - Assert.IsFalse (controller.TabViewItems.Contains (item), "NSTabViewControllerShouldRemoveTabViewItem - Failed to remove item"); + Assert.That (controller.TabViewItems.Contains (item), Is.False, "NSTabViewControllerShouldRemoveTabViewItem - Failed to remove item"); } [Test] @@ -106,8 +106,8 @@ public void NSTabViewControllerShouldInsertTabViewItem () var item = new NSTabViewItem { ViewController = new NSViewController () }; controller.InsertTabViewItem (item, 1); - Assert.IsTrue (controller.TabViewItems [1] == item, "NSTabViewControllerShouldInsertTabViewItem - Failed to insert the item at the given position."); - Assert.IsFalse (controller.TabViewItems [0] == item, "NSTabViewControllerShouldInsertTabViewItem - Inserted the item in the wrong position."); + Assert.That (controller.TabViewItems [1] == item, Is.True, "NSTabViewControllerShouldInsertTabViewItem - Failed to insert the item at the given position."); + Assert.That (controller.TabViewItems [0] == item, Is.False, "NSTabViewControllerShouldInsertTabViewItem - Inserted the item in the wrong position."); } [Test] @@ -122,7 +122,7 @@ public void NSTabViewControllerShouldGetTabViewItem () var retrievedItem = controller.GetTabViewItem (viewController); - Assert.IsTrue (retrievedItem == item, "NSTabViewControllerShouldGetTabViewItem - Failed to get TabViewItem from ViewController"); + Assert.That (retrievedItem == item, Is.True, "NSTabViewControllerShouldGetTabViewItem - Failed to get TabViewItem from ViewController"); } } } diff --git a/tests/monotouch-test/AppKit/NSTabViewItem.cs b/tests/monotouch-test/AppKit/NSTabViewItem.cs index 6a269b60302b..fd1f4ab3a89d 100644 --- a/tests/monotouch-test/AppKit/NSTabViewItem.cs +++ b/tests/monotouch-test/AppKit/NSTabViewItem.cs @@ -19,7 +19,7 @@ public void NSTabViewItemShouldChangeImage () var image = item.Image; item.Image = new NSImage (); - Assert.IsFalse (item.Image == image, "NSTabViewItemShouldChangeImage - Failed to set the Image property"); + Assert.That (item.Image == image, Is.False, "NSTabViewItemShouldChangeImage - Failed to set the Image property"); } [Test] @@ -28,7 +28,7 @@ public void NSTabViewItemShouldChangeViewController () var vc = item.ViewController; item.ViewController = new NSViewController (); - Assert.IsFalse (item.ViewController == vc, "NSTabViewItemShouldChangeViewController - Failed to set the ViewController property"); + Assert.That (item.ViewController == vc, Is.False, "NSTabViewItemShouldChangeViewController - Failed to set the ViewController property"); } } } diff --git a/tests/monotouch-test/AppKit/NSTableColumn.cs b/tests/monotouch-test/AppKit/NSTableColumn.cs index 801d16c625b4..6827c94d0991 100644 --- a/tests/monotouch-test/AppKit/NSTableColumn.cs +++ b/tests/monotouch-test/AppKit/NSTableColumn.cs @@ -19,7 +19,7 @@ public void NSTableColumnShouldChangeTitle () var title = column.Title; column.Title = "Test"; - Assert.IsFalse (column.Title == title, "NSTableColumnShouldChangeTitle - Failed to set the Title property"); + Assert.That (column.Title == title, Is.False, "NSTableColumnShouldChangeTitle - Failed to set the Title property"); } } } diff --git a/tests/monotouch-test/AppKit/NSTableRowView.cs b/tests/monotouch-test/AppKit/NSTableRowView.cs index 4436827d068d..32d45cb3d7ee 100644 --- a/tests/monotouch-test/AppKit/NSTableRowView.cs +++ b/tests/monotouch-test/AppKit/NSTableRowView.cs @@ -19,7 +19,7 @@ public void NSTableRowViewShouldChangePreviousRowSelected () var selected = view.PreviousRowSelected; view.PreviousRowSelected = !selected; - Assert.IsFalse (view.PreviousRowSelected == selected, "NSTableRowViewShouldChangePreviousRowSelected - Failed to set the PreviousRowSelected property"); + Assert.That (view.PreviousRowSelected == selected, Is.False, "NSTableRowViewShouldChangePreviousRowSelected - Failed to set the PreviousRowSelected property"); } [Test] @@ -28,7 +28,7 @@ public void NSTableRowViewShouldChangeNextRowSelected () var selected = view.NextRowSelected; view.NextRowSelected = !selected; - Assert.IsFalse (view.NextRowSelected == selected, "NSTableRowViewShouldChangeNextRowSelected - Failed to set the NextRowSelected property"); + Assert.That (view.NextRowSelected == selected, Is.False, "NSTableRowViewShouldChangeNextRowSelected - Failed to set the NextRowSelected property"); } } } diff --git a/tests/monotouch-test/AppKit/NSTextField.cs b/tests/monotouch-test/AppKit/NSTextField.cs index 44244c9e8f98..9af67abd0f4f 100644 --- a/tests/monotouch-test/AppKit/NSTextField.cs +++ b/tests/monotouch-test/AppKit/NSTextField.cs @@ -19,7 +19,7 @@ public void NSTextFieldShouldChangePlaceholderString () var placeholder = textField.PlaceholderString; textField.PlaceholderString = "Test"; - Assert.IsFalse (textField.PlaceholderString == placeholder, "NSTextFieldShouldChangePlaceholderString - Failed to set the PlaceholderString property"); + Assert.That (textField.PlaceholderString == placeholder, Is.False, "NSTextFieldShouldChangePlaceholderString - Failed to set the PlaceholderString property"); } [Test] @@ -28,7 +28,7 @@ public void NSTextFieldShouldChangePlaceholderAttributedString () var placeholder = textField.PlaceholderAttributedString; textField.PlaceholderAttributedString = new NSAttributedString ("Test"); - Assert.IsFalse (textField.PlaceholderAttributedString == placeholder, "NSTextFieldShouldChangePlaceholderAttributedString - Failed to set the PlaceholderAttributedString property"); + Assert.That (textField.PlaceholderAttributedString == placeholder, Is.False, "NSTextFieldShouldChangePlaceholderAttributedString - Failed to set the PlaceholderAttributedString property"); } } } diff --git a/tests/monotouch-test/AppKit/NSTextFinder.cs b/tests/monotouch-test/AppKit/NSTextFinder.cs index c922d955e69a..8a5c789fc2cb 100644 --- a/tests/monotouch-test/AppKit/NSTextFinder.cs +++ b/tests/monotouch-test/AppKit/NSTextFinder.cs @@ -13,7 +13,7 @@ public class NSTextFinderTests { public void NSTextFinderConstructor () { NSTextFinder f = new NSTextFinder (); - Assert.IsNotNull (f); + Assert.That (f, Is.Not.Null); FinderClient client = new FinderClient (); f.Client = client; diff --git a/tests/monotouch-test/AppKit/NSTextInputClient.cs b/tests/monotouch-test/AppKit/NSTextInputClient.cs index 3554327c1a18..b088e1514ead 100644 --- a/tests/monotouch-test/AppKit/NSTextInputClient.cs +++ b/tests/monotouch-test/AppKit/NSTextInputClient.cs @@ -14,7 +14,7 @@ public void SetUp () { textView = new NSTextView (new CGRect (0, 0, 37, 120)); textView.Value = "This is a new string"; - Assert.AreEqual (textView.Value, "This is a new string", "NSTextInputClientSetup - Failed to set value"); + Assert.That (textView.Value, Is.EqualTo ("This is a new string"), "NSTextInputClientSetup - Failed to set value"); } [TearDown] @@ -28,7 +28,7 @@ public void NSTextInputClient_ShouldInsertText () { textView.InsertText ((NSString) "Test", new NSRange (5, 4)); - Assert.AreEqual (textView.Value, "This Test new string", "NSTextInputClient_ShouldInsertText - Failed to insert text"); + Assert.That (textView.Value, Is.EqualTo ("This Test new string"), "NSTextInputClient_ShouldInsertText - Failed to insert text"); } [Test] @@ -36,8 +36,8 @@ public void NSTextInputClient_ShouldMarkText () { textView.SetMarkedText ((NSString) "Testing", new NSRange (0, 10), new NSRange (5, 4)); - Assert.IsTrue (textView.HasMarkedText, "NSTextInputClient_ShouldMarkText - Failed to mark text"); - Assert.AreEqual (textView.MarkedRange, new NSRange (5, 7)); + Assert.That (textView.HasMarkedText, Is.True, "NSTextInputClient_ShouldMarkText - Failed to mark text"); + Assert.That (new NSRange (5, 7), Is.EqualTo (textView.MarkedRange)); textView.UnmarkText (); } @@ -45,7 +45,7 @@ public void NSTextInputClient_ShouldMarkText () [Test] public void NSTextInputClient_ShouldGetValidAttributesForMarkedText () { - Assert.IsTrue (textView.ValidAttributesForMarkedText.Length > 0, "NSTextInputClient_ShouldGetValidAttributesForMarkedTExt - No valid attributes"); + Assert.That (textView.ValidAttributesForMarkedText.Length > 0, Is.True, "NSTextInputClient_ShouldGetValidAttributesForMarkedTExt - No valid attributes"); } [Test] @@ -53,12 +53,12 @@ public void NSTextInputClient_ShouldUnmarkText () { textView.SetMarkedText ((NSString) "Testing", new NSRange (0, 10), new NSRange (5, 4)); - Assert.IsTrue (textView.HasMarkedText, "NSTextInputClient_ShouldUnMarkText - Failed to mark text"); + Assert.That (textView.HasMarkedText, Is.True, "NSTextInputClient_ShouldUnMarkText - Failed to mark text"); textView.UnmarkText (); - Assert.IsFalse (textView.HasMarkedText, "NSTextInputClient_ShouldUnmarkText - Failed to Unmark text"); - Assert.IsTrue (textView.MarkedRange.Length == 0, "NSTextInputClient_ShouldUnmarkText - MarkedRange is not 0"); + Assert.That (textView.HasMarkedText, Is.False, "NSTextInputClient_ShouldUnmarkText - Failed to Unmark text"); + Assert.That (textView.MarkedRange.Length == 0, Is.True, "NSTextInputClient_ShouldUnmarkText - MarkedRange is not 0"); } [Test] @@ -67,8 +67,8 @@ public void NSTextInputClient_ShouldGetAttributedSubstring () NSRange range; var attributedString = textView.GetAttributedSubstring (new NSRange (10, 15), out range); - Assert.AreEqual (attributedString.Value, "new string", "NSTextInputClient_ShouldGetAttributedSubstring - Failed to get the correct string"); - Assert.AreEqual (range, new NSRange (10, 10), "NSTextInputClient_ShouldGetAttributedSubstring - Wrong range value returned"); + Assert.That (attributedString.Value, Is.EqualTo ("new string"), "NSTextInputClient_ShouldGetAttributedSubstring - Failed to get the correct string"); + Assert.That (new NSRange (10, 10), Is.EqualTo (range), "NSTextInputClient_ShouldGetAttributedSubstring - Wrong range value returned"); } [Test] @@ -88,13 +88,13 @@ public void NSTextInputClient_ShouldGetFirstRect () [Test] public void NSTextInputClient_ShouldGetAttributedString () { - Assert.AreEqual (textView.AttributedString.Value, "This is a new string", "NSTextInputClient_ShouldGetAttributedString - Returned the wrong attributed string"); + Assert.That (textView.AttributedString.Value, Is.EqualTo ("This is a new string"), "NSTextInputClient_ShouldGetAttributedString - Returned the wrong attributed string"); } [Test] public void NSTextInputClient_ShouldGetFractionofDistanceThroughGlyph () { - Assert.IsTrue (textView.GetFractionOfDistanceThroughGlyph (new CGPoint (1, 2)) == 0, "NSTextInputClient_ShouldGetFractionofDistanceThroughGlyph - Returned wrong fraaction value"); + Assert.That (textView.GetFractionOfDistanceThroughGlyph (new CGPoint (1, 2)) == 0, Is.True, "NSTextInputClient_ShouldGetFractionofDistanceThroughGlyph - Returned wrong fraaction value"); } [Test] @@ -106,13 +106,13 @@ public void NSTextInputClient_ShouldGetBaselineDelta () [Test] public void NSTextInputClient_ShouldGetDrawsVertically () { - Assert.IsFalse (textView.DrawsVertically (4), "NSTextInputClient_ShouldGetDrawsVertically - Returned wrong value"); + Assert.That (textView.DrawsVertically (4), Is.False, "NSTextInputClient_ShouldGetDrawsVertically - Returned wrong value"); } [Test] public void NSTextInputClient_ShouldGetWindowLevel () { - Assert.AreEqual (textView.WindowLevel, NSWindowLevel.Normal, "NSTextInputClient_ShouldGetWindowLevel - WindowLevel returned the wrong value"); + Assert.That (NSWindowLevel.Normal, Is.EqualTo (textView.WindowLevel), "NSTextInputClient_ShouldGetWindowLevel - WindowLevel returned the wrong value"); } } } diff --git a/tests/monotouch-test/AppKit/NSTextView.cs b/tests/monotouch-test/AppKit/NSTextView.cs index 956920381808..2e4dde9c5f90 100644 --- a/tests/monotouch-test/AppKit/NSTextView.cs +++ b/tests/monotouch-test/AppKit/NSTextView.cs @@ -19,7 +19,7 @@ public void NSTextViewShouldChangeUsesRolloverButtonForSelection () var usesRollover = view.UsesRolloverButtonForSelection; view.UsesRolloverButtonForSelection = !usesRollover; - Assert.IsFalse (view.UsesRolloverButtonForSelection == usesRollover, "NSTextViewShouldChangeUsesRolloverButtonForSelection - Failed to set the UsesRolloverButtonForSelection property"); + Assert.That (view.UsesRolloverButtonForSelection == usesRollover, Is.False, "NSTextViewShouldChangeUsesRolloverButtonForSelection - Failed to set the UsesRolloverButtonForSelection property"); } } } diff --git a/tests/monotouch-test/AppKit/NSToolbar.cs b/tests/monotouch-test/AppKit/NSToolbar.cs index c144f4d9d7fa..5c736525cc4b 100644 --- a/tests/monotouch-test/AppKit/NSToolbar.cs +++ b/tests/monotouch-test/AppKit/NSToolbar.cs @@ -20,7 +20,7 @@ public void NSToolbarShouldChangeAllowsExtensionItems () var allows = toolbar.AllowsExtensionItems; toolbar.AllowsExtensionItems = !allows; - Assert.IsFalse (toolbar.AllowsExtensionItems == allows, "NSToolbarShouldChangeAllowsExtensionItems - Failed to set the AllowsExtensionItems property"); + Assert.That (toolbar.AllowsExtensionItems == allows, Is.False, "NSToolbarShouldChangeAllowsExtensionItems - Failed to set the AllowsExtensionItems property"); } [Test] diff --git a/tests/monotouch-test/AppKit/NSToolbarItem.cs b/tests/monotouch-test/AppKit/NSToolbarItem.cs index 21df96163c84..bac9a2977d72 100644 --- a/tests/monotouch-test/AppKit/NSToolbarItem.cs +++ b/tests/monotouch-test/AppKit/NSToolbarItem.cs @@ -10,15 +10,15 @@ public void InitTests () { const string TestLabel = "NSToolbarItemTests.Label"; NSToolbarItem item = new NSToolbarItem (); - Assert.IsNotNull (item.Handle, "NSToolbarItem has handle"); + Assert.That (item.Handle, Is.Not.Null, "NSToolbarItem has handle"); item.Label = TestLabel; - Assert.AreEqual (item.Label, TestLabel, "NSToolbarItem has non null Label"); + Assert.That (TestLabel, Is.EqualTo (item.Label), "NSToolbarItem has non null Label"); NSToolbarItemGroup group = new NSToolbarItemGroup (); - Assert.IsNotNull (group.Handle, "NSToolbarItemGroup has handle"); - Assert.AreEqual (group.Subitems.Length, 0, "NSToolbarItemGroup has zero items"); + Assert.That (group.Handle, Is.Not.Null, "NSToolbarItemGroup has handle"); + Assert.That (group.Subitems.Length, Is.EqualTo (0), "NSToolbarItemGroup has zero items"); group.Label = TestLabel; - Assert.AreEqual (group.Label, TestLabel, "NSToolbarItemGroup has non null Label"); + Assert.That (TestLabel, Is.EqualTo (group.Label), "NSToolbarItemGroup has non null Label"); } } } diff --git a/tests/monotouch-test/AppKit/NSUserDefaultsController.cs b/tests/monotouch-test/AppKit/NSUserDefaultsController.cs index 85389769d65e..f1f43a0f16f9 100644 --- a/tests/monotouch-test/AppKit/NSUserDefaultsController.cs +++ b/tests/monotouch-test/AppKit/NSUserDefaultsController.cs @@ -12,7 +12,7 @@ public void NSUserDefaultsControllerShouldGetSharedController () { controller = NSUserDefaultsController.SharedUserDefaultsController; - Assert.IsNotNull (controller, "NSUserDefaultsControllerShouldGetDefaultController - SharedUserDefaultsController returned null"); + Assert.That (controller, Is.Not.Null, "NSUserDefaultsControllerShouldGetDefaultController - SharedUserDefaultsController returned null"); } [Test] @@ -20,7 +20,7 @@ public void NSUserDefaultsControllerShouldCreateNewControllerWithDefaultConstruc { controller = new NSUserDefaultsController (); - Assert.IsNotNull (controller, "NSUserDefaultsControllerShouldCreateNewControllerWithDefaultConstructor - Constructor returned null"); + Assert.That (controller, Is.Not.Null, "NSUserDefaultsControllerShouldCreateNewControllerWithDefaultConstructor - Constructor returned null"); } [Test] @@ -28,9 +28,9 @@ public void NSUserDefaultsControllerShouldCreateNewControllerWithNullParameters { controller = new NSUserDefaultsController (null, null); - Assert.IsTrue (controller.Defaults == NSUserDefaults.StandardUserDefaults); - Assert.IsTrue (controller.InitialValues is null); - Assert.IsNotNull (controller, "NSUserDefaultsControllerShouldCreateNewControllerWithNullParameters - Constructor returned null"); + Assert.That (controller.Defaults, Is.EqualTo (NSUserDefaults.StandardUserDefaults)); + Assert.That (controller.InitialValues, Is.Null); + Assert.That (controller, Is.Not.Null, "NSUserDefaultsControllerShouldCreateNewControllerWithNullParameters - Constructor returned null"); } [Test] @@ -39,9 +39,9 @@ public void NSUserDefaultsControllerShouldCreateNewControllerWithParameters () var initialValues = new NSDictionary (); controller = new NSUserDefaultsController (NSUserDefaults.StandardUserDefaults, initialValues); - Assert.IsTrue (controller.Defaults == NSUserDefaults.StandardUserDefaults); - Assert.IsTrue (controller.InitialValues == initialValues); - Assert.IsNotNull (controller, "NSUserDefaultsControllerShouldCreateNewControllerWithParameters - Constructor returned null"); + Assert.That (controller.Defaults, Is.EqualTo (NSUserDefaults.StandardUserDefaults)); + Assert.That (controller.InitialValues, Is.EqualTo (initialValues)); + Assert.That (controller, Is.Not.Null, "NSUserDefaultsControllerShouldCreateNewControllerWithParameters - Constructor returned null"); } [Test] @@ -51,7 +51,7 @@ public void NSUserDefaultsControllerShouldChangeInitialValues () var initialValues = controller.InitialValues; controller.InitialValues = new NSDictionary (); - Assert.IsFalse (controller.InitialValues == initialValues, "NSUserDefaultsControllerShouldChangeInitialValues - Failed to set the InitialValues property"); + Assert.That (controller.InitialValues, Is.Not.EqualTo (initialValues), "NSUserDefaultsControllerShouldChangeInitialValues - Failed to set the InitialValues property"); } [Test] @@ -61,7 +61,7 @@ public void NSUserDefaultsControllerShouldChangeAppliesImmediately () var appliesImmediately = controller.AppliesImmediately; controller.AppliesImmediately = !appliesImmediately; - Assert.IsFalse (controller.AppliesImmediately == appliesImmediately, "NSUserDefaultsControllerShouldChangeAppliesImmediately - Failed to set the AppliesImmediately property"); + Assert.That (controller.AppliesImmediately, Is.Not.EqualTo (appliesImmediately), "NSUserDefaultsControllerShouldChangeAppliesImmediately - Failed to set the AppliesImmediately property"); } } } diff --git a/tests/monotouch-test/AppKit/NSView.cs b/tests/monotouch-test/AppKit/NSView.cs index 830c77187bb5..aaeb7031e712 100644 --- a/tests/monotouch-test/AppKit/NSView.cs +++ b/tests/monotouch-test/AppKit/NSView.cs @@ -23,7 +23,7 @@ public void NSViewShouldAddGestureRecognizer () length = view.GestureRecognizers.Length; view.AddGestureRecognizer (new NSGestureRecognizer ()); - Assert.IsTrue (view.GestureRecognizers.Length == length + 1, "NSViewShouldAddGestureRecognizer - Failed to add recognizer, count didn't change."); + Assert.That (view.GestureRecognizers.Length, Is.EqualTo (length + 1), "NSViewShouldAddGestureRecognizer - Failed to add recognizer, count didn't change."); } [Test] @@ -32,11 +32,11 @@ public void NSViewShouldRemoveGestureRecognizer () var recognizer = new NSClickGestureRecognizer (); view.AddGestureRecognizer (recognizer); - Assert.IsTrue (view.GestureRecognizers.Length != 0, "NSViewShouldRemoveGestureRecognizer - Failed to add gesture recognizer"); + Assert.That (view.GestureRecognizers.Length, Is.Not.EqualTo (0), "NSViewShouldRemoveGestureRecognizer - Failed to add gesture recognizer"); view.RemoveGestureRecognizer (recognizer); - Assert.IsTrue (view.GestureRecognizers.Length == 0, "NSViewShouldRemoveGestureRecognizer - Failed to remove gesture recognizer"); + Assert.That (view.GestureRecognizers.Length, Is.EqualTo (0), "NSViewShouldRemoveGestureRecognizer - Failed to remove gesture recognizer"); } [Test] @@ -45,11 +45,16 @@ public void NSViewShouldChangeGestureRecognizers () var recognizers = view.GestureRecognizers; view.GestureRecognizers = new NSGestureRecognizer [] { new NSClickGestureRecognizer (), new NSPanGestureRecognizer () }; - Assert.IsFalse (view.GestureRecognizers == recognizers); + Assert.That (view.GestureRecognizers, Is.Not.EqualTo (recognizers)); } [Test] [UnconditionalSuppressMessage ("Trimming", "IL2075", Justification = "This test handles APIs that have been linked away, so it's trimmer-safe.")] + [DynamicDependency ("Menu", typeof (AppKit.NSCell))] + [DynamicDependency ("Menu", typeof (AppKit.NSMenuItem))] + [DynamicDependency ("Menu", typeof (AppKit.NSPathControl))] + [DynamicDependency ("Menu", typeof (AppKit.NSPopUpButton))] + [DynamicDependency ("Menu", typeof (AppKit.NSPopUpButtonCell))] public void AllItemsWithNSMenuShouldAllowNull () { // Can't test NSResponder since it is abstract @@ -64,7 +69,7 @@ public void AllItemsWithNSMenuShouldAllowNull () foreach (var ctor in types) { var o = ctor (); var prop = o.GetType ().GetProperty ("Menu", BindingFlags.Public | BindingFlags.Instance); - if (prop is null && TestRuntime.IsLinkAll) + if (prop is null && TestRuntime.IsLinkAny) continue; // the property was linked away. prop.SetValue (o, null, null); } @@ -87,10 +92,10 @@ public void SubviewSort () Assert.Throws (() => containerView.SortSubviews (null), "ANE"); - Assert.AreEqual (3, containerView.Subviews.Length, "Presort Length"); - Assert.AreEqual ("b", ((NSTextView) containerView.Subviews [0]).Value, "Presort Value 0"); - Assert.AreEqual ("c", ((NSTextView) containerView.Subviews [1]).Value, "Presort Value 1"); - Assert.AreEqual ("a", ((NSTextView) containerView.Subviews [2]).Value, "Presort Value 2"); + Assert.That (containerView.Subviews.Length, Is.EqualTo (3), "Presort Length"); + Assert.That (((NSTextView) containerView.Subviews [0]).Value, Is.EqualTo ("b"), "Presort Value 0"); + Assert.That (((NSTextView) containerView.Subviews [1]).Value, Is.EqualTo ("c"), "Presort Value 1"); + Assert.That (((NSTextView) containerView.Subviews [2]).Value, Is.EqualTo ("a"), "Presort Value 2"); containerView.SortSubviews ((x, y) => { var viewX = (NSTextView) x; @@ -104,10 +109,10 @@ public void SubviewSort () return NSComparisonResult.Descending; }); - Assert.AreEqual (3, containerView.Subviews.Length, "Postsort Length"); - Assert.AreEqual ("a", ((NSTextView) containerView.Subviews [0]).Value, "Postsort Value 0"); - Assert.AreEqual ("b", ((NSTextView) containerView.Subviews [1]).Value, "Postsort Value 1"); - Assert.AreEqual ("c", ((NSTextView) containerView.Subviews [2]).Value, "Postsort Value 2"); + Assert.That (containerView.Subviews.Length, Is.EqualTo (3), "Postsort Length"); + Assert.That (((NSTextView) containerView.Subviews [0]).Value, Is.EqualTo ("a"), "Postsort Value 0"); + Assert.That (((NSTextView) containerView.Subviews [1]).Value, Is.EqualTo ("b"), "Postsort Value 1"); + Assert.That (((NSTextView) containerView.Subviews [2]).Value, Is.EqualTo ("c"), "Postsort Value 2"); try { containerView.SortSubviews ((x, y) => { @@ -115,8 +120,8 @@ public void SubviewSort () }); Assert.Fail ("No exception thrown"); } catch (Exception e) { - Assert.AreEqual ("An exception occurred during sorting.", e.Message, "Exception Message"); - Assert.AreEqual ("Something went wrong", e.InnerException.Message, "InnerException Message"); + Assert.That (e.Message, Is.EqualTo ("An exception occurred during sorting."), "Exception Message"); + Assert.That (e.InnerException.Message, Is.EqualTo ("Something went wrong"), "InnerException Message"); } } } diff --git a/tests/monotouch-test/AppKit/NSViewController.cs b/tests/monotouch-test/AppKit/NSViewController.cs index 2b5c5b344352..341424bb5fbb 100644 --- a/tests/monotouch-test/AppKit/NSViewController.cs +++ b/tests/monotouch-test/AppKit/NSViewController.cs @@ -19,7 +19,7 @@ public void NSViewControllerShouldAddChildViewController () var child = new NSViewController (); controller.AddChildViewController (child); - Assert.IsTrue (controller.ChildViewControllers.Length == 1, "NSViewControllerShouldAddChildViewControllers - Failed to add child view controller"); + Assert.That (controller.ChildViewControllers.Length == 1, Is.True, "NSViewControllerShouldAddChildViewControllers - Failed to add child view controller"); } [Test] @@ -28,11 +28,11 @@ public void NSViewControllerShouldRemoveChildViewController () var child = new NSViewController (); controller.AddChildViewController (child); - Assert.IsTrue (controller.ChildViewControllers.Length == 1, "NSViewControllerShouldRemoveChildViewControllers - Failed to add child view controller"); + Assert.That (controller.ChildViewControllers.Length == 1, Is.True, "NSViewControllerShouldRemoveChildViewControllers - Failed to add child view controller"); controller.RemoveChildViewController (0); - Assert.IsTrue (controller.ChildViewControllers.Length == 0, "NSViewControllerShouldRemoveChildViewController - Failed to remove child view controller"); + Assert.That (controller.ChildViewControllers.Length == 0, Is.True, "NSViewControllerShouldRemoveChildViewController - Failed to remove child view controller"); } [Test] @@ -41,13 +41,13 @@ public void NSViewControllerShouldInsertChildViewController () controller.AddChildViewController (new NSViewController ()); controller.AddChildViewController (new NSViewController ()); - Assert.IsTrue (controller.ChildViewControllers.Length == 2, "NSViewControllerShouldInsertChildViewController - Failed to add child view controller"); + Assert.That (controller.ChildViewControllers.Length == 2, Is.True, "NSViewControllerShouldInsertChildViewController - Failed to add child view controller"); var child = new NSViewController (); controller.InsertChildViewController (child, 1); - Assert.IsTrue (controller.ChildViewControllers.Length == 3, "NSViewControllerShouldInsertChildViewController - Failed to insert child view controller"); - Assert.IsTrue (controller.ChildViewControllers [1] == child, "NSViewControllerShouldInsertChildViewController - Inserted child view controller at the wrong index."); + Assert.That (controller.ChildViewControllers.Length == 3, Is.True, "NSViewControllerShouldInsertChildViewController - Failed to insert child view controller"); + Assert.That (controller.ChildViewControllers [1] == child, Is.True, "NSViewControllerShouldInsertChildViewController - Inserted child view controller at the wrong index."); } } } diff --git a/tests/monotouch-test/AppKit/NSVisualEffectView.cs b/tests/monotouch-test/AppKit/NSVisualEffectView.cs index 19a37721af4e..40a57b9a2d2c 100644 --- a/tests/monotouch-test/AppKit/NSVisualEffectView.cs +++ b/tests/monotouch-test/AppKit/NSVisualEffectView.cs @@ -19,7 +19,7 @@ public void NSVisualEffectViewShouldChangeMaterial () var material = view.Material; view.Material = NSVisualEffectMaterial.Titlebar; - Assert.IsFalse (view.Material == material, "NSVisualEffectViewShouldChangeMaterial - Failed to set the Material property"); + Assert.That (view.Material == material, Is.False, "NSVisualEffectViewShouldChangeMaterial - Failed to set the Material property"); } [Test] @@ -28,7 +28,7 @@ public void NSVisualEffectViewShouldChangeBlendingMode () var blendingMode = view.BlendingMode; view.BlendingMode = NSVisualEffectBlendingMode.WithinWindow; - Assert.IsFalse (view.BlendingMode == blendingMode, "NSVisualEffectViewShouldChangeBlendingMode - Failed to set the BlendingMode property"); + Assert.That (view.BlendingMode == blendingMode, Is.False, "NSVisualEffectViewShouldChangeBlendingMode - Failed to set the BlendingMode property"); } [Test] @@ -37,7 +37,7 @@ public void NSVisualEffectViewShouldChangeState () var state = view.State; view.State = NSVisualEffectState.Inactive; - Assert.IsFalse (view.State == state, "NSVisualEffectViewShouldChangeState - Failed to set the State property"); + Assert.That (view.State == state, Is.False, "NSVisualEffectViewShouldChangeState - Failed to set the State property"); } [Test] @@ -46,7 +46,7 @@ public void NSVisualEffectViewShouldChangeMaskImage () var image = view.MaskImage; view.MaskImage = new NSImage (); - Assert.IsFalse (view.MaskImage == image, "NSVisualEffectViewShouldChangeMaskImage - Failed to set the MaskImage property"); + Assert.That (view.MaskImage == image, Is.False, "NSVisualEffectViewShouldChangeMaskImage - Failed to set the MaskImage property"); } } } diff --git a/tests/monotouch-test/AppKit/NSWorkspace.cs b/tests/monotouch-test/AppKit/NSWorkspace.cs index 2696f1f2fce3..306ce82682f0 100644 --- a/tests/monotouch-test/AppKit/NSWorkspace.cs +++ b/tests/monotouch-test/AppKit/NSWorkspace.cs @@ -9,10 +9,10 @@ public class NSWorkspaceTests { [Test] public void NSWorkspaceConstantTests () { - Assert.IsNotNull (NSWorkspace.LaunchConfigurationAppleEvent); - Assert.IsNotNull (NSWorkspace.LaunchConfigurationArguments); - Assert.IsNotNull (NSWorkspace.LaunchConfigurationEnvironment); - Assert.IsNotNull (NSWorkspace.LaunchConfigurationArchitecture); + Assert.That (NSWorkspace.LaunchConfigurationAppleEvent, Is.Not.Null); + Assert.That (NSWorkspace.LaunchConfigurationArguments, Is.Not.Null); + Assert.That (NSWorkspace.LaunchConfigurationEnvironment, Is.Not.Null); + Assert.That (NSWorkspace.LaunchConfigurationArchitecture, Is.Not.Null); } [Test] diff --git a/tests/monotouch-test/Asserts.cs b/tests/monotouch-test/Asserts.cs index 897b15d77030..b24178745c9d 100644 --- a/tests/monotouch-test/Asserts.cs +++ b/tests/monotouch-test/Asserts.cs @@ -31,90 +31,90 @@ public static class Asserts { public static void AreEqual (bool expected, bool actual, string message) { - Assert.AreEqual (expected, actual, $"{message} (M) expected: {expected} actual: {actual}"); + Assert.That (actual, Is.EqualTo (expected), $"{message} (M) expected: {expected} actual: {actual}"); } public static void AreEqual (float expected, float actual, string message) { - Assert.AreEqual (expected, actual, $"{message} (M) expected: {expected} actual: {actual}"); + Assert.That (actual, Is.EqualTo (expected), $"{message} (M) expected: {expected} actual: {actual}"); } public static void AreEqual (float expected, float actual, float delta, string message) { - Assert.AreEqual (expected, actual, delta, message); + Assert.That (actual, Is.EqualTo (expected).Within (delta), message); } public static void AreEqual (Vector2 expected, Vector2 actual, string message) { - Assert.AreEqual (expected.X, actual.X, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y), $"{message} (Y) expected: {expected} actual: {actual}"); } public static void AreEqual (Vector3 expected, Vector3 actual, string message) { - Assert.AreEqual (expected.X, actual.X, 0.001, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, 0.001, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, 0.001, $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (0.001), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (0.001), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z).Within (0.001), $"{message} (Z) expected: {expected} actual: {actual}"); } public static void AreEqual (Vector3 expected, Vector3 actual, float delta, string message) { - Assert.AreEqual (expected.X, actual.X, delta, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, delta, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, delta, $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (delta), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (delta), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z).Within (delta), $"{message} (Z) expected: {expected} actual: {actual}"); } public static void AreEqual (Vector3 expected, VectorFloat3 actual, string message) { - Assert.AreEqual (expected.X, actual.X, 0.001, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, 0.001, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, 0.001, $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (0.001), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (0.001), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z).Within (0.001), $"{message} (Z) expected: {expected} actual: {actual}"); } public static void AreEqual (VectorFloat3 expected, Vector3 actual, string message) { - Assert.AreEqual (expected.X, actual.X, 0.001, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, 0.001, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, 0.001, $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (0.001), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (0.001), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z).Within (0.001), $"{message} (Z) expected: {expected} actual: {actual}"); } public static void AreEqual (VectorFloat3 expected, VectorFloat3 actual, string message) { - Assert.AreEqual (expected.X, actual.X, 0.001, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, 0.001, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, 0.001, $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (0.001), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (0.001), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z).Within (0.001), $"{message} (Z) expected: {expected} actual: {actual}"); } public static void AreEqual (VectorFloat3 expected, VectorFloat3 actual, float delta, string message) { - Assert.AreEqual (expected.X, actual.X, delta, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, delta, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, delta, $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (delta), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (delta), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z).Within (delta), $"{message} (Z) expected: {expected} actual: {actual}"); } public static void AreEqual (Vector4 expected, Vector4 actual, string message) { - Assert.AreEqual (expected.X, actual.X, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, $"{message} (Z) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.W, actual.W, $"{message} (W) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z), $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.W, Is.EqualTo (expected.W), $"{message} (W) expected: {expected} actual: {actual}"); } public static void AreEqual (float expectedX, float expectedY, float expectedZ, float expectedW, Vector4 actual, string message) { - Assert.AreEqual (expectedX, actual.X, $"{message} (X) expected: {new Vector4 (expectedX, expectedY, expectedZ, expectedW)} actual: {actual}"); - Assert.AreEqual (expectedY, actual.Y, $"{message} (Y) expected: {new Vector4 (expectedX, expectedY, expectedZ, expectedW)} actual: {actual}"); - Assert.AreEqual (expectedZ, actual.Z, $"{message} (Z) expected: {new Vector4 (expectedX, expectedY, expectedZ, expectedW)} actual: {actual}"); - Assert.AreEqual (expectedW, actual.W, $"{message} (W) expected: {new Vector4 (expectedX, expectedY, expectedZ, expectedW)} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expectedX), $"{message} (X) expected: {new Vector4 (expectedX, expectedY, expectedZ, expectedW)} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expectedY), $"{message} (Y) expected: {new Vector4 (expectedX, expectedY, expectedZ, expectedW)} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expectedZ), $"{message} (Z) expected: {new Vector4 (expectedX, expectedY, expectedZ, expectedW)} actual: {actual}"); + Assert.That (actual.W, Is.EqualTo (expectedW), $"{message} (W) expected: {new Vector4 (expectedX, expectedY, expectedZ, expectedW)} actual: {actual}"); } public static void AreEqual (Vector4 expected, Vector4 actual, float delta, string message) { - Assert.AreEqual (expected.X, actual.X, delta, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, delta, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, delta, $"{message} (Z) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.W, actual.W, delta, $"{message} (W) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (delta), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (delta), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z).Within (delta), $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.W, Is.EqualTo (expected.W).Within (delta), $"{message} (W) expected: {expected} actual: {actual}"); } public static void AreEqual (Matrix4 expected, Matrix4 actual, string message) @@ -159,16 +159,16 @@ public static void AreEqual (Matrix4 expected, Matrix4 actual, float delta, stri public static void AreEqual (Vector2i expected, Vector2i actual, string message) { - Assert.AreEqual (expected.X, actual.X, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y), $"{message} (Y) expected: {expected} actual: {actual}"); } public static void AreEqual (Vector4i expected, Vector4i actual, string message) { - Assert.AreEqual (expected.X, actual.X, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, $"{message} (Z) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.W, actual.W, $"{message} (W) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z), $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.W, Is.EqualTo (expected.W), $"{message} (W) expected: {expected} actual: {actual}"); } public static void AreEqual (MDLAxisAlignedBoundingBox expected, MDLAxisAlignedBoundingBox actual, string message) @@ -179,10 +179,10 @@ public static void AreEqual (MDLAxisAlignedBoundingBox expected, MDLAxisAlignedB public static void AreEqual (Quaternion expected, Quaternion actual, string message) { - Assert.AreEqual (expected.X, actual.X, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, $"{message} (Z) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.W, actual.W, $"{message} (W) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z), $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.W, Is.EqualTo (expected.W), $"{message} (W) expected: {expected} actual: {actual}"); } public static void AreEqual (Quaternion [] expected, Quaternion [] actual, string message) @@ -195,7 +195,7 @@ public static void AreEqual (Quaternion [] expected, Quaternion [] actual, strin Assert.Fail ($"Expected {expected}, got null. {message}"); } - Assert.AreEqual (expected.Length, actual.Length, $"{message} array lengths"); + Assert.That (actual.Length, Is.EqualTo (expected.Length), $"{message} array lengths"); for (var i = 0; i < expected.Length; i++) { AreEqual (expected [i], actual [i], message + $" [{i}]"); } @@ -203,23 +203,23 @@ public static void AreEqual (Quaternion [] expected, Quaternion [] actual, strin public static void AreEqual (Quaterniond expected, Quaterniond actual, string message) { - Assert.AreEqual (expected.X, actual.X, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, $"{message} (Z) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.W, actual.W, $"{message} (W) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z), $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.W, Is.EqualTo (expected.W), $"{message} (W) expected: {expected} actual: {actual}"); } public static void AreEqual (Quaterniond expected, Quaterniond actual, double delta, string message) { - Assert.AreEqual (expected.X, actual.X, delta, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, delta, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, delta, $"{message} (Z) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.W, actual.W, delta, $"{message} (W) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (delta), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (delta), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z).Within (delta), $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.W, Is.EqualTo (expected.W).Within (delta), $"{message} (W) expected: {expected} actual: {actual}"); } public static void AreEqual (Quaterniond [] expected, Quaterniond [] actual, string message) { - Assert.AreEqual (expected.Length, actual.Length, $"{message} array lengths"); + Assert.That (actual.Length, Is.EqualTo (expected.Length), $"{message} array lengths"); for (var i = 0; i < expected.Length; i++) { AreEqual (expected [i], actual [i], message + $" [{i}]"); } @@ -227,10 +227,10 @@ public static void AreEqual (Quaterniond [] expected, Quaterniond [] actual, str public static void AreEqual (MPSImageHistogramInfo expected, MPSImageHistogramInfo actual, string message) { - Assert.AreEqual (expected.HistogramForAlpha, actual.HistogramForAlpha, $"{message} HistogramForAlpha expected: {expected} actual: {actual}"); + Assert.That (actual.HistogramForAlpha, Is.EqualTo (expected.HistogramForAlpha), $"{message} HistogramForAlpha expected: {expected} actual: {actual}"); Asserts.AreEqual (expected.MaxPixelValue, actual.MaxPixelValue, $"{message} MaxPixelValue expected: {expected} actual: {actual}"); Asserts.AreEqual (expected.MinPixelValue, actual.MinPixelValue, $"{message} MinPixelValue expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.NumberOfHistogramEntries, actual.NumberOfHistogramEntries, $"{message} NumberOfHistogramEntries expected: {expected} actual: {actual}"); + Assert.That (actual.NumberOfHistogramEntries, Is.EqualTo (expected.NumberOfHistogramEntries), $"{message} NumberOfHistogramEntries expected: {expected} actual: {actual}"); } public static void AreEqual (MatrixFloat2x2 expected, MatrixFloat2x2 actual, string message) @@ -378,54 +378,54 @@ public static void AreEqual (MatrixFloat4x4 expected, Matrix4 actual, string mes #region Double Based Types public static void AreEqual (double expected, double actual, string message) { - Assert.AreEqual (expected, actual, $"{message} (M) expected: {expected} actual: {actual}"); + Assert.That (actual, Is.EqualTo (expected), $"{message} (M) expected: {expected} actual: {actual}"); } public static void AreEqual (double expected, double actual, double delta, string message) { - Assert.AreEqual (expected, actual, delta, message); + Assert.That (actual, Is.EqualTo (expected).Within (delta), message); } public static void AreEqual (VectorDouble2 expected, VectorDouble2 actual, string message) { - Assert.AreEqual (expected.X, actual.X, 0.001, message + " (X)"); - Assert.AreEqual (expected.Y, actual.Y, 0.001, message + " (Y)"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (0.001), message + " (X)"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (0.001), message + " (Y)"); } public static void AreEqual (VectorDouble2 expected, VectorDouble2 actual, double delta, string message) { - Assert.AreEqual (expected.X, actual.X, delta, message + " (X)"); - Assert.AreEqual (expected.Y, actual.Y, delta, message + " (Y)"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (delta), message + " (X)"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (delta), message + " (Y)"); } public static void AreEqual (VectorDouble3 expected, VectorDouble3 actual, string message) { - Assert.AreEqual (expected.X, actual.X, 0.001, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, 0.001, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, 0.001, $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (0.001), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (0.001), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z).Within (0.001), $"{message} (Z) expected: {expected} actual: {actual}"); } public static void AreEqual (VectorDouble3 expected, VectorDouble3 actual, double delta, string message) { - Assert.AreEqual (expected.X, actual.X, delta, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, delta, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, delta, $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (delta), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (delta), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z).Within (delta), $"{message} (Z) expected: {expected} actual: {actual}"); } public static void AreEqual (Vector4d expected, Vector4d actual, string message) { - Assert.AreEqual (expected.X, actual.X, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, $"{message} (Z) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.W, actual.W, $"{message} (W) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z), $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.W, Is.EqualTo (expected.W), $"{message} (W) expected: {expected} actual: {actual}"); } public static void AreEqual (Vector4d expected, Vector4d actual, double delta, string message) { - Assert.AreEqual (expected.X, actual.X, delta, $"{message} (X) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Y, actual.Y, delta, $"{message} (Y) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.Z, actual.Z, delta, $"{message} (Z) expected: {expected} actual: {actual}"); - Assert.AreEqual (expected.W, actual.W, delta, $"{message} (W) expected: {expected} actual: {actual}"); + Assert.That (actual.X, Is.EqualTo (expected.X).Within (delta), $"{message} (X) expected: {expected} actual: {actual}"); + Assert.That (actual.Y, Is.EqualTo (expected.Y).Within (delta), $"{message} (Y) expected: {expected} actual: {actual}"); + Assert.That (actual.Z, Is.EqualTo (expected.Z).Within (delta), $"{message} (Z) expected: {expected} actual: {actual}"); + Assert.That (actual.W, Is.EqualTo (expected.W).Within (delta), $"{message} (W) expected: {expected} actual: {actual}"); } public static void AreEqual (MatrixDouble4x4 expected, MatrixDouble4x4 actual, string message) diff --git a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/Contents.json b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/Contents.json index 6be52c8f7640..0e65c18b41c3 100644 --- a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/Contents.json +++ b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/Contents.json @@ -1,221 +1,15 @@ { "images": [ { - "size": "29x29", - "scale": "1x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "2x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "3x", - "idiom": "iphone" - }, - { - "size": "40x40", - "scale": "2x", - "idiom": "iphone" - }, - { - "size": "40x40", - "scale": "3x", - "idiom": "iphone" - }, - { - "filename": "icon-app-57.png", - "size": "57x57", - "scale": "1x", - "idiom": "iphone" - }, - { - "filename": "icon-app-57@2x.png", - "size": "57x57", - "scale": "2x", - "idiom": "iphone" - }, - { - "filename": "icon-app-60@2x.png", - "size": "60x60", - "scale": "2x", - "idiom": "iphone" - }, - { - "filename": "icon-app-60@3x.png", - "size": "60x60", - "scale": "3x", - "idiom": "iphone" - }, - { - "size": "29x29", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "29x29", - "scale": "2x", - "idiom": "ipad" - }, - { - "size": "40x40", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "40x40", - "scale": "2x", - "idiom": "ipad" - }, - { - "size": "50x50", - "scale": "1x", - "idiom": "ipad" - }, - { - "size": "50x50", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-83.5@2x.png", - "size": "83.5x83.5", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-72.png", - "size": "72x72", - "scale": "1x", - "idiom": "ipad" - }, - { - "filename": "icon-app-72@2x.png", - "size": "72x72", - "scale": "2x", - "idiom": "ipad" - }, - { - "filename": "icon-app-76.png", - "size": "76x76", - "scale": "1x", - "idiom": "ipad" - }, - { - "filename": "icon-app-76@2x.png", - "size": "76x76", - "scale": "2x", - "idiom": "ipad" - }, - { - "role": "notificationCenter", - "size": "24x24", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "notificationCenter", - "size": "27.5x27.5", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "companionSettings", - "size": "29x29", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "companionSettings", - "size": "29x29", - "scale": "3x", - "idiom": "watch" - }, - { - "role": "appLauncher", - "size": "40x40", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "longLook", - "size": "44x44", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "quickLook", - "size": "86x86", - "subtype": "38mm", - "scale": "2x", - "idiom": "watch" - }, - { - "role": "quickLook", - "size": "98x98", - "subtype": "42mm", - "scale": "2x", - "idiom": "watch" - }, - { - "size": "16x16", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "16x16", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "32x32", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "32x32", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "128x128", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "128x128", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "256x256", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "256x256", - "scale": "2x", - "idiom": "mac" - }, - { - "size": "512x512", - "scale": "1x", - "idiom": "mac" - }, - { - "size": "512x512", - "scale": "2x", - "idiom": "mac" + "filename": "icon-1024.png", + "idiom": "universal", + "platform": "ios", + "size": "1024x1024" } ], "info": { - "version": 1, - "author": "xcode" + "author": "xcode", + "version": 1 } -} \ No newline at end of file +} + diff --git a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/Icon-app-60@3x.png b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/Icon-app-60@3x.png deleted file mode 100644 index 45342a7513b6..000000000000 Binary files a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/Icon-app-60@3x.png and /dev/null differ diff --git a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-1024.png b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-1024.png new file mode 100644 index 000000000000..1e62561f25b7 Binary files /dev/null and b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-1024.png differ diff --git a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-57.png b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-57.png deleted file mode 100644 index ce1d9df94d4f..000000000000 Binary files a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-57.png and /dev/null differ diff --git a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png deleted file mode 100644 index d34d9c694d3f..000000000000 Binary files a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-57@2x.png and /dev/null differ diff --git a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png deleted file mode 100644 index 4409624b29d9..000000000000 Binary files a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-60@2x.png and /dev/null differ diff --git a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-72.png b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-72.png deleted file mode 100644 index 9a77ea277312..000000000000 Binary files a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-72.png and /dev/null differ diff --git a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png deleted file mode 100644 index 32f57d7d89da..000000000000 Binary files a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-72@2x.png and /dev/null differ diff --git a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-76.png b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-76.png deleted file mode 100644 index 12db0c47cc4e..000000000000 Binary files a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-76.png and /dev/null differ diff --git a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png deleted file mode 100644 index 163f1c7f0f18..000000000000 Binary files a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-76@2x.png and /dev/null differ diff --git a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png b/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png deleted file mode 100644 index 0bac1da399b5..000000000000 Binary files a/tests/monotouch-test/Assets.xcassets/AppIcons.appiconset/icon-app-83.5@2x.png and /dev/null differ diff --git a/tests/monotouch-test/AudioToolbox/AudioBalanceFadeTest.cs b/tests/monotouch-test/AudioToolbox/AudioBalanceFadeTest.cs index 5e0a3f55a00e..bafa39fda16a 100644 --- a/tests/monotouch-test/AudioToolbox/AudioBalanceFadeTest.cs +++ b/tests/monotouch-test/AudioToolbox/AudioBalanceFadeTest.cs @@ -19,7 +19,7 @@ public void GetBalanceFade () { var acl = AudioChannelLayout.FromAudioChannelLayoutTag (AudioChannelLayoutTag.AudioUnit_6_1); var abf = new AudioBalanceFade (acl); - Assert.IsNotNull (abf.GetBalanceFade ()); + Assert.That (abf.GetBalanceFade (), Is.Not.Null); } } } diff --git a/tests/monotouch-test/AudioToolbox/AudioBufferList.cs b/tests/monotouch-test/AudioToolbox/AudioBufferList.cs index 15dca28c24e4..c200ffc46217 100644 --- a/tests/monotouch-test/AudioToolbox/AudioBufferList.cs +++ b/tests/monotouch-test/AudioToolbox/AudioBufferList.cs @@ -12,17 +12,17 @@ public unsafe void Usage () var buffer = new byte [1024]; fixed (byte* ptr = buffer) { var list = (AudioBufferList*) ptr; - Assert.AreEqual (0, list->Count, "Count"); + Assert.That (list->Count, Is.EqualTo (0), "Count"); Assert.Throws (() => list->GetBuffer (0), "Item 0"); Assert.Throws (() => list->GetBuffer (-1), "Item -1"); Assert.Throws (() => list->GetBuffer (1), "Item 1"); *(int*) ptr = 3; - Assert.AreEqual (3, list->Count, "Count B"); + Assert.That (list->Count, Is.EqualTo (3), "Count B"); for (var i = 0; i < 3; i++) { - Assert.AreEqual (0, list->GetBuffer (i)->NumberChannels, $"NumberChannels B#{i}"); - Assert.AreEqual (0, list->GetBuffer (i)->DataByteSize, $"DataByteSize B#{i}"); - Assert.AreEqual ((nint) 0, list->GetBuffer (i)->Data, $"Data B#{i}"); + Assert.That (list->GetBuffer (i)->NumberChannels, Is.EqualTo (0), $"NumberChannels B#{i}"); + Assert.That (list->GetBuffer (i)->DataByteSize, Is.EqualTo (0), $"DataByteSize B#{i}"); + Assert.That (list->GetBuffer (i)->Data, Is.EqualTo ((nint) 0), $"Data B#{i}"); list->GetBuffer (i)->NumberChannels = (i + 1) * 10; list->GetBuffer (i)->DataByteSize = (i + 1) * 100; @@ -32,17 +32,17 @@ public unsafe void Usage () Assert.Throws (() => list->GetBuffer (3), "Item 3 B"); int* iptr = (int*) ptr; - Assert.AreEqual (10, iptr [2 + 0 * 4], "10"); // NumberChannels - Assert.AreEqual (100, iptr [2 + 0 * 4 + 1], "20"); // DataByteSize - Assert.AreEqual (20, iptr [2 + 1 * 4], "20"); // NumberChannels - Assert.AreEqual (200, iptr [2 + 1 * 4 + 1], "40"); // DataByteSize - Assert.AreEqual (30, iptr [2 + 2 * 4], "30"); // NumberChannels - Assert.AreEqual (300, iptr [2 + 2 * 4 + 1], "60"); // DataByteSize + Assert.That (iptr [2 + 0 * 4], Is.EqualTo (10), "10"); // NumberChannels + Assert.That (iptr [2 + 0 * 4 + 1], Is.EqualTo (100), "20"); // DataByteSize + Assert.That (iptr [2 + 1 * 4], Is.EqualTo (20), "20"); // NumberChannels + Assert.That (iptr [2 + 1 * 4 + 1], Is.EqualTo (200), "40"); // DataByteSize + Assert.That (iptr [2 + 2 * 4], Is.EqualTo (30), "30"); // NumberChannels + Assert.That (iptr [2 + 2 * 4 + 1], Is.EqualTo (300), "60"); // DataByteSize nint* nptr = (nint*) ptr; - Assert.AreEqual ((nint) 1000, nptr [1 + 0 * 2 + 1], "1000"); // Data - Assert.AreEqual ((nint) 2000, nptr [1 + 1 * 2 + 1], "2000"); // Data - Assert.AreEqual ((nint) 3000, nptr [1 + 2 * 2 + 1], "3000"); // Data + Assert.That (nptr [1 + 0 * 2 + 1], Is.EqualTo ((nint) 1000), "1000"); // Data + Assert.That (nptr [1 + 1 * 2 + 1], Is.EqualTo ((nint) 2000), "2000"); // Data + Assert.That (nptr [1 + 2 * 2 + 1], Is.EqualTo ((nint) 3000), "3000"); // Data } } } diff --git a/tests/monotouch-test/AudioToolbox/AudioChannelLayoutTest.cs b/tests/monotouch-test/AudioToolbox/AudioChannelLayoutTest.cs index 9cb98eb73c46..f73415abdbb8 100644 --- a/tests/monotouch-test/AudioToolbox/AudioChannelLayoutTest.cs +++ b/tests/monotouch-test/AudioToolbox/AudioChannelLayoutTest.cs @@ -18,20 +18,20 @@ public class AudioChannelLayoutTest { public void Validate () { var acl = AudioChannelLayout.FromAudioChannelLayoutTag (AudioChannelLayoutTag.AudioUnit_6_1); - Assert.AreEqual (AudioFormatError.None, AudioChannelLayout.Validate (acl)); + Assert.That (AudioChannelLayout.Validate (acl), Is.EqualTo (AudioFormatError.None)); } [Test] public void FromAudioChannelBitmap () { var bitmap = AudioChannelLayoutTag.AudioUnit_7_1_Front.ToAudioChannel (); - Assert.IsNotNull (AudioChannelLayout.FromAudioChannelBitmap (bitmap.Value)); + Assert.That (AudioChannelLayout.FromAudioChannelBitmap (bitmap.Value), Is.Not.Null); } [Test] public void FromAudioChannelLayoutTag () { - Assert.IsNotNull (AudioChannelLayout.FromAudioChannelLayoutTag (AudioChannelLayoutTag.AudioUnit_6_1)); + Assert.That (AudioChannelLayout.FromAudioChannelLayoutTag (AudioChannelLayoutTag.AudioUnit_6_1), Is.Not.Null); } [Test] @@ -54,13 +54,13 @@ public void GetChannelMap () var acl1 = AudioChannelLayout.FromAudioChannelLayoutTag (AudioChannelLayoutTag.AudioUnit_6_1); var acl2 = AudioChannelLayout.FromAudioChannelLayoutTag (AudioChannelLayoutTag.MPEG_7_1_B); - Assert.IsNotNull (AudioChannelLayout.GetChannelMap (acl1, acl2)); + Assert.That (AudioChannelLayout.GetChannelMap (acl1, acl2), Is.Not.Null); } [Test] public void GetTagsForNumberOfChannels () { - Assert.IsNotNull (AudioChannelLayout.GetTagsForNumberOfChannels (4)); + Assert.That (AudioChannelLayout.GetTagsForNumberOfChannels (4), Is.Not.Null); } [Test] @@ -69,7 +69,7 @@ public void GetMatrixMixMap () var acl1 = AudioChannelLayout.FromAudioChannelLayoutTag (AudioChannelLayoutTag.AudioUnit_6_1); var acl2 = AudioChannelLayout.FromAudioChannelLayoutTag (AudioChannelLayoutTag.MPEG_7_1_B); - Assert.IsNotNull (AudioChannelLayout.GetMatrixMixMap (acl1, acl2)); + Assert.That (AudioChannelLayout.GetMatrixMixMap (acl1, acl2), Is.Not.Null); } } } diff --git a/tests/monotouch-test/AudioToolbox/AudioComponentTest.cs b/tests/monotouch-test/AudioToolbox/AudioComponentTest.cs index 1653026b0562..617534f1d6ca 100644 --- a/tests/monotouch-test/AudioToolbox/AudioComponentTest.cs +++ b/tests/monotouch-test/AudioToolbox/AudioComponentTest.cs @@ -40,7 +40,7 @@ public void GetSetComponentList () if (component is null) continue; var l = component.ComponentList; - Assert.IsNull (l, "List is not null."); + Assert.That (l, Is.Null, "List is not null."); l = new AudioComponentInfo [] { componentInfo }; //monotouchtests does not have permissions to deal with the hwd. Assert.Throws (() => component.ComponentList = l); @@ -87,14 +87,14 @@ public void TestResourceUsageInfoIOKitUserClient () var resources = new ResourceUsageInfo (); resources.IOKitUserClient = new string [] { clientId }; var userClientList = resources.IOKitUserClient; - Assert.IsNotNull (userClientList); - Assert.AreEqual (1, userClientList.Length, "List does not have all client ids."); - Assert.AreEqual (clientId, userClientList [0], "Client ids are not the same."); + Assert.That (userClientList, Is.Not.Null); + Assert.That (userClientList.Length, Is.EqualTo (1), "List does not have all client ids."); + Assert.That (userClientList [0], Is.EqualTo (clientId), "Client ids are not the same."); // similar test but with null values. resources.IOKitUserClient = null; - Assert.IsNull (resources.IOKitUserClient, "Value was not set to null."); + Assert.That (resources.IOKitUserClient, Is.Null, "Value was not set to null."); } [Test] @@ -105,14 +105,14 @@ public void TestResourceUsageInfoMachLookUpGlobalName () var resources = new ResourceUsageInfo (); resources.MachLookUpGlobalName = new string [] { serviceName }; var serviceNames = resources.MachLookUpGlobalName; - Assert.NotNull (serviceNames, "Returned list is null"); - Assert.AreEqual (1, serviceNames.Length, "List does not have all service names."); - Assert.AreEqual (serviceName, serviceNames [0], "Service names are not equal."); + Assert.That (serviceNames, Is.Not.Null, "Returned list is null"); + Assert.That (serviceNames.Length, Is.EqualTo (1), "List does not have all service names."); + Assert.That (serviceNames [0], Is.EqualTo (serviceName), "Service names are not equal."); // similar test but with null values resources.MachLookUpGlobalName = null; - Assert.IsNull (resources.MachLookUpGlobalName, "Value was no set to null."); + Assert.That (resources.MachLookUpGlobalName, Is.Null, "Value was no set to null."); } [Test] @@ -132,10 +132,10 @@ public void TestConfigurationInfo () componentInfo.Version = 1; componentInfo.ResourceUsage = resources; using var component = AudioComponent.FindComponent (AudioTypeOutput.Generic); - Assert.IsNotNull (component); + Assert.That (component, Is.Not.Null); // assert the property and break var configInfo = component.GetConfigurationInfo (); - Assert.IsNotNull (configInfo); + Assert.That (configInfo, Is.Not.Null); } [Test] @@ -163,11 +163,10 @@ public void TestValidation () componentInfo.Version = 1; componentInfo.ResourceUsage = resources; using var component = AudioComponent.FindComponent (AudioTypeOutput.Generic); - Assert.IsNotNull (component); + Assert.That (component, Is.Not.Null); // validate and break var validation = component.Validate (null); - Assert.Contains (validation, - new List () { AudioComponentValidationResult.Unknown, AudioComponentValidationResult.Passed }, "validation"); + Assert.That (new List () { AudioComponentValidationResult.Unknown, AudioComponentValidationResult.Passed }, Does.Contain (validation), "validation"); tcs.SetResult (true); } catch (Exception e) { tcs.SetException (e); @@ -175,7 +174,7 @@ public void TestValidation () }); thread.IsBackground = true; thread.Start (); - Assert.IsTrue (tcs.Task.Wait (TimeSpan.FromSeconds (20)), "Timed out"); + Assert.That (tcs.Task.Wait (TimeSpan.FromSeconds (20)), Is.True, "Timed out"); } [Test] @@ -200,14 +199,14 @@ public void TestValidationAsync () componentInfo.Version = 1; componentInfo.ResourceUsage = resources; using var component = AudioComponent.FindComponent (AudioTypeOutput.Generic); - Assert.IsNotNull (component); + Assert.That (component, Is.Not.Null); var cbEvent = new AutoResetEvent (false); Action cb = (AudioComponentValidationResult _, NSDictionary? _) => { cbEvent.Set (); }; component.ValidateAsync (cb); - Assert.True (cbEvent.WaitOne (20000), "Cb was not called."); + Assert.That (cbEvent.WaitOne (20000), Is.True, "Cb was not called."); } } } diff --git a/tests/monotouch-test/AudioToolbox/AudioConverterTest.cs b/tests/monotouch-test/AudioToolbox/AudioConverterTest.cs index f87d66f4c716..4604a57193f8 100644 --- a/tests/monotouch-test/AudioToolbox/AudioConverterTest.cs +++ b/tests/monotouch-test/AudioToolbox/AudioConverterTest.cs @@ -46,7 +46,7 @@ public void Properties () // create the AudioConverter using AudioConverter? converter = AudioConverter.Create (srcFormat, dstFormat, out var createResult); - Assert.AreEqual (AudioConverterError.None, createResult, $"AudioConverterCreate ({srcFormat} -> {dstFormat}): {createResult}"); + Assert.That (createResult, Is.EqualTo (AudioConverterError.None), $"AudioConverterCreate ({srcFormat} -> {dstFormat}): {createResult}"); Assert.That (converter.PerformDownmix, Is.EqualTo (false), "PerformDownmix #0"); converter.PerformDownmix = true; @@ -81,11 +81,11 @@ public void Properties () public void Formats () { var decodeFormats = AudioConverter.DecodeFormats; - Assert.NotNull (decodeFormats, "Decode #1"); + Assert.That (decodeFormats, Is.Not.Null, "Decode #1"); Assert.That (decodeFormats.Length, Is.GreaterThan (10), "Decode Length #1"); var encodeFormats = AudioConverter.EncodeFormats; - Assert.NotNull (encodeFormats, "Encode #1"); + Assert.That (encodeFormats, Is.Not.Null, "Encode #1"); Assert.That (encodeFormats.Length, Is.GreaterThan (10), "Encode Length #1"); } @@ -200,14 +200,14 @@ void Convert (string sourceFilePath, string destinationFilePath, AudioFormatType Assert.Ignore ("Couldn't figure out the right properties to make the Apac encoder work:/"); // use AudioFormat API to fill out the rest of the description var afe = AudioStreamBasicDescription.GetFormatInfo (ref dstFormat); - Assert.AreEqual (AudioFormatError.None, afe, $"GetFormatInfo: {name}"); + Assert.That (afe, Is.EqualTo (AudioFormatError.None), $"GetFormatInfo: {name}"); } else if (outputFormatType == AudioFormatType.AppleLossless) { // compressed format - need to set at least format, sample rate and channel fields for kAudioFormatProperty_FormatInfo dstFormat.ChannelsPerFrame = srcFormat.ChannelsPerFrame; // for iLBC num channels must be 1 // use AudioFormat API to fill out the rest of the description var afe = AudioStreamBasicDescription.GetFormatInfo (ref dstFormat); - Assert.AreEqual (AudioFormatError.None, afe, $"GetFormatInfo: {name}"); + Assert.That (afe, Is.EqualTo (AudioFormatError.None), $"GetFormatInfo: {name}"); } else { throw new NotImplementedException (); } @@ -217,7 +217,7 @@ void Convert (string sourceFilePath, string destinationFilePath, AudioFormatType using AudioConverter? converter = options.HasValue ? AudioConverter.Create (srcFormat, dstFormat, options.Value, out ce) : AudioConverter.Create (srcFormat, dstFormat, out ce); - Assert.AreEqual (AudioConverterError.None, ce, $"AudioConverterCreate : {name}\n\tSource format: {srcFormat}\n\tDestination format: {dstFormat})"); + Assert.That (ce, Is.EqualTo (AudioConverterError.None), $"AudioConverterCreate : {name}\n\tSource format: {srcFormat}\n\tDestination format: {dstFormat})"); // set up source buffers and data proc info struct var afio = new AudioFileIO (32 * 1024); // 32Kb @@ -314,7 +314,7 @@ void Convert (string sourceFilePath, string destinationFilePath, AudioFormatType fe = converter.FillComplexBuffer (ref ioOutputDataPackets, fillBufList, outputPacketDescriptions); } // if interrupted in the process of the conversion call, we must handle the error appropriately - Assert.AreEqual (AudioConverterError.None, fe, $"FillComplexBuffer: {name}"); + Assert.That (fe, Is.EqualTo (AudioConverterError.None), $"FillComplexBuffer: {name}"); if (ioOutputDataPackets == 0) { // this is the EOF conditon @@ -325,7 +325,7 @@ void Convert (string sourceFilePath, string destinationFilePath, AudioFormatType var inNumBytes = fillBufList [0].DataByteSize; var we = destinationFile.WritePackets (false, inNumBytes, outputPacketDescriptions, outputFilePos, ref ioOutputDataPackets, outputBuffer); - Assert.AreEqual (AudioFileError.Success, we, $"WritePackets: {name}"); + Assert.That (we, Is.EqualTo (AudioFileError.Success), $"WritePackets: {name}"); // advance output file packet position outputFilePos += ioOutputDataPackets; diff --git a/tests/monotouch-test/AudioToolbox/AudioFileGlobalInfoTest.cs b/tests/monotouch-test/AudioToolbox/AudioFileGlobalInfoTest.cs index d4af2624c2aa..2e39b5a55955 100644 --- a/tests/monotouch-test/AudioToolbox/AudioFileGlobalInfoTest.cs +++ b/tests/monotouch-test/AudioToolbox/AudioFileGlobalInfoTest.cs @@ -22,10 +22,10 @@ public class AudioFileGlobalInfoTest { public void Properties () { Assert.Multiple (() => { - Assert.NotNull (AudioFileGlobalInfo.ReadableTypes, "ReadableTypes"); + Assert.That (AudioFileGlobalInfo.ReadableTypes, Is.Not.Null, "ReadableTypes"); Assert.That (AudioFileGlobalInfo.ReadableTypes?.Length, Is.GreaterThan (0), "ReadableTypes #"); - Assert.NotNull (AudioFileGlobalInfo.WritableTypes, "WritableTypes"); + Assert.That (AudioFileGlobalInfo.WritableTypes, Is.Not.Null, "WritableTypes"); Assert.That (AudioFileGlobalInfo.WritableTypes?.Length, Is.GreaterThan (0), "WritableTypes #"); var validFileTypeAndAudioFormatTypeCombinations = 0; @@ -37,18 +37,18 @@ public void Properties () validAudioFileTypes.Remove (AudioFileType.MP2); // doesn't work on macOS 11 foreach (var fileType in validAudioFileTypes) { - Assert.NotNull (AudioFileGlobalInfo.GetFileTypeName (fileType), $"GetFileTypeName: {fileType}"); + Assert.That (AudioFileGlobalInfo.GetFileTypeName (fileType), Is.Not.Null, $"GetFileTypeName: {fileType}"); - Assert.NotNull (AudioFileGlobalInfo.GetAvailableFormats (fileType), $"GetAvailableFormats: {fileType}"); + Assert.That (AudioFileGlobalInfo.GetAvailableFormats (fileType), Is.Not.Null, $"GetAvailableFormats: {fileType}"); Assert.That (AudioFileGlobalInfo.GetAvailableFormats (fileType)?.Length ?? -1, Is.GreaterThan (0), $"GetAvailableFormats #: {fileType}"); - Assert.NotNull (AudioFileGlobalInfo.GetExtensions (fileType), $"GetExtensions: {fileType}"); + Assert.That (AudioFileGlobalInfo.GetExtensions (fileType), Is.Not.Null, $"GetExtensions: {fileType}"); Assert.That (AudioFileGlobalInfo.GetExtensions (fileType)?.Length ?? -1, Is.GreaterThan (0), $"GetExtensions #: {fileType}"); - Assert.NotNull (AudioFileGlobalInfo.GetMIMETypes (fileType), $"GetMIMETypes: {fileType}"); + Assert.That (AudioFileGlobalInfo.GetMIMETypes (fileType), Is.Not.Null, $"GetMIMETypes: {fileType}"); Assert.That (AudioFileGlobalInfo.GetMIMETypes (fileType)?.Length ?? -1, Is.GreaterThan (0), $"GetMIMETypes #: {fileType}"); - Assert.NotNull (AudioFileGlobalInfo.GetUTIs (fileType), $"GetUTIs: {fileType}"); + Assert.That (AudioFileGlobalInfo.GetUTIs (fileType), Is.Not.Null, $"GetUTIs: {fileType}"); Assert.That (AudioFileGlobalInfo.GetUTIs (fileType)?.Length ?? -1, Is.GreaterThan (0), $"GetUTIs #: {fileType}"); foreach (var audioFormatType in Enum.GetValues ()) { @@ -61,7 +61,7 @@ public void Properties () } Assert.That (validFileTypeAndAudioFormatTypeCombinations, Is.GreaterThan (50), "Valid FileType And AudioFormatType Combinations"); - Assert.NotNull (AudioFileGlobalInfo.AllExtensions, "AllExtensions"); + Assert.That (AudioFileGlobalInfo.AllExtensions, Is.Not.Null, "AllExtensions"); Assert.That (AudioFileGlobalInfo.AllExtensions.Length, Is.GreaterThan (0), $"AllExtensions #"); }); } diff --git a/tests/monotouch-test/AudioToolbox/AudioFileTest.cs b/tests/monotouch-test/AudioToolbox/AudioFileTest.cs index 0dac320b1bcb..a1a52cb7a94b 100644 --- a/tests/monotouch-test/AudioToolbox/AudioFileTest.cs +++ b/tests/monotouch-test/AudioToolbox/AudioFileTest.cs @@ -49,72 +49,72 @@ public void ApiTest () try { var chunkType = AudioFileChunkType.CAFStreamDescription; Assert.Multiple (() => { - Assert.AreEqual (1, af.CountUserData (chunkType), "CountUserData #1"); - Assert.AreEqual (1, af.CountUserData ((uint) chunkType), "CountUserData #2"); + Assert.That (af.CountUserData (chunkType), Is.EqualTo (1), "CountUserData #1"); + Assert.That (af.CountUserData ((uint) chunkType), Is.EqualTo (1), "CountUserData #2"); - Assert.AreEqual (32, af.GetUserDataSize (chunkType, 0), "GetUserDataSize #1"); - Assert.AreEqual (32, af.GetUserDataSize ((uint) chunkType, 0), "GetUserDataSize #2"); + Assert.That (af.GetUserDataSize (chunkType, 0), Is.EqualTo (32), "GetUserDataSize #1"); + Assert.That (af.GetUserDataSize ((uint) chunkType, 0), Is.EqualTo (32), "GetUserDataSize #2"); - Assert.AreEqual (AudioFileError.Success, af.GetUserDataSize (chunkType, 0, out var userDataSize64), "GetUserDataSize64 #1"); - Assert.AreEqual (32, userDataSize64, "GetUserDataSize64 #2"); + Assert.That (af.GetUserDataSize (chunkType, 0, out var userDataSize64), Is.EqualTo (AudioFileError.Success), "GetUserDataSize64 #1"); + Assert.That (userDataSize64, Is.EqualTo (32), "GetUserDataSize64 #2"); - Assert.AreEqual (AudioFileError.Success, af.GetUserDataSize ((uint) chunkType, 0, out userDataSize64), "GetUserDataSize64 #3"); - Assert.AreEqual (32, userDataSize64, "GetUserDataSize64 #4"); + Assert.That (af.GetUserDataSize ((uint) chunkType, 0, out userDataSize64), Is.EqualTo (AudioFileError.Success), "GetUserDataSize64 #3"); + Assert.That (userDataSize64, Is.EqualTo (32), "GetUserDataSize64 #4"); size = memorySize; - Assert.AreEqual (AudioFileError.Success, af.GetUserData (chunkType, 0, ref size, memory), "GetUserData #1"); - Assert.AreEqual (32, size, "GetUserData #2"); - Assert.AreEqual (size, expectedData.Length, "GetUserData #3"); + Assert.That (af.GetUserData (chunkType, 0, ref size, memory), Is.EqualTo (AudioFileError.Success), "GetUserData #1"); + Assert.That (size, Is.EqualTo (32), "GetUserData #2"); + Assert.That (expectedData.Length, Is.EqualTo (size), "GetUserData #3"); for (var i = 0; i < expectedData.Length; i++) { - Assert.AreEqual (expectedData [i], Marshal.ReadByte (memory, i), $"GetUserData #4[{i}]"); + Assert.That (Marshal.ReadByte (memory, i), Is.EqualTo (expectedData [i]), $"GetUserData #4[{i}]"); Marshal.WriteByte (memory, i, 0); } size = memorySize; - Assert.AreEqual (0, af.GetUserData ((int) chunkType, 0, ref size, memory), "GetUserData/B #1"); - Assert.AreEqual (32, size, "GetUserData/B #2"); - Assert.AreEqual (size, expectedData.Length, "GetUserData/B #3"); + Assert.That (af.GetUserData ((int) chunkType, 0, ref size, memory), Is.EqualTo (0), "GetUserData/B #1"); + Assert.That (size, Is.EqualTo (32), "GetUserData/B #2"); + Assert.That (expectedData.Length, Is.EqualTo (size), "GetUserData/B #3"); for (var i = 0; i < expectedData.Length; i++) { - Assert.AreEqual (expectedData [i], Marshal.ReadByte (memory, i), $"GetUserData/B #4[{i}]"); + Assert.That (Marshal.ReadByte (memory, i), Is.EqualTo (expectedData [i]), $"GetUserData/B #4[{i}]"); Marshal.WriteByte (memory, i, 0); } size = memorySize; offset = 16; - Assert.AreEqual (AudioFileError.Success, af.GetUserData (chunkType, 0, offset, ref size, memory), "GetUserDataAtOffset/A #1"); - Assert.AreEqual (32 - offset, size, "GetUserDataAtOffset/A #2"); - Assert.AreEqual (size, expectedData.Length - offset, "GetUserDataAtOffset/A #3"); + Assert.That (af.GetUserData (chunkType, 0, offset, ref size, memory), Is.EqualTo (AudioFileError.Success), "GetUserDataAtOffset/A #1"); + Assert.That (size, Is.EqualTo (32 - offset), "GetUserDataAtOffset/A #2"); + Assert.That (expectedData.Length - offset, Is.EqualTo (size), "GetUserDataAtOffset/A #3"); for (var i = offset; i < expectedData.Length; i++) { - Assert.AreEqual (expectedData [i], Marshal.ReadByte (memory, i - offset), $"GetUserDataAtOffset/A #4[{i}]"); + Assert.That (Marshal.ReadByte (memory, i - offset), Is.EqualTo (expectedData [i]), $"GetUserDataAtOffset/A #4[{i}]"); Marshal.WriteByte (memory, i - offset, 0); } size = memorySize; offset = 12; - Assert.AreEqual (AudioFileError.Success, af.GetUserData ((uint) chunkType, 0, offset, ref size, memory), "GetUserDataAtOffset/B #1"); - Assert.AreEqual (32 - offset, size, "GetUserDataAtOffset/B #2"); - Assert.AreEqual (size, expectedData.Length - offset, "GetUserDataAtOffset/B #3"); + Assert.That (af.GetUserData ((uint) chunkType, 0, offset, ref size, memory), Is.EqualTo (AudioFileError.Success), "GetUserDataAtOffset/B #1"); + Assert.That (size, Is.EqualTo (32 - offset), "GetUserDataAtOffset/B #2"); + Assert.That (expectedData.Length - offset, Is.EqualTo (size), "GetUserDataAtOffset/B #3"); for (var i = offset; i < expectedData.Length; i++) { - Assert.AreEqual (expectedData [i], Marshal.ReadByte (memory, i - offset), $"GetUserDataAtOffset/B #4[{i}]"); + Assert.That (Marshal.ReadByte (memory, i - offset), Is.EqualTo (expectedData [i]), $"GetUserDataAtOffset/B #4[{i}]"); Marshal.WriteByte (memory, i - offset, 0); } size = memorySize; offset = 24; buffer = new byte [memorySize]; - Assert.AreEqual (AudioFileError.Success, af.GetUserData (chunkType, 0, offset, buffer, out size), "GetUserDataAtOffset/C #1"); - Assert.AreEqual (32 - offset, size, "GetUserDataAtOffset/C #2"); - Assert.AreEqual (size, expectedData.Length - offset, "GetUserDataAtOffset/C #3"); + Assert.That (af.GetUserData (chunkType, 0, offset, buffer, out size), Is.EqualTo (AudioFileError.Success), "GetUserDataAtOffset/C #1"); + Assert.That (size, Is.EqualTo (32 - offset), "GetUserDataAtOffset/C #2"); + Assert.That (expectedData.Length - offset, Is.EqualTo (size), "GetUserDataAtOffset/C #3"); for (var i = offset; i < expectedData.Length; i++) - Assert.AreEqual (expectedData [i], buffer [i - offset], $"GetUserDataAtOffset/C #4[{i}]"); + Assert.That (buffer [i - offset], Is.EqualTo (expectedData [i]), $"GetUserDataAtOffset/C #4[{i}]"); size = memorySize; offset = 8; - Assert.AreEqual (AudioFileError.Success, af.GetUserData ((uint) chunkType, 0, offset, buffer, out size), "GetUserDataAtOffset/D #1"); - Assert.AreEqual (32 - offset, size, "GetUserDataAtOffset/D #2"); - Assert.AreEqual (size, expectedData.Length - offset, "GetUserDataAtOffset/D #3"); + Assert.That (af.GetUserData ((uint) chunkType, 0, offset, buffer, out size), Is.EqualTo (AudioFileError.Success), "GetUserDataAtOffset/D #1"); + Assert.That (size, Is.EqualTo (32 - offset), "GetUserDataAtOffset/D #2"); + Assert.That (expectedData.Length - offset, Is.EqualTo (size), "GetUserDataAtOffset/D #3"); for (var i = offset; i < expectedData.Length; i++) - Assert.AreEqual (expectedData [i], buffer [i - offset], $"GetUserDataAtOffset/D #4[{i}]"); + Assert.That (buffer [i - offset], Is.EqualTo (expectedData [i]), $"GetUserDataAtOffset/D #4[{i}]"); }); } finally { Marshal.FreeHGlobal (memory); diff --git a/tests/monotouch-test/AudioToolbox/AudioFormatAvailabilityTest.cs b/tests/monotouch-test/AudioToolbox/AudioFormatAvailabilityTest.cs index 0bcc7d79bfa9..f5e195dc1a1d 100644 --- a/tests/monotouch-test/AudioToolbox/AudioFormatAvailabilityTest.cs +++ b/tests/monotouch-test/AudioToolbox/AudioFormatAvailabilityTest.cs @@ -17,13 +17,13 @@ public class AudioFormatAvailabilityTest { [Test] public void GetDecoders () { - Assert.IsNotNull (AudioFormatAvailability.GetDecoders (AudioFormatType.LinearPCM)); + Assert.That (AudioFormatAvailability.GetDecoders (AudioFormatType.LinearPCM), Is.Not.Null); } [Test] public void GetEncoders () { - Assert.IsNotNull (AudioFormatAvailability.GetEncoders (AudioFormatType.AC3)); + Assert.That (AudioFormatAvailability.GetEncoders (AudioFormatType.AC3), Is.Not.Null); } } } diff --git a/tests/monotouch-test/AudioToolbox/AudioFormatTest.cs b/tests/monotouch-test/AudioToolbox/AudioFormatTest.cs index 76a617005ff1..90981ace72ac 100644 --- a/tests/monotouch-test/AudioToolbox/AudioFormatTest.cs +++ b/tests/monotouch-test/AudioToolbox/AudioFormatTest.cs @@ -22,7 +22,7 @@ public void GetFirstPlayableFormat () var ofl = asbd.GetOutputFormatList (); - Assert.IsNotNull (AudioFormat.GetFirstPlayableFormat (ofl)); + Assert.That (AudioFormat.GetFirstPlayableFormat (ofl), Is.Not.Null); } } } diff --git a/tests/monotouch-test/AudioToolbox/AudioQueueBufferTest.cs b/tests/monotouch-test/AudioToolbox/AudioQueueBufferTest.cs index c6b001238ef0..ceb892c00fba 100644 --- a/tests/monotouch-test/AudioToolbox/AudioQueueBufferTest.cs +++ b/tests/monotouch-test/AudioToolbox/AudioQueueBufferTest.cs @@ -30,18 +30,18 @@ public unsafe void Properties () }; using var aq = new OutputAudioQueue (asbd); AudioQueueBuffer* buffer = null; - Assert.AreEqual (AudioQueueStatus.Ok, aq.AllocateBuffer (5000, 1, out buffer), "AllocateBuffer"); + Assert.That (aq.AllocateBuffer (5000, 1, out buffer), Is.EqualTo (AudioQueueStatus.Ok), "AllocateBuffer"); Assert.Multiple (() => { - Assert.AreEqual (5000, buffer->AudioDataBytesCapacity, "AudioDataBytesCapacity"); - Assert.AreNotEqual (IntPtr.Zero, buffer->AudioData, "AudioData"); - Assert.AreEqual (0, buffer->AudioDataByteSize, "AudioDataByteSize"); - Assert.AreEqual (IntPtr.Zero, buffer->UserData, "UserData"); - Assert.AreEqual (1, buffer->PacketDescriptionCapacity, "PacketDescriptionCapacity"); - Assert.AreNotEqual (IntPtr.Zero, buffer->IntPtrPacketDescriptions, "IntPtrPacketDescriptions"); - Assert.AreEqual (0, buffer->PacketDescriptionCount, "PacketDescriptionCount"); - Assert.AreEqual (0, buffer->PacketDescriptions.Length, "PacketDescriptions"); - Assert.AreEqual (5000, buffer->AsSpan ().Length, "AsSpan ().Length"); - Assert.AreEqual (0, buffer->AsSpanOfValidData ().Length, "AsSpanOfValidData ().Length"); + Assert.That (buffer->AudioDataBytesCapacity, Is.EqualTo (5000), "AudioDataBytesCapacity"); + Assert.That (buffer->AudioData, Is.Not.EqualTo (IntPtr.Zero), "AudioData"); + Assert.That (buffer->AudioDataByteSize, Is.EqualTo (0), "AudioDataByteSize"); + Assert.That (buffer->UserData, Is.EqualTo (IntPtr.Zero), "UserData"); + Assert.That (buffer->PacketDescriptionCapacity, Is.EqualTo (1), "PacketDescriptionCapacity"); + Assert.That (buffer->IntPtrPacketDescriptions, Is.Not.EqualTo (IntPtr.Zero), "IntPtrPacketDescriptions"); + Assert.That (buffer->PacketDescriptionCount, Is.EqualTo (0), "PacketDescriptionCount"); + Assert.That (buffer->PacketDescriptions.Length, Is.EqualTo (0), "PacketDescriptions"); + Assert.That (buffer->AsSpan ().Length, Is.EqualTo (5000), "AsSpan ().Length"); + Assert.That (buffer->AsSpanOfValidData ().Length, Is.EqualTo (0), "AsSpanOfValidData ().Length"); buffer->PacketDescriptions = new AudioStreamPacketDescription [] { new AudioStreamPacketDescription () { @@ -50,15 +50,15 @@ public unsafe void Properties () DataByteSize = 4, }, }; - Assert.AreEqual (1, buffer->PacketDescriptionCapacity, "PacketDescriptionCapacity#2"); - Assert.AreEqual (1, buffer->PacketDescriptionCount, "PacketDescriptionCount#2"); - Assert.AreEqual (2, buffer->PacketDescriptions [0].StartOffset, "PacketDescriptions[0].StartOffset"); - Assert.AreEqual (3, buffer->PacketDescriptions [0].VariableFramesInPacket, "PacketDescriptions[0].VariableFramesInPacket"); - Assert.AreEqual (4, buffer->PacketDescriptions [0].DataByteSize, "PacketDescriptions[0].DataByteSize"); + Assert.That (buffer->PacketDescriptionCapacity, Is.EqualTo (1), "PacketDescriptionCapacity#2"); + Assert.That (buffer->PacketDescriptionCount, Is.EqualTo (1), "PacketDescriptionCount#2"); + Assert.That (buffer->PacketDescriptions [0].StartOffset, Is.EqualTo (2), "PacketDescriptions[0].StartOffset"); + Assert.That (buffer->PacketDescriptions [0].VariableFramesInPacket, Is.EqualTo (3), "PacketDescriptions[0].VariableFramesInPacket"); + Assert.That (buffer->PacketDescriptions [0].DataByteSize, Is.EqualTo (4), "PacketDescriptions[0].DataByteSize"); buffer->PacketDescriptions = new AudioStreamPacketDescription [0]; - Assert.AreEqual (1, buffer->PacketDescriptionCapacity, "PacketDescriptionCapacity#3"); - Assert.AreEqual (0, buffer->PacketDescriptionCount, "PacketDescriptionCount#3"); + Assert.That (buffer->PacketDescriptionCapacity, Is.EqualTo (1), "PacketDescriptionCapacity#3"); + Assert.That (buffer->PacketDescriptionCount, Is.EqualTo (0), "PacketDescriptionCount#3"); Assert.Throws (() => buffer->PacketDescriptions = new AudioStreamPacketDescription [2], "too many packet descriptions"); @@ -66,21 +66,21 @@ public unsafe void Properties () fixed (byte* dataPtr = data) buffer->CopyToAudioData ((IntPtr) dataPtr, data.Length); Assert.That (buffer->AsSpanOfValidData ().ToArray (), Is.EqualTo (data), "CopyToAudioData 1"); - Assert.AreEqual (data.Length, buffer->AudioDataByteSize, "CopyToAudioData 1 - AudioDataByteSize"); + Assert.That (buffer->AudioDataByteSize, Is.EqualTo (data.Length), "CopyToAudioData 1 - AudioDataByteSize"); Assert.That (buffer->AsSpan ().Length, Is.EqualTo (5000), "CopyToAudioData 1 - AsSpan"); Assert.That (buffer->AsSpan ().Slice (0, data.Length).ToArray (), Is.EqualTo (buffer->AsSpanOfValidData ().ToArray ()), "CopyToAudioData 1 - Sliced AsSpan"); data = new byte [] { 2, 3, 4, 5, 6 }; buffer->CopyToAudioData (data); Assert.That (buffer->AsSpanOfValidData ().ToArray (), Is.EqualTo (data), "CopyToAudioData 2"); - Assert.AreEqual (data.Length, buffer->AudioDataByteSize, "CopyToAudioData 2 - AudioDataByteSize"); + Assert.That (buffer->AudioDataByteSize, Is.EqualTo (data.Length), "CopyToAudioData 2 - AudioDataByteSize"); Assert.That (buffer->AsSpan ().Length, Is.EqualTo (5000), "CopyToAudioData 2 - AsSpan"); Assert.That (buffer->AsSpan ().Slice (0, data.Length).ToArray (), Is.EqualTo (buffer->AsSpanOfValidData ().ToArray ()), "CopyToAudioData 2 - Sliced AsSpan"); data = new byte [5000]; buffer->CopyToAudioData (data); Assert.That (buffer->AsSpanOfValidData ().ToArray (), Is.EqualTo (data), "CopyToAudioData 3"); - Assert.AreEqual (data.Length, buffer->AudioDataByteSize, "CopyToAudioData 3 - AudioDataByteSize"); + Assert.That (buffer->AudioDataByteSize, Is.EqualTo (data.Length), "CopyToAudioData 3 - AudioDataByteSize"); Assert.That (buffer->AsSpan ().Length, Is.EqualTo (5000), "CopyToAudioData 3 - AsSpan"); Assert.That (buffer->AsSpan ().Slice (0, data.Length).ToArray (), Is.EqualTo (buffer->AsSpanOfValidData ().ToArray ()), "CopyToAudioData 3 - Sliced AsSpan"); @@ -93,14 +93,14 @@ public unsafe void Properties () data = new byte [0]; buffer->CopyToAudioData (IntPtr.Zero, 0); Assert.That (buffer->AsSpanOfValidData ().ToArray (), Is.EqualTo (data), "CopyToAudioData 5"); - Assert.AreEqual (data.Length, buffer->AudioDataByteSize, "CopyToAudioData 5 - AudioDataByteSize"); + Assert.That (buffer->AudioDataByteSize, Is.EqualTo (data.Length), "CopyToAudioData 5 - AudioDataByteSize"); Assert.That (buffer->AsSpan ().Length, Is.EqualTo (5000), "CopyToAudioData 5 - AsSpan"); Assert.That (buffer->AsSpan ().Slice (0, data.Length).ToArray (), Is.EqualTo (buffer->AsSpanOfValidData ().ToArray ()), "CopyToAudioData 5 - Sliced AsSpan"); data = new byte [0]; buffer->CopyToAudioData (data); Assert.That (buffer->AsSpanOfValidData ().ToArray (), Is.EqualTo (data), "CopyToAudioData 6"); - Assert.AreEqual (data.Length, buffer->AudioDataByteSize, "CopyToAudioData 6 - AudioDataByteSize"); + Assert.That (buffer->AudioDataByteSize, Is.EqualTo (data.Length), "CopyToAudioData 6 - AudioDataByteSize"); Assert.That (buffer->AsSpan ().Length, Is.EqualTo (5000), "CopyToAudioData 6 - AsSpan"); Assert.That (buffer->AsSpan ().Slice (0, data.Length).ToArray (), Is.EqualTo (buffer->AsSpanOfValidData ().ToArray ()), "CopyToAudioData 6 - Sliced AsSpan"); diff --git a/tests/monotouch-test/AudioToolbox/AudioQueueTest.cs b/tests/monotouch-test/AudioToolbox/AudioQueueTest.cs index ba5531637927..a5249b42ea58 100644 --- a/tests/monotouch-test/AudioToolbox/AudioQueueTest.cs +++ b/tests/monotouch-test/AudioToolbox/AudioQueueTest.cs @@ -41,9 +41,9 @@ public void ChannelAssignments () for (int i = 0; i < aq.AudioStreamDescription.ChannelsPerFrame; i++) { assignments.Add (new AudioQueueChannelAssignment (id, (uint) i)); } - Assert.AreEqual (AudioQueueStatus.Ok, aq.SetChannelAssignments (assignments.ToArray ())); + Assert.That (aq.SetChannelAssignments (assignments.ToArray ()), Is.EqualTo (AudioQueueStatus.Ok)); } else { - Assert.Ignore ("No outputs in the current route ({0})", route.Description); + Assert.Ignore ($"No outputs in the current route ({route.Description})"); } } @@ -63,13 +63,13 @@ public void ProcessingTap () // called = true; return 33; }, AudioQueueProcessingTapFlags.PreEffects, out ret)) { - Assert.AreEqual (AudioQueueStatus.Ok, ret, "#1"); + Assert.That (ret, Is.EqualTo (AudioQueueStatus.Ok), "#1"); unsafe { AudioQueueBuffer* buffer; - Assert.AreEqual (AudioQueueStatus.Ok, aq.AllocateBuffer (5000, out buffer), "#2"); - Assert.AreEqual (AudioQueueStatus.Ok, aq.EnqueueBuffer (buffer), "#3"); - //Assert.AreEqual (AudioQueueStatus.Ok, aq.Start (), "#4"); + Assert.That (aq.AllocateBuffer (5000, out buffer), Is.EqualTo (AudioQueueStatus.Ok), "#2"); + Assert.That (aq.EnqueueBuffer (buffer), Is.EqualTo (AudioQueueStatus.Ok), "#3"); + //Assert.That (aq.Start (), Is.EqualTo (AudioQueueStatus.Ok), "#4"); } } @@ -88,20 +88,20 @@ public unsafe void AllocateBuffer_1 () { var asbd = AudioStreamBasicDescription.CreateLinearPCM (); using var aq = new InputAudioQueue (asbd); - Assert.AreEqual (AudioQueueStatus.Ok, aq.AllocateBuffer (5000, out AudioQueueBuffer* buffer), "AllocateBuffer"); + Assert.That (aq.AllocateBuffer (5000, out AudioQueueBuffer* buffer), Is.EqualTo (AudioQueueStatus.Ok), "AllocateBuffer"); Assert.Multiple (() => { - Assert.AreEqual (5000, buffer->AudioDataBytesCapacity, "AudioDataBytesCapacity"); - Assert.AreNotEqual (IntPtr.Zero, buffer->AudioData, "AudioData"); - Assert.AreEqual (0, buffer->AudioDataByteSize, "AudioDataByteSize"); - Assert.AreEqual (IntPtr.Zero, buffer->UserData, "UserData"); - Assert.AreEqual (0, buffer->PacketDescriptionCapacity, "PacketDescriptionCapacity"); - Assert.AreEqual (IntPtr.Zero, buffer->IntPtrPacketDescriptions, "IntPtrPacketDescriptions"); - Assert.AreEqual (0, buffer->PacketDescriptionCount, "PacketDescriptionCount"); - Assert.AreEqual (0, buffer->PacketDescriptions.Length, "PacketDescriptions"); - Assert.AreEqual (5000, buffer->AsSpan ().Length, "AsSpan ().Length"); - Assert.AreEqual (0, buffer->AsSpanOfValidData ().Length, "AsSpanOfValidData ().Length"); + Assert.That (buffer->AudioDataBytesCapacity, Is.EqualTo (5000), "AudioDataBytesCapacity"); + Assert.That (buffer->AudioData, Is.Not.EqualTo (IntPtr.Zero), "AudioData"); + Assert.That (buffer->AudioDataByteSize, Is.EqualTo (0), "AudioDataByteSize"); + Assert.That (buffer->UserData, Is.EqualTo (IntPtr.Zero), "UserData"); + Assert.That (buffer->PacketDescriptionCapacity, Is.EqualTo (0), "PacketDescriptionCapacity"); + Assert.That (buffer->IntPtrPacketDescriptions, Is.EqualTo (IntPtr.Zero), "IntPtrPacketDescriptions"); + Assert.That (buffer->PacketDescriptionCount, Is.EqualTo (0), "PacketDescriptionCount"); + Assert.That (buffer->PacketDescriptions.Length, Is.EqualTo (0), "PacketDescriptions"); + Assert.That (buffer->AsSpan ().Length, Is.EqualTo (5000), "AsSpan ().Length"); + Assert.That (buffer->AsSpanOfValidData ().Length, Is.EqualTo (0), "AsSpanOfValidData ().Length"); }); - Assert.AreEqual (AudioQueueStatus.Ok, aq.FreeBuffer (buffer), "FreeBuffer"); + Assert.That (aq.FreeBuffer (buffer), Is.EqualTo (AudioQueueStatus.Ok), "FreeBuffer"); } [Test] @@ -119,18 +119,18 @@ public unsafe void AllocateBuffer_2 () FramesPerPacket = 1024, }; using var aq = new OutputAudioQueue (asbd); - Assert.AreEqual (AudioQueueStatus.Ok, aq.AllocateBuffer (5000, 1, out var buffer), "AllocateBuffer"); + Assert.That (aq.AllocateBuffer (5000, 1, out var buffer), Is.EqualTo (AudioQueueStatus.Ok), "AllocateBuffer"); Assert.Multiple (() => { - Assert.AreEqual (5000, buffer->AudioDataBytesCapacity, "AudioDataBytesCapacity"); - Assert.AreNotEqual (IntPtr.Zero, buffer->AudioData, "AudioData"); - Assert.AreEqual (0, buffer->AudioDataByteSize, "AudioDataByteSize"); - Assert.AreEqual (IntPtr.Zero, buffer->UserData, "UserData"); - Assert.AreEqual (1, buffer->PacketDescriptionCapacity, "PacketDescriptionCapacity"); - Assert.AreNotEqual (IntPtr.Zero, buffer->IntPtrPacketDescriptions, "IntPtrPacketDescriptions"); - Assert.AreEqual (0, buffer->PacketDescriptionCount, "PacketDescriptionCount"); - Assert.AreEqual (0, buffer->PacketDescriptions.Length, "PacketDescriptions"); - Assert.AreEqual (5000, buffer->AsSpan ().Length, "AsSpan ().Length"); - Assert.AreEqual (0, buffer->AsSpanOfValidData ().Length, "AsSpanOfValidData ().Length"); + Assert.That (buffer->AudioDataBytesCapacity, Is.EqualTo (5000), "AudioDataBytesCapacity"); + Assert.That (buffer->AudioData, Is.Not.EqualTo (IntPtr.Zero), "AudioData"); + Assert.That (buffer->AudioDataByteSize, Is.EqualTo (0), "AudioDataByteSize"); + Assert.That (buffer->UserData, Is.EqualTo (IntPtr.Zero), "UserData"); + Assert.That (buffer->PacketDescriptionCapacity, Is.EqualTo (1), "PacketDescriptionCapacity"); + Assert.That (buffer->IntPtrPacketDescriptions, Is.Not.EqualTo (IntPtr.Zero), "IntPtrPacketDescriptions"); + Assert.That (buffer->PacketDescriptionCount, Is.EqualTo (0), "PacketDescriptionCount"); + Assert.That (buffer->PacketDescriptions.Length, Is.EqualTo (0), "PacketDescriptions"); + Assert.That (buffer->AsSpan ().Length, Is.EqualTo (5000), "AsSpan ().Length"); + Assert.That (buffer->AsSpanOfValidData ().Length, Is.EqualTo (0), "AsSpanOfValidData ().Length"); }); } } diff --git a/tests/monotouch-test/AudioToolbox/AudioStreamBasicDescriptionTest.cs b/tests/monotouch-test/AudioToolbox/AudioStreamBasicDescriptionTest.cs index 5dcb29710f7f..ae99b691544e 100644 --- a/tests/monotouch-test/AudioToolbox/AudioStreamBasicDescriptionTest.cs +++ b/tests/monotouch-test/AudioToolbox/AudioStreamBasicDescriptionTest.cs @@ -18,26 +18,26 @@ public class AudioStreamBasicDescriptionTest { public void CreateLinearPCM () { var pcm = AudioStreamBasicDescription.CreateLinearPCM (); - Assert.IsNotNull (pcm.FormatName); - Assert.IsFalse (pcm.IsVariableBitrate); + Assert.That (pcm.FormatName, Is.Not.Null); + Assert.That (pcm.IsVariableBitrate, Is.False); } [Test] public void VBR () { var mp3 = new AudioStreamBasicDescription (AudioFormatType.MPEGLayer3); - Assert.IsTrue (mp3.IsVariableBitrate); + Assert.That (mp3.IsVariableBitrate, Is.True); } [Test] public void GetFormatInfo () { var asbd = new AudioStreamBasicDescription (AudioFormatType.MPEG4AAC); - Assert.AreEqual (AudioFormatError.None, AudioStreamBasicDescription.GetFormatInfo (ref asbd)); + Assert.That (AudioStreamBasicDescription.GetFormatInfo (ref asbd), Is.EqualTo (AudioFormatError.None)); - Assert.IsNotNull (AudioStreamBasicDescription.GetAvailableEncodeChannelLayoutTags (asbd)); - Assert.IsNotNull (AudioStreamBasicDescription.GetAvailableEncodeNumberChannels (asbd)); - Assert.IsNotNull (asbd.GetOutputFormatList ()); + Assert.That (AudioStreamBasicDescription.GetAvailableEncodeChannelLayoutTags (asbd), Is.Not.Null); + Assert.That (AudioStreamBasicDescription.GetAvailableEncodeNumberChannels (asbd), Is.Not.Null); + Assert.That (asbd.GetOutputFormatList (), Is.Not.Null); } } } diff --git a/tests/monotouch-test/AudioToolbox/AudioUnitTest.cs b/tests/monotouch-test/AudioToolbox/AudioUnitTest.cs index 5b6d362b0d31..598c96e22c2a 100644 --- a/tests/monotouch-test/AudioToolbox/AudioUnitTest.cs +++ b/tests/monotouch-test/AudioToolbox/AudioUnitTest.cs @@ -32,13 +32,13 @@ public void Callbacks () var rv = audioUnit.SetInputCallback (InputCallback, AudioUnitScopeType.Input, 1); if (rv == AudioUnitStatus.CannotDoInCurrentContext) Assert.Ignore ("Can't set input callback"); // No microphone? In a VM? This seems to happen often on bots. - Assert.AreEqual (AudioUnitStatus.OK, rv, "SetInputCallback"); - Assert.AreEqual (AudioUnitStatus.OK, audioUnit.Initialize (), "Initialize"); + Assert.That (rv, Is.EqualTo (AudioUnitStatus.OK), "SetInputCallback"); + Assert.That (audioUnit.Initialize (), Is.EqualTo (AudioUnitStatus.OK), "Initialize"); try { - Assert.AreEqual (AudioUnitStatus.OK, audioUnit.Start (), "Start"); - Assert.IsTrue (inputCallbackEvent.WaitOne (TimeSpan.FromSeconds (1)), "No input callback for 1 second"); + Assert.That (audioUnit.Start (), Is.EqualTo (AudioUnitStatus.OK), "Start"); + Assert.That (inputCallbackEvent.WaitOne (TimeSpan.FromSeconds (1)), Is.True, "No input callback for 1 second"); } finally { - Assert.AreEqual (AudioUnitStatus.OK, audioUnit.Stop (), "Stop"); + Assert.That (audioUnit.Stop (), Is.EqualTo (AudioUnitStatus.OK), "Stop"); } } diff --git a/tests/monotouch-test/AudioToolbox/MusicPlayer.cs b/tests/monotouch-test/AudioToolbox/MusicPlayer.cs index f9639a2fe6aa..7970fa47be19 100644 --- a/tests/monotouch-test/AudioToolbox/MusicPlayer.cs +++ b/tests/monotouch-test/AudioToolbox/MusicPlayer.cs @@ -19,14 +19,14 @@ public class MusicPlayerTest { public void Defaults () { using (var player = new MusicPlayer ()) { - Assert.IsFalse (player.IsPlaying, "IsPlaying"); - Assert.AreEqual (0, player.Time, "Time"); - Assert.AreEqual (1, player.PlayRateScalar, "PlayRateScalar"); - Assert.AreEqual (MusicPlayerStatus.InvalidPlayerState, player.GetHostTimeForBeats (0, out var hosttime), "GetHostTimeForBeats"); - Assert.AreEqual (0, hosttime, "GetHostTimeForBeats - rv"); - Assert.AreEqual (MusicPlayerStatus.InvalidPlayerState, player.GetBeatsForHostTime (0, out var beats), "GetBeatsForHostTime"); - Assert.AreEqual (0, beats, "GetBeatsForHostTime - rv"); - Assert.IsNull (player.MusicSequence, "MusicSequence"); + Assert.That (player.IsPlaying, Is.False, "IsPlaying"); + Assert.That (player.Time, Is.EqualTo (0), "Time"); + Assert.That (player.PlayRateScalar, Is.EqualTo (1), "PlayRateScalar"); + Assert.That (player.GetHostTimeForBeats (0, out var hosttime), Is.EqualTo (MusicPlayerStatus.InvalidPlayerState), "GetHostTimeForBeats"); + Assert.That (hosttime, Is.EqualTo (0), "GetHostTimeForBeats - rv"); + Assert.That (player.GetBeatsForHostTime (0, out var beats), Is.EqualTo (MusicPlayerStatus.InvalidPlayerState), "GetBeatsForHostTime"); + Assert.That (beats, Is.EqualTo (0), "GetBeatsForHostTime - rv"); + Assert.That (player.MusicSequence, Is.Null, "MusicSequence"); } } @@ -35,13 +35,13 @@ public void MusicSequenceTest () { using (var player = new MusicPlayer ()) { using (var ms = new MusicSequence ()) { - Assert.IsNull (player.MusicSequence, "MusicSequence A"); + Assert.That (player.MusicSequence, Is.Null, "MusicSequence A"); player.MusicSequence = null; - Assert.IsNull (player.MusicSequence, "MusicSequence B"); + Assert.That (player.MusicSequence, Is.Null, "MusicSequence B"); player.MusicSequence = ms; - Assert.AreSame (ms, player.MusicSequence, "MusicSequence C"); + Assert.That (player.MusicSequence, Is.SameAs (ms), "MusicSequence C"); player.MusicSequence = null; - Assert.IsNull (player.MusicSequence, "MusicSequence D"); + Assert.That (player.MusicSequence, Is.Null, "MusicSequence D"); } } } @@ -50,9 +50,9 @@ public void MusicSequenceTest () public void PlayRateScalarTest () { using (var player = new MusicPlayer ()) { - Assert.AreEqual (1, player.PlayRateScalar, "PlayRateScalar A"); + Assert.That (player.PlayRateScalar, Is.EqualTo (1), "PlayRateScalar A"); player.PlayRateScalar = 2; - Assert.AreEqual (2, player.PlayRateScalar, "PlayRateScalar B"); + Assert.That (player.PlayRateScalar, Is.EqualTo (2), "PlayRateScalar B"); } } @@ -60,14 +60,14 @@ public void PlayRateScalarTest () public void TimeTest () { using (var player = new MusicPlayer ()) { - Assert.AreEqual (0, player.Time, "Time A"); + Assert.That (player.Time, Is.EqualTo (0), "Time A"); player.Time = 1; - Assert.AreEqual (0, player.Time, "Time B"); - Assert.AreEqual (MusicPlayerStatus.Success, player.GetTime (out var time), "GetTime A"); - Assert.AreEqual (0, time, "GetTime B"); - Assert.AreEqual (MusicPlayerStatus.Success, player.SetTime (1), "SetTime A"); - Assert.AreEqual (MusicPlayerStatus.Success, player.GetTime (out time), "GetTime C"); - Assert.AreEqual (0, time, "GetTime D"); + Assert.That (player.Time, Is.EqualTo (0), "Time B"); + Assert.That (player.GetTime (out var time), Is.EqualTo (MusicPlayerStatus.Success), "GetTime A"); + Assert.That (time, Is.EqualTo (0), "GetTime B"); + Assert.That (player.SetTime (1), Is.EqualTo (MusicPlayerStatus.Success), "SetTime A"); + Assert.That (player.GetTime (out time), Is.EqualTo (MusicPlayerStatus.Success), "GetTime C"); + Assert.That (time, Is.EqualTo (0), "GetTime D"); } } @@ -75,19 +75,19 @@ public void TimeTest () public void CreateTest () { using var player = MusicPlayer.Create (out var status); - Assert.NotNull (player, "Got a player"); - Assert.AreEqual (MusicPlayerStatus.Success, status, "Status"); + Assert.That (player, Is.Not.Null, "Got a player"); + Assert.That (status, Is.EqualTo (MusicPlayerStatus.Success), "Status"); } [Test] public void StartStopPreroll () { using var player = MusicPlayer.Create (out var status); - Assert.NotNull (player, "Got a player"); - Assert.AreEqual (MusicPlayerStatus.Success, status, "Status"); - Assert.AreEqual (MusicPlayerStatus.NoSequence, player.Preroll (), "Preroll"); - Assert.AreEqual (MusicPlayerStatus.NoSequence, player.Start (), "Start"); - Assert.AreEqual (MusicPlayerStatus.NoSequence, player.Stop (), "Stop"); + Assert.That (player, Is.Not.Null, "Got a player"); + Assert.That (status, Is.EqualTo (MusicPlayerStatus.Success), "Status"); + Assert.That (player.Preroll (), Is.EqualTo (MusicPlayerStatus.NoSequence), "Preroll"); + Assert.That (player.Start (), Is.EqualTo (MusicPlayerStatus.NoSequence), "Start"); + Assert.That (player.Stop (), Is.EqualTo (MusicPlayerStatus.NoSequence), "Stop"); } } } diff --git a/tests/monotouch-test/AudioToolbox/MusicSequenceTest.cs b/tests/monotouch-test/AudioToolbox/MusicSequenceTest.cs index 9776a53d2f44..f5e70da480f2 100644 --- a/tests/monotouch-test/AudioToolbox/MusicSequenceTest.cs +++ b/tests/monotouch-test/AudioToolbox/MusicSequenceTest.cs @@ -21,7 +21,7 @@ public class MusicSequenceTest { public void Defaults () { using (var ms = new MusicSequence ()) { - Assert.NotNull (ms.AUGraph, "AUGraph"); + Assert.That (ms.AUGraph, Is.Not.Null, "AUGraph"); Assert.That (ms.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); Assert.That (ms.SequenceType, Is.EqualTo (MusicSequenceType.Beats), "SequenceType"); Assert.That (ms.TrackCount, Is.EqualTo (0), "TrackCount"); diff --git a/tests/monotouch-test/AudioToolbox/MusicTrackTest.cs b/tests/monotouch-test/AudioToolbox/MusicTrackTest.cs index b9cae1aa4ea2..3b1229f9c6be 100644 --- a/tests/monotouch-test/AudioToolbox/MusicTrackTest.cs +++ b/tests/monotouch-test/AudioToolbox/MusicTrackTest.cs @@ -41,24 +41,24 @@ public void Defaults () Assert.That (track.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); Assert.That (track.Sequence, Is.Not.Null, "Sequence"); - Assert.IsFalse (track.MuteStatus, "MuteStatus"); + Assert.That (track.MuteStatus, Is.False, "MuteStatus"); track.MuteStatus = true; - Assert.IsTrue (track.MuteStatus, "MuteStatus B"); + Assert.That (track.MuteStatus, Is.True, "MuteStatus B"); track.MuteStatus = false; - Assert.IsFalse (track.MuteStatus, "MuteStatus C"); + Assert.That (track.MuteStatus, Is.False, "MuteStatus C"); - Assert.IsFalse (track.SoloStatus, "SoloStatus"); + Assert.That (track.SoloStatus, Is.False, "SoloStatus"); track.SoloStatus = true; - Assert.IsTrue (track.SoloStatus, "SoloStatus B"); + Assert.That (track.SoloStatus, Is.True, "SoloStatus B"); track.SoloStatus = false; - Assert.IsFalse (track.SoloStatus, "SoloStatus C"); + Assert.That (track.SoloStatus, Is.False, "SoloStatus C"); - Assert.AreEqual (0.0f, track.TrackLength, "TrackLength"); + Assert.That (track.TrackLength, Is.EqualTo (0.0f), "TrackLength"); var originalTrackLength = track.TrackLength; track.TrackLength = 1.32f; - Assert.AreEqual (1.32f, track.TrackLength, "TrackLength B"); + Assert.That (track.TrackLength, Is.EqualTo (1.32f), "TrackLength B"); track.TrackLength = originalTrackLength; - Assert.AreEqual (0.0f, track.TrackLength, "TrackLength C"); + Assert.That (track.TrackLength, Is.EqualTo (0.0f), "TrackLength C"); } [Test] @@ -72,7 +72,7 @@ public void MidiEndPointProperty () track.SetDestMidiEndpoint (endpoint); MidiEndpoint outEnpoint; var status = track.GetDestMidiEndpoint (out outEnpoint); - Assert.AreEqual (endpoint.Handle, outEnpoint.Handle, "Track endpoint."); + Assert.That (outEnpoint.Handle, Is.EqualTo (endpoint.Handle), "Track endpoint."); } } } diff --git a/tests/monotouch-test/AudioToolbox/SoundBankTest.cs b/tests/monotouch-test/AudioToolbox/SoundBankTest.cs index 6f5075059bf6..e9d53b0ca401 100644 --- a/tests/monotouch-test/AudioToolbox/SoundBankTest.cs +++ b/tests/monotouch-test/AudioToolbox/SoundBankTest.cs @@ -26,7 +26,7 @@ public void GetName () Assert.Throws (delegate { SoundBank.GetName (null); }, "null"); using (NSUrl url = new NSUrl ("http://www.xamarin.com")) { - Assert.Null (SoundBank.GetName (url), "Not a SoundBank"); + Assert.That (SoundBank.GetName (url), Is.Null, "Not a SoundBank"); } } @@ -52,7 +52,7 @@ public void GetInstrumentInfo () Assert.Throws (delegate { SoundBank.GetInstrumentInfo (null); }, "null"); using (NSUrl url = new NSUrl ("http://www.xamarin.com")) { - Assert.Null (SoundBank.GetInstrumentInfo (url), "Not a SoundBank"); + Assert.That (SoundBank.GetInstrumentInfo (url), Is.Null, "Not a SoundBank"); } } diff --git a/tests/monotouch-test/AudioToolbox/SystemSoundTest.cs b/tests/monotouch-test/AudioToolbox/SystemSoundTest.cs index 946efd148956..b923dac81b75 100644 --- a/tests/monotouch-test/AudioToolbox/SystemSoundTest.cs +++ b/tests/monotouch-test/AudioToolbox/SystemSoundTest.cs @@ -29,13 +29,13 @@ public void FromFile () var completed = new TaskCompletionSource (); const int timeout = 10; - Assert.AreEqual (AudioServicesError.None, ss.AddSystemSoundCompletion (delegate + Assert.That (ss.AddSystemSoundCompletion (delegate { completed.SetResult (true); - })); + }), Is.EqualTo (AudioServicesError.None)); ss.PlaySystemSound (); - Assert.IsTrue (TestRuntime.RunAsync (TimeSpan.FromSeconds (timeout), completed.Task), "PlaySystemSound"); + Assert.That (TestRuntime.RunAsync (TimeSpan.FromSeconds (timeout), completed.Task), Is.True, "PlaySystemSound"); } } @@ -74,7 +74,7 @@ public void TestCallbackPlaySystem () const int timeout = 10; ss.PlaySystemSound (() => { completed.SetResult (true); }); - Assert.IsTrue (TestRuntime.RunAsync (TimeSpan.FromSeconds (timeout), completed.Task), "TestCallbackPlaySystem"); + Assert.That (TestRuntime.RunAsync (TimeSpan.FromSeconds (timeout), completed.Task), Is.True, "TestCallbackPlaySystem"); } } @@ -92,7 +92,7 @@ public void TestCallbackPlayAlert () const int timeout = 10; ss.PlayAlertSound (() => { completed.SetResult (true); }); - Assert.IsTrue (TestRuntime.RunAsync (TimeSpan.FromSeconds (timeout), completed.Task), "TestCallbackPlayAlert"); + Assert.That (TestRuntime.RunAsync (TimeSpan.FromSeconds (timeout), completed.Task), Is.True, "TestCallbackPlayAlert"); } } diff --git a/tests/monotouch-test/AudioUnit/AUAudioUnitFactoryTest.cs b/tests/monotouch-test/AudioUnit/AUAudioUnitFactoryTest.cs index 1fe4293ae359..ce98f690e99c 100644 --- a/tests/monotouch-test/AudioUnit/AUAudioUnitFactoryTest.cs +++ b/tests/monotouch-test/AudioUnit/AUAudioUnitFactoryTest.cs @@ -32,9 +32,8 @@ public void CreateAudioUnit () using (var auFactory = new CustomAudioUnitFactory ()) { NSError error; using (var audioUnit = auFactory.CreateAudioUnit (desc, out error)) { - Assert.True (audioUnit is not null, "CustomAudioUnitFactory returned null object for valid component description"); - Assert.True (audioUnit.ManufacturerName == expectedManufacturer, - $"CustomAudioUnitFactory returned audio unit with incorrect manufacturer. Expected - {expectedManufacturer}, actual - {audioUnit.ManufacturerName}"); + Assert.That (audioUnit is not null, Is.True, "CustomAudioUnitFactory returned null object for valid component description"); + Assert.That (audioUnit.ManufacturerName == expectedManufacturer, Is.True, $"CustomAudioUnitFactory returned audio unit with incorrect manufacturer. Expected - {expectedManufacturer}, actual - {audioUnit.ManufacturerName}"); } } } diff --git a/tests/monotouch-test/AudioUnit/AUGraphTest.cs b/tests/monotouch-test/AudioUnit/AUGraphTest.cs index 73aa779ae8b0..74dfb29bba34 100644 --- a/tests/monotouch-test/AudioUnit/AUGraphTest.cs +++ b/tests/monotouch-test/AudioUnit/AUGraphTest.cs @@ -19,24 +19,24 @@ public void BasicOperations () { using (var aug = new AUGraph ()) { aug.Open (); - Assert.IsTrue (aug.IsOpen, "#0"); - Assert.IsFalse (aug.IsInitialized, "#0a"); - Assert.IsFalse (aug.IsRunning, "#0b"); + Assert.That (aug.IsOpen, Is.True, "#0"); + Assert.That (aug.IsInitialized, Is.False, "#0a"); + Assert.That (aug.IsRunning, Is.False, "#0b"); var node = aug.AddNode (AudioComponentDescription.CreateOutput (AudioTypeOutput.Generic)); int count; - Assert.AreEqual (AUGraphError.OK, aug.GetNodeCount (out count), "#1"); - Assert.AreEqual (1, count, "#2"); + Assert.That (aug.GetNodeCount (out count), Is.EqualTo (AUGraphError.OK), "#1"); + Assert.That (count, Is.EqualTo (1), "#2"); var info = aug.GetNodeInfo (node); - Assert.IsNotNull (info, "#3"); + Assert.That (info, Is.Not.Null, "#3"); int node2; - Assert.AreEqual (AUGraphError.OK, aug.GetNode (0, out node2), "#4"); - Assert.AreEqual (1, node2, "#4a"); + Assert.That (aug.GetNode (0, out node2), Is.EqualTo (AUGraphError.OK), "#4"); + Assert.That (node2, Is.EqualTo (1), "#4a"); float max_load; - Assert.AreEqual (AUGraphError.OK, aug.GetMaxCPULoad (out max_load)); + Assert.That (aug.GetMaxCPULoad (out max_load), Is.EqualTo (AUGraphError.OK)); } } @@ -49,16 +49,16 @@ public void Connections () var node_1 = aug.AddNode (AudioComponentDescription.CreateGenerator (AudioTypeGenerator.AudioFilePlayer)); var node_2 = aug.AddNode (AudioComponentDescription.CreateOutput (AudioTypeOutput.Generic)); - Assert.AreEqual (AUGraphError.OK, aug.ConnnectNodeInput (node_1, 0, node_2, 0), "#1"); + Assert.That (aug.ConnnectNodeInput (node_1, 0, node_2, 0), Is.EqualTo (AUGraphError.OK), "#1"); uint count; aug.GetNumberOfInteractions (out count); - Assert.AreEqual (1, count, "#2"); + Assert.That (count, Is.EqualTo (1), "#2"); - Assert.AreEqual (AUGraphError.OK, aug.Initialize (), "#3"); + Assert.That (aug.Initialize (), Is.EqualTo (AUGraphError.OK), "#3"); - Assert.AreEqual (AUGraphError.OK, aug.ClearConnections (), "#4"); + Assert.That (aug.ClearConnections (), Is.EqualTo (AUGraphError.OK), "#4"); aug.GetNumberOfInteractions (out count); - Assert.AreEqual (0, count, "#5"); + Assert.That (count, Is.EqualTo (0), "#5"); } } @@ -67,14 +67,14 @@ public void CreateTest () { int errCode; using (var aug = AUGraph.Create (out errCode)) { - Assert.NotNull (aug, "CreateTest"); - Assert.AreEqual (0, errCode, "CreateTest"); + Assert.That (aug, Is.Not.Null, "CreateTest"); + Assert.That (errCode, Is.EqualTo (0), "CreateTest"); // Make sure it is a working instance aug.Open (); - Assert.IsTrue (aug.IsOpen, "CreateTest #0"); - Assert.IsFalse (aug.IsInitialized, "CreateTest #0a"); - Assert.IsFalse (aug.IsRunning, "CreateTest #0b"); + Assert.That (aug.IsOpen, Is.True, "CreateTest #0"); + Assert.That (aug.IsInitialized, Is.False, "CreateTest #0a"); + Assert.That (aug.IsRunning, Is.False, "CreateTest #0b"); } } @@ -86,18 +86,18 @@ public void GetNativeTest () { IntPtr ret = IntPtr.Zero; var errCode = NewAUGraph (ref ret); - Assert.AreEqual (0, errCode, "GetNativeTest"); + Assert.That (errCode, Is.EqualTo (0), "GetNativeTest"); Assert.That (ret, Is.Not.EqualTo (IntPtr.Zero), "ret"); using (var aug = Runtime.GetINativeObject (ret, true)) { - Assert.NotNull (aug, "CreateTest"); + Assert.That (aug, Is.Not.Null, "CreateTest"); Assert.That ((IntPtr) aug.Handle, Is.EqualTo (ret), "Handle"); // Make sure it is a working instance aug.Open (); - Assert.IsTrue (aug.IsOpen, "CreateTest #0"); - Assert.IsFalse (aug.IsInitialized, "CreateTest #0a"); - Assert.IsFalse (aug.IsRunning, "CreateTest #0b"); + Assert.That (aug.IsOpen, Is.True, "CreateTest #0"); + Assert.That (aug.IsInitialized, Is.False, "CreateTest #0a"); + Assert.That (aug.IsRunning, Is.False, "CreateTest #0b"); } } } diff --git a/tests/monotouch-test/AudioUnit/AUGraphTestMac.cs b/tests/monotouch-test/AudioUnit/AUGraphTestMac.cs index b9e99e62b40d..6a4a1812b1ee 100644 --- a/tests/monotouch-test/AudioUnit/AUGraphTestMac.cs +++ b/tests/monotouch-test/AudioUnit/AUGraphTestMac.cs @@ -36,14 +36,14 @@ void SetupAUGraph () int outputNode = graph.AddNode (outputDesciption); AUGraphError error = graph.ConnnectNodeInput (mixerNode, 0, outputNode, 0); - Assert.AreEqual (AUGraphError.OK, error); + Assert.That (error, Is.EqualTo (AUGraphError.OK)); graph.Open (); mMixer = graph.GetNodeInfo (mixerNode); AudioUnitStatus status = mMixer.SetElementCount (AudioUnitScopeType.Input, 0); - Assert.AreEqual (AudioUnitStatus.OK, status); + Assert.That (status, Is.EqualTo (AudioUnitStatus.OK)); } [Test] @@ -59,7 +59,7 @@ public void DoTest () //graph.RenderCallback += HandleRenderCallback; AudioUnitStatus status = mMixer.SetRenderCallback (MixerRenderCallback); - Assert.AreEqual (AudioUnitStatus.OK, status); + Assert.That (status, Is.EqualTo (AudioUnitStatus.OK)); WaitOnGraphAndMixerCallbacks (); } diff --git a/tests/monotouch-test/AudioUnit/AUParameterNodeTest.cs b/tests/monotouch-test/AudioUnit/AUParameterNodeTest.cs index 6b0ac617062a..6d52be3b1838 100644 --- a/tests/monotouch-test/AudioUnit/AUParameterNodeTest.cs +++ b/tests/monotouch-test/AudioUnit/AUParameterNodeTest.cs @@ -31,14 +31,11 @@ public void CreateTokenByAddingParameterRecordingObserver () Exception ex = null; var recordingObserver = tree.CreateTokenByAddingParameterRecordingObserver ((nint numberOfEvents, ref AURecordedParameterEvent events) => { try { - Assert.True (numberOfEvents == 1, - $"Number of events was wrong. Expected {1} but was {numberOfEvents}"); + Assert.That (numberOfEvents == 1, Is.True, $"Number of events was wrong. Expected {1} but was {numberOfEvents}"); - Assert.True (events.Address == address, - $"Address was wrong. Expected {address} but was {events.Address}"); + Assert.That (events.Address == address, Is.True, $"Address was wrong. Expected {address} but was {events.Address}"); - Assert.True (events.Value == newValue, - $"Value was wrong. Expected {newValue} but was {events.Value}"); + Assert.That (events.Value == newValue, Is.True, $"Value was wrong. Expected {newValue} but was {events.Value}"); recordingObserverInvoked = true; } catch (Exception e) { @@ -48,12 +45,12 @@ public void CreateTokenByAddingParameterRecordingObserver () } }); - Assert.True (recordingObserver.ObserverToken != IntPtr.Zero, "TokenByAddingParameterRecordingObserver return zero pointer for recording observer."); + Assert.That (recordingObserver.ObserverToken != IntPtr.Zero, Is.True, "TokenByAddingParameterRecordingObserver return zero pointer for recording observer."); parameter.Value = newValue; completion.WaitOne (TimeSpan.FromSeconds (1)); - Assert.IsNull (ex, "Exceptions"); - Assert.True (recordingObserverInvoked, "Recording observer was not invoked when parameter value was changed."); + Assert.That (ex, Is.Null, "Exceptions"); + Assert.That (recordingObserverInvoked, Is.True, "Recording observer was not invoked when parameter value was changed."); } } } @@ -77,11 +74,11 @@ public void RemoveParameterObserver () tree.RemoveParameterObserver (recordingObserver); - Assert.True (recordingObserver.ObserverToken != IntPtr.Zero, "TokenByAddingParameterRecordingObserver return zero pointer for recording observer."); + Assert.That (recordingObserver.ObserverToken != IntPtr.Zero, Is.True, "TokenByAddingParameterRecordingObserver return zero pointer for recording observer."); parameter.Value = newValue; completion.WaitOne (TimeSpan.FromSeconds (1)); - Assert.False (recordingObserverInvoked, "Recording observer was invoked however observer it should be removed already."); + Assert.That (recordingObserverInvoked, Is.False, "Recording observer was invoked however observer it should be removed already."); } } } @@ -100,11 +97,9 @@ public void ImplementorStringFromValueCallback () using (var parameter = CreateAUParameter ()) { parameter.ImplementorStringFromValueCallback = new AUImplementorStringFromValueCallback ((AUParameter param, ref float? value) => { try { - Assert.True (floatValue == value.Value, - $"Passed float value was incorrect. Expected {floatValue} but was {value}"); + Assert.That (floatValue == value.Value, Is.True, $"Passed float value was incorrect. Expected {floatValue} but was {value}"); - Assert.True (param.Identifier == parameter.Identifier, - $"Passed AUParameter was incorrect. Expected {parameter.Identifier} but was {param.Identifier}"); + Assert.That (param.Identifier == parameter.Identifier, Is.True, $"Passed AUParameter was incorrect. Expected {parameter.Identifier} but was {param.Identifier}"); } catch (Exception e) { ex = e; } finally { @@ -113,13 +108,12 @@ public void ImplementorStringFromValueCallback () return (NSString) value.ToString (); }); - Assert.IsNull (ex, "Exception"); + Assert.That (ex, Is.Null, "Exception"); var str = parameter.GetString (floatValue); - Assert.True (implementorCallbackInvoked, "StringValueFrom callback was not invoked."); - Assert.True (str == expectedStringValue, - $"String doesn't match. Expected {expectedStringValue}, actual {str}"); + Assert.That (implementorCallbackInvoked, Is.True, "StringValueFrom callback was not invoked."); + Assert.That (str == expectedStringValue, Is.True, $"String doesn't match. Expected {expectedStringValue}, actual {str}"); } } @@ -135,11 +129,9 @@ public void ImplementorValueFromStringCallback () using (var parameter = CreateAUParameter ()) { parameter.ImplementorValueFromStringCallback = new AUImplementorValueFromStringCallback ((param, str) => { - Assert.True (str == stringValue, - $"Passed string value was incorrect. Expected {stringValue} but was {str}"); + Assert.That (str == stringValue, Is.True, $"Passed string value was incorrect. Expected {stringValue} but was {str}"); - Assert.True (param.Identifier == parameter.Identifier, - $"Passed AUParameter was incorrect. Expected {parameter.Identifier} but was {param.Identifier}"); + Assert.That (param.Identifier == parameter.Identifier, Is.True, $"Passed AUParameter was incorrect. Expected {parameter.Identifier} but was {param.Identifier}"); implementorCallbackInvoked = true; return Single.Parse (str); @@ -147,9 +139,8 @@ public void ImplementorValueFromStringCallback () var value = parameter.GetValue (stringValue); - Assert.True (implementorCallbackInvoked, "ValueFromString callback was not invoked."); - Assert.False (Math.Abs (value - expectedValue) > float.Epsilon, - $"Values doesn't match. Expected {expectedValue}, actual {value}"); + Assert.That (implementorCallbackInvoked, Is.True, "ValueFromString callback was not invoked."); + Assert.That (Math.Abs (value - expectedValue) > float.Epsilon, Is.False, $"Values doesn't match. Expected {expectedValue}, actual {value}"); } } @@ -170,17 +161,16 @@ public void ImplementorDisplayNameWithLengthCallback () using (var parameter = CreateAUParameter ()) { parameter.ImplementorDisplayNameWithLengthCallback = new AUImplementorDisplayNameWithLengthCallback ((node, desiredLength) => { - Assert.AreEqual ((nint) length, (nint) desiredLength, "Passed length value is incorrect."); - Assert.True (node.Identifier == parameter.Identifier, - $"Passed AUParameterNode was incorrect. Expected {parameter.Identifier} but was {node.Identifier}"); + Assert.That ((nint) desiredLength, Is.EqualTo ((nint) length), "Passed length value is incorrect."); + Assert.That (node.Identifier == parameter.Identifier, Is.True, $"Passed AUParameterNode was incorrect. Expected {parameter.Identifier} but was {node.Identifier}"); implementorCallbackInvoked = true; return node.DisplayName.Substring (0, (int) desiredLength); }); var s = parameter.GetDisplayName (length); - Assert.True (implementorCallbackInvoked, "Display name callback was not invoked."); - Assert.True (expectedTruncatedName == s, $"Truncated node display name was incorrect. Expected {expectedTruncatedName} but was {s}"); + Assert.That (implementorCallbackInvoked, Is.True, "Display name callback was not invoked."); + Assert.That (expectedTruncatedName == s, Is.True, $"Truncated node display name was incorrect. Expected {expectedTruncatedName} but was {s}"); } } diff --git a/tests/monotouch-test/AudioUnit/AVSpeechSynthesisProviderAudioUnitTest.cs b/tests/monotouch-test/AudioUnit/AVSpeechSynthesisProviderAudioUnitTest.cs index 78116f2749de..dc1f9d8f60f0 100644 --- a/tests/monotouch-test/AudioUnit/AVSpeechSynthesisProviderAudioUnitTest.cs +++ b/tests/monotouch-test/AudioUnit/AVSpeechSynthesisProviderAudioUnitTest.cs @@ -19,8 +19,8 @@ public void Create () ComponentManufacturer = AudioComponentManufacturerType.Apple, }; using var unit = AVSpeechSynthesisProviderAudioUnit.Create (cd, (AudioComponentInstantiationOptions) 0, out var error); - Assert.IsNotNull (unit, "Unit"); - Assert.IsNull (error, "Error"); + Assert.That (unit, Is.Not.Null, "Unit"); + Assert.That (error, Is.Null, "Error"); } } } diff --git a/tests/monotouch-test/AudioUnit/AudioUnitTest.cs b/tests/monotouch-test/AudioUnit/AudioUnitTest.cs index c4fa750ba3aa..9aed16e30a03 100644 --- a/tests/monotouch-test/AudioUnit/AudioUnitTest.cs +++ b/tests/monotouch-test/AudioUnit/AudioUnitTest.cs @@ -37,7 +37,7 @@ public void GetElementCount () var mixerNode = graph.AddNode (AudioComponentDescription.CreateMixer (AudioTypeMixer.MultiChannel)); graph.Open (); var mixer = graph.GetNodeInfo (mixerNode); - Assert.AreEqual (1, mixer.GetElementCount (AudioUnitScopeType.Global)); + Assert.That (mixer.GetElementCount (AudioUnitScopeType.Global), Is.EqualTo (1)); } [Test] @@ -62,9 +62,9 @@ public void CopyIconTest () [Test] public unsafe void TestSizeOf () { - Assert.AreEqual (sizeof (AudioFormat), Marshal.SizeOf ()); - Assert.AreEqual (sizeof (AudioValueRange), Marshal.SizeOf ()); - Assert.AreEqual (sizeof (AudioClassDescription), Marshal.SizeOf ()); + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (AudioFormat))); + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (AudioValueRange))); + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (AudioClassDescription))); } } } diff --git a/tests/monotouch-test/AudioUnit/ExtAudioFileTest.cs b/tests/monotouch-test/AudioUnit/ExtAudioFileTest.cs index 7c1905ffe41b..1c4f7938b794 100644 --- a/tests/monotouch-test/AudioUnit/ExtAudioFileTest.cs +++ b/tests/monotouch-test/AudioUnit/ExtAudioFileTest.cs @@ -19,10 +19,10 @@ public void WrapAudioFileID () { var path = NSBundle.MainBundle.PathForResource ("1", "caf", "AudioToolbox"); using (var file = ExtAudioFile.OpenUrl (CFUrl.FromFile (path))) { - Assert.IsNotNull (file.AudioFile, "#1"); + Assert.That (file.AudioFile, Is.Not.Null, "#1"); ExtAudioFile f2; - Assert.AreEqual (ExtAudioFileError.OK, ExtAudioFile.WrapAudioFileID (file.AudioFile.Value, true, out f2)); + Assert.That (ExtAudioFile.WrapAudioFileID (file.AudioFile.Value, true, out f2), Is.EqualTo (ExtAudioFileError.OK)); } } @@ -41,8 +41,8 @@ public void OpenNSUrlTest () var path = NSBundle.MainBundle.PathForResource ("1", "caf", "AudioToolbox"); ExtAudioFileError err; using (var file = ExtAudioFile.OpenUrl (NSUrl.FromFilename (path), out err)) { - Assert.IsTrue (err == ExtAudioFileError.OK, "OpenNSUrlTest"); - Assert.IsNotNull (file.AudioFile, "OpenNSUrlTest"); + Assert.That (err == ExtAudioFileError.OK, Is.True, "OpenNSUrlTest"); + Assert.That (file.AudioFile, Is.Not.Null, "OpenNSUrlTest"); } } @@ -52,8 +52,8 @@ public void OpenCFUrlTest () var path = NSBundle.MainBundle.PathForResource ("1", "caf", "AudioToolbox"); ExtAudioFileError err; using (var file = ExtAudioFile.OpenUrl (CFUrl.FromFile (path), out err)) { - Assert.IsTrue (err == ExtAudioFileError.OK, "OpenCFUrlTest"); - Assert.IsNotNull (file.AudioFile, "OpenCFUrlTest"); + Assert.That (err == ExtAudioFileError.OK, Is.True, "OpenCFUrlTest"); + Assert.That (file.AudioFile, Is.Not.Null, "OpenCFUrlTest"); } } } diff --git a/tests/monotouch-test/AuthenticationServices/PublicPrivateKeyAuthenticationTests.cs b/tests/monotouch-test/AuthenticationServices/PublicPrivateKeyAuthenticationTests.cs index 9ca83740977b..8f7ec732d96a 100644 --- a/tests/monotouch-test/AuthenticationServices/PublicPrivateKeyAuthenticationTests.cs +++ b/tests/monotouch-test/AuthenticationServices/PublicPrivateKeyAuthenticationTests.cs @@ -25,7 +25,7 @@ public void Setup () public void GetAllSupportedPublicKeyCredentialDescriptorTransports () { var transports = PublicPrivateKeyAuthentication.GetAllSupportedPublicKeyCredentialDescriptorTransports (); - Assert.IsNotNull (PublicPrivateKeyAuthentication.GetAllSupportedPublicKeyCredentialDescriptorTransports (), "The transports should not be null"); + Assert.That (PublicPrivateKeyAuthentication.GetAllSupportedPublicKeyCredentialDescriptorTransports (), Is.Not.Null, "The transports should not be null"); // since there is no default enum value, make sure there is not // more than one ASAuthorizationSecurityKeyPublicKeyCredentialDescriptorTransport.Usb @@ -34,7 +34,7 @@ public void GetAllSupportedPublicKeyCredentialDescriptorTransports () if (transport == ASAuthorizationSecurityKeyPublicKeyCredentialDescriptorTransport.Usb) usbCounter++; } - Assert.LessOrEqual (usbCounter, 1, "There were multiple usb transports found. Add any new transports to GetAllSupportedPublicKeyCredentialDescriptorTransports inside src/AuthenticationServices/PublicPrivateKeyAuthentication.cs"); + Assert.That (usbCounter, Is.LessThanOrEqualTo (1), "There were multiple usb transports found. Add any new transports to GetAllSupportedPublicKeyCredentialDescriptorTransports inside src/AuthenticationServices/PublicPrivateKeyAuthentication.cs"); } } } diff --git a/tests/monotouch-test/BackgroundTasks/BGTaskSchedulerTest.cs b/tests/monotouch-test/BackgroundTasks/BGTaskSchedulerTest.cs index 098448c55665..7d111954adf8 100644 --- a/tests/monotouch-test/BackgroundTasks/BGTaskSchedulerTest.cs +++ b/tests/monotouch-test/BackgroundTasks/BGTaskSchedulerTest.cs @@ -44,16 +44,16 @@ public void SubmitTaskRequestTest () { TestRuntime.AssertDevice (); TestRuntime.AssertXcodeVersion (11, 0); - Assert.True (registered, "Task was not registered."); + Assert.That (registered, Is.True, "Task was not registered."); // get the shared scheduler, create a request and submit it, this will be called asap // and the autoreset event set. var request = new BGProcessingTaskRequest (taskIdentifier); NSError error; BGTaskScheduler.Shared.Submit (request, out error); - Assert.IsNull (error, $"Error submiting request {error}"); + Assert.That (error, Is.Null, $"Error submiting request {error}"); LaunchBGTask (); autoResetEvent.WaitOne (300); - Assert.True (taskWasCalled, "Called task."); + Assert.That (taskWasCalled, Is.True, "Called task."); } } } diff --git a/tests/monotouch-test/CarPlay/CPMessageListItemTests.cs b/tests/monotouch-test/CarPlay/CPMessageListItemTests.cs index 39b870b86876..156f008d0e1a 100644 --- a/tests/monotouch-test/CarPlay/CPMessageListItemTests.cs +++ b/tests/monotouch-test/CarPlay/CPMessageListItemTests.cs @@ -33,13 +33,13 @@ public void InitUsingConversationIdentifier () var trailingItemConfig = new CPMessageListItemTrailingConfiguration (new CPMessageTrailingItem (), null); CPMessageListItem listItem = new CPMessageListItem ("convoId", "text", leadingItemConfig, trailingItemConfig, "detailText", "trailingText", CPMessageListItemType.Identifier); - Assert.NotNull (listItem, "CPMessageListItem not be null."); - Assert.AreEqual (listItem.Text, "text"); - Assert.AreEqual (listItem.ConversationIdentifier, "convoId"); - Assert.AreSame (listItem.LeadingConfiguration, leadingItemConfig); - Assert.AreSame (listItem.TrailingConfiguration, trailingItemConfig); - Assert.AreEqual (listItem.DetailText, "detailText"); - Assert.AreEqual (listItem.TrailingText, "trailingText"); + Assert.That (listItem, Is.Not.Null, "CPMessageListItem not be null."); + Assert.That (listItem.Text, Is.EqualTo ("text")); + Assert.That (listItem.ConversationIdentifier, Is.EqualTo ("convoId")); + Assert.That (leadingItemConfig, Is.SameAs (listItem.LeadingConfiguration)); + Assert.That (trailingItemConfig, Is.SameAs (listItem.TrailingConfiguration)); + Assert.That (listItem.DetailText, Is.EqualTo ("detailText")); + Assert.That (listItem.TrailingText, Is.EqualTo ("trailingText")); } [Test] @@ -49,13 +49,13 @@ public void InitUsingFullName () var trailingItemConfig = new CPMessageListItemTrailingConfiguration (new CPMessageTrailingItem (), null); CPMessageListItem listItem = new CPMessageListItem ("fullName", "phoneOrEmail", leadingItemConfig, trailingItemConfig, "detailText", "trailingText", CPMessageListItemType.FullName); - Assert.NotNull (listItem, "CPMessageListItem not be null."); - Assert.AreEqual (listItem.Text, "fullName"); - Assert.AreEqual (listItem.PhoneOrEmailAddress, "phoneOrEmail"); - Assert.AreSame (listItem.LeadingConfiguration, leadingItemConfig); - Assert.AreSame (listItem.TrailingConfiguration, trailingItemConfig); - Assert.AreEqual (listItem.DetailText, "detailText"); - Assert.AreEqual (listItem.TrailingText, "trailingText"); + Assert.That (listItem, Is.Not.Null, "CPMessageListItem not be null."); + Assert.That (listItem.Text, Is.EqualTo ("fullName")); + Assert.That (listItem.PhoneOrEmailAddress, Is.EqualTo ("phoneOrEmail")); + Assert.That (leadingItemConfig, Is.SameAs (listItem.LeadingConfiguration)); + Assert.That (trailingItemConfig, Is.SameAs (listItem.TrailingConfiguration)); + Assert.That (listItem.DetailText, Is.EqualTo ("detailText")); + Assert.That (listItem.TrailingText, Is.EqualTo ("trailingText")); } } diff --git a/tests/monotouch-test/CarPlay/CPNavigationWaypointTest.cs b/tests/monotouch-test/CarPlay/CPNavigationWaypointTest.cs index 6018b1b55850..b74a81646d01 100644 --- a/tests/monotouch-test/CarPlay/CPNavigationWaypointTest.cs +++ b/tests/monotouch-test/CarPlay/CPNavigationWaypointTest.cs @@ -34,19 +34,19 @@ public void CreateWithCenterPointAndEntryPoints () var waypoint = CPNavigationWaypoint.Create (centerPoint, null, "Test", "123 Main St", entryPoints, null); - Assert.IsNotNull (waypoint, "waypoint"); - Assert.AreEqual ("Test", waypoint.Name, "Name"); - Assert.AreEqual ("123 Main St", waypoint.Address, "Address"); - Assert.AreEqual ((nuint) 2, waypoint.EntryPointsCount, "EntryPointsCount"); + Assert.That (waypoint, Is.Not.Null, "waypoint"); + Assert.That (waypoint.Name, Is.EqualTo ("Test"), "Name"); + Assert.That (waypoint.Address, Is.EqualTo ("123 Main St"), "Address"); + Assert.That (waypoint.EntryPointsCount, Is.EqualTo ((nuint) 2), "EntryPointsCount"); var result = waypoint.EntryPoints; - Assert.AreEqual (2, result.Length, "EntryPoints.Length"); - Assert.AreEqual (37.7750, result [0].Latitude, 0.0001, "EntryPoints[0].Latitude"); - Assert.AreEqual (-122.4195, result [0].Longitude, 0.0001, "EntryPoints[0].Longitude"); - Assert.AreEqual (5.0, result [0].Altitude, 0.0001, "EntryPoints[0].Altitude"); - Assert.AreEqual (37.7751, result [1].Latitude, 0.0001, "EntryPoints[1].Latitude"); - Assert.AreEqual (-122.4196, result [1].Longitude, 0.0001, "EntryPoints[1].Longitude"); - Assert.AreEqual (15.0, result [1].Altitude, 0.0001, "EntryPoints[1].Altitude"); + Assert.That (result.Length, Is.EqualTo (2), "EntryPoints.Length"); + Assert.That (result [0].Latitude, Is.EqualTo (37.7750).Within (0.0001), "EntryPoints[0].Latitude"); + Assert.That (result [0].Longitude, Is.EqualTo (-122.4195).Within (0.0001), "EntryPoints[0].Longitude"); + Assert.That (result [0].Altitude, Is.EqualTo (5.0).Within (0.0001), "EntryPoints[0].Altitude"); + Assert.That (result [1].Latitude, Is.EqualTo (37.7751).Within (0.0001), "EntryPoints[1].Latitude"); + Assert.That (result [1].Longitude, Is.EqualTo (-122.4196).Within (0.0001), "EntryPoints[1].Longitude"); + Assert.That (result [1].Altitude, Is.EqualTo (15.0).Within (0.0001), "EntryPoints[1].Altitude"); } [Test] @@ -56,12 +56,12 @@ public void CreateWithNullEntryPoints () var waypoint = CPNavigationWaypoint.Create (centerPoint, null, "NYC", null, null, null); - Assert.IsNotNull (waypoint, "waypoint"); - Assert.AreEqual ("NYC", waypoint.Name, "Name"); - Assert.AreEqual ((nuint) 0, waypoint.EntryPointsCount, "EntryPointsCount"); + Assert.That (waypoint, Is.Not.Null, "waypoint"); + Assert.That (waypoint.Name, Is.EqualTo ("NYC"), "Name"); + Assert.That (waypoint.EntryPointsCount, Is.EqualTo ((nuint) 0), "EntryPointsCount"); var result = waypoint.EntryPoints; - Assert.AreEqual (0, result.Length, "EntryPoints.Length"); + Assert.That (result.Length, Is.EqualTo (0), "EntryPoints.Length"); } [Test] @@ -71,9 +71,9 @@ public void CreateWithEmptyEntryPoints () var waypoint = CPNavigationWaypoint.Create (centerPoint, null, "London", null, new CPLocationCoordinate3D [0], null); - Assert.IsNotNull (waypoint, "waypoint"); - Assert.AreEqual ((nuint) 0, waypoint.EntryPointsCount, "EntryPointsCount"); - Assert.AreEqual (0, waypoint.EntryPoints.Length, "EntryPoints.Length"); + Assert.That (waypoint, Is.Not.Null, "waypoint"); + Assert.That (waypoint.EntryPointsCount, Is.EqualTo ((nuint) 0), "EntryPointsCount"); + Assert.That (waypoint.EntryPoints.Length, Is.EqualTo (0), "EntryPoints.Length"); } [Test] @@ -86,12 +86,12 @@ public void CreateWithSingleEntryPoint () var waypoint = CPNavigationWaypoint.Create (centerPoint, null, null, null, entryPoints, null); - Assert.IsNotNull (waypoint, "waypoint"); - Assert.AreEqual ((nuint) 1, waypoint.EntryPointsCount, "EntryPointsCount"); + Assert.That (waypoint, Is.Not.Null, "waypoint"); + Assert.That (waypoint.EntryPointsCount, Is.EqualTo ((nuint) 1), "EntryPointsCount"); var result = waypoint.EntryPoints; - Assert.AreEqual (1, result.Length, "EntryPoints.Length"); - Assert.AreEqual (48.8567, result [0].Latitude, 0.0001, "EntryPoints[0].Latitude"); + Assert.That (result.Length, Is.EqualTo (1), "EntryPoints.Length"); + Assert.That (result [0].Latitude, Is.EqualTo (48.8567).Within (0.0001), "EntryPoints[0].Latitude"); } [Test] @@ -101,9 +101,9 @@ public void CenterPointRoundTrip () var waypoint = CPNavigationWaypoint.Create (centerPoint, null, null, null, null, null); - Assert.AreEqual (-33.8688, waypoint.CenterPoint.Latitude, 0.0001, "CenterPoint.Latitude"); - Assert.AreEqual (151.2093, waypoint.CenterPoint.Longitude, 0.0001, "CenterPoint.Longitude"); - Assert.AreEqual (58.0, waypoint.CenterPoint.Altitude, 0.0001, "CenterPoint.Altitude"); + Assert.That (waypoint.CenterPoint.Latitude, Is.EqualTo (-33.8688).Within (0.0001), "CenterPoint.Latitude"); + Assert.That (waypoint.CenterPoint.Longitude, Is.EqualTo (151.2093).Within (0.0001), "CenterPoint.Longitude"); + Assert.That (waypoint.CenterPoint.Altitude, Is.EqualTo (58.0).Within (0.0001), "CenterPoint.Altitude"); } } @@ -145,20 +145,20 @@ public void CreateWithCoordinates () estimates, estimates, coordinates); - Assert.IsNotNull (segment, "segment"); - Assert.AreEqual ((nint) 3, segment.CoordinatesCount, "CoordinatesCount"); + Assert.That (segment, Is.Not.Null, "segment"); + Assert.That (segment.CoordinatesCount, Is.EqualTo ((nint) 3), "CoordinatesCount"); var result = segment.Coordinates; - Assert.AreEqual (3, result.Length, "Coordinates.Length"); - Assert.AreEqual (37.0, result [0].Latitude, 0.0001, "Coordinates[0].Latitude"); - Assert.AreEqual (-122.0, result [0].Longitude, 0.0001, "Coordinates[0].Longitude"); - Assert.AreEqual (0.0, result [0].Altitude, 0.0001, "Coordinates[0].Altitude"); - Assert.AreEqual (36.0, result [1].Latitude, 0.0001, "Coordinates[1].Latitude"); - Assert.AreEqual (-121.0, result [1].Longitude, 0.0001, "Coordinates[1].Longitude"); - Assert.AreEqual (100.0, result [1].Altitude, 0.0001, "Coordinates[1].Altitude"); - Assert.AreEqual (35.0, result [2].Latitude, 0.0001, "Coordinates[2].Latitude"); - Assert.AreEqual (-120.0, result [2].Longitude, 0.0001, "Coordinates[2].Longitude"); - Assert.AreEqual (200.0, result [2].Altitude, 0.0001, "Coordinates[2].Altitude"); + Assert.That (result.Length, Is.EqualTo (3), "Coordinates.Length"); + Assert.That (result [0].Latitude, Is.EqualTo (37.0).Within (0.0001), "Coordinates[0].Latitude"); + Assert.That (result [0].Longitude, Is.EqualTo (-122.0).Within (0.0001), "Coordinates[0].Longitude"); + Assert.That (result [0].Altitude, Is.EqualTo (0.0).Within (0.0001), "Coordinates[0].Altitude"); + Assert.That (result [1].Latitude, Is.EqualTo (36.0).Within (0.0001), "Coordinates[1].Latitude"); + Assert.That (result [1].Longitude, Is.EqualTo (-121.0).Within (0.0001), "Coordinates[1].Longitude"); + Assert.That (result [1].Altitude, Is.EqualTo (100.0).Within (0.0001), "Coordinates[1].Altitude"); + Assert.That (result [2].Latitude, Is.EqualTo (35.0).Within (0.0001), "Coordinates[2].Latitude"); + Assert.That (result [2].Longitude, Is.EqualTo (-120.0).Within (0.0001), "Coordinates[2].Longitude"); + Assert.That (result [2].Altitude, Is.EqualTo (200.0).Within (0.0001), "Coordinates[2].Altitude"); } [Test] @@ -187,9 +187,9 @@ public void OriginAndDestination () estimates, estimates, coordinates); - Assert.IsNotNull (segment.Origin, "Origin"); - Assert.IsNotNull (segment.Destination, "Destination"); - Assert.IsNotNull (segment.Identifier, "Identifier"); + Assert.That (segment.Origin, Is.Not.Null, "Origin"); + Assert.That (segment.Destination, Is.Not.Null, "Destination"); + Assert.That (segment.Identifier, Is.Not.Null, "Identifier"); } } } diff --git a/tests/monotouch-test/CloudKit/CKFetchRecordChangesOperationTest.cs b/tests/monotouch-test/CloudKit/CKFetchRecordChangesOperationTest.cs index c945247a5b10..0b9bb4bc4cb2 100644 --- a/tests/monotouch-test/CloudKit/CKFetchRecordChangesOperationTest.cs +++ b/tests/monotouch-test/CloudKit/CKFetchRecordChangesOperationTest.cs @@ -28,21 +28,21 @@ public void TearDown () public void TestRecordChangedSetter () { op.RecordChanged = (record) => { Console.WriteLine ("Changed"); }; - Assert.NotNull (op.RecordChanged); + Assert.That (op.RecordChanged, Is.Not.Null); } [Test] public void TestRecordDeletedSetter () { op.RecordDeleted = (record) => { Console.WriteLine ("Deleted"); }; - Assert.NotNull (op.RecordDeleted); + Assert.That (op.RecordDeleted, Is.Not.Null); } [Test] public void TestAllChangesReported () { op.AllChangesReported = (s, c, e) => { Console.WriteLine ("Completed"); }; - Assert.NotNull (op.AllChangesReported); + Assert.That (op.AllChangesReported, Is.Not.Null); } } } diff --git a/tests/monotouch-test/CloudKit/CKFetchRecordZonesOperationTest.cs b/tests/monotouch-test/CloudKit/CKFetchRecordZonesOperationTest.cs index cdca38a6b5d2..d22410ddcbf1 100644 --- a/tests/monotouch-test/CloudKit/CKFetchRecordZonesOperationTest.cs +++ b/tests/monotouch-test/CloudKit/CKFetchRecordZonesOperationTest.cs @@ -27,7 +27,7 @@ public void TearDown () public void TestCompletedSetter () { op.Completed = (idDict, e) => { Console.WriteLine ("Completed"); }; - Assert.NotNull (op.Completed); + Assert.That (op.Completed, Is.Not.Null); } } } diff --git a/tests/monotouch-test/CloudKit/CKFetchRecordsOperationTest.cs b/tests/monotouch-test/CloudKit/CKFetchRecordsOperationTest.cs index 7b3a86b4c80f..98ef91325ce3 100644 --- a/tests/monotouch-test/CloudKit/CKFetchRecordsOperationTest.cs +++ b/tests/monotouch-test/CloudKit/CKFetchRecordsOperationTest.cs @@ -27,21 +27,21 @@ public void TearDown () public void PerRecordProgressSetter () { op.PerRecordProgress = (id, p) => { Console.WriteLine ("Notification"); }; - Assert.NotNull (op.PerRecordProgress); + Assert.That (op.PerRecordProgress, Is.Not.Null); } [Test] public void PerRecordCompletionSetter () { op.PerRecordCompletion = (record, id, e) => { Console.WriteLine ("Notification"); }; - Assert.NotNull (op.PerRecordCompletion); + Assert.That (op.PerRecordCompletion, Is.Not.Null); } [Test] public void TestCompletedSetter () { op.Completed = (idDict, e) => { Console.WriteLine ("Completed"); }; - Assert.NotNull (op.Completed); + Assert.That (op.Completed, Is.Not.Null); } } } diff --git a/tests/monotouch-test/CloudKit/CKFetchSubscriptionsOperationTest.cs b/tests/monotouch-test/CloudKit/CKFetchSubscriptionsOperationTest.cs index 14992f42f8d5..e36b5632c5e6 100644 --- a/tests/monotouch-test/CloudKit/CKFetchSubscriptionsOperationTest.cs +++ b/tests/monotouch-test/CloudKit/CKFetchSubscriptionsOperationTest.cs @@ -27,7 +27,7 @@ public void TearDown () public void TestCompletedSetter () { op.Completed = (dict, e) => { Console.WriteLine ("Completed"); }; - Assert.NotNull (op.Completed); + Assert.That (op.Completed, Is.Not.Null); } } } diff --git a/tests/monotouch-test/CloudKit/CKModifyRecordZonesOperationTest.cs b/tests/monotouch-test/CloudKit/CKModifyRecordZonesOperationTest.cs index 4ef7c2457e42..54335a083446 100644 --- a/tests/monotouch-test/CloudKit/CKModifyRecordZonesOperationTest.cs +++ b/tests/monotouch-test/CloudKit/CKModifyRecordZonesOperationTest.cs @@ -26,7 +26,7 @@ public void TearDown () public void TestCompletedSetter () { op.Completed = (saved, deleted, e) => { Console.WriteLine ("Completed"); }; - Assert.NotNull (op.Completed); + Assert.That (op.Completed, Is.Not.Null); } [Test] diff --git a/tests/monotouch-test/CloudKit/CKModifyRecordsOperationTest.cs b/tests/monotouch-test/CloudKit/CKModifyRecordsOperationTest.cs index 48bed8ccd3fb..e0bbb365dfb0 100644 --- a/tests/monotouch-test/CloudKit/CKModifyRecordsOperationTest.cs +++ b/tests/monotouch-test/CloudKit/CKModifyRecordsOperationTest.cs @@ -26,21 +26,21 @@ public void TearDown () public void PerRecordProgressSetter () { op.PerRecordProgress = (record, p) => { Console.WriteLine ("Progress"); }; - Assert.NotNull (op.PerRecordProgress); + Assert.That (op.PerRecordProgress, Is.Not.Null); } [Test] public void PerRecordCompletionSetter () { op.PerRecordCompletion = (record, e) => { Console.WriteLine ("Notification"); }; - Assert.NotNull (op.PerRecordCompletion); + Assert.That (op.PerRecordCompletion, Is.Not.Null); } [Test] public void TestCompletedSetter () { op.Completed = (saved, deleted, e) => { Console.WriteLine ("Completed"); }; - Assert.NotNull (op.Completed); + Assert.That (op.Completed, Is.Not.Null); } [Test] diff --git a/tests/monotouch-test/CloudKit/CKModifySubscriptionsOperationTest.cs b/tests/monotouch-test/CloudKit/CKModifySubscriptionsOperationTest.cs index a27932189e1e..f991403410cd 100644 --- a/tests/monotouch-test/CloudKit/CKModifySubscriptionsOperationTest.cs +++ b/tests/monotouch-test/CloudKit/CKModifySubscriptionsOperationTest.cs @@ -26,7 +26,7 @@ public void TearDown () public void TestCompletedSetter () { op.Completed = (saved, deleted, e) => { Console.WriteLine ("Completed"); }; - Assert.NotNull (op.Completed); + Assert.That (op.Completed, Is.Not.Null); } } } diff --git a/tests/monotouch-test/CloudKit/CKQueryOperationTest.cs b/tests/monotouch-test/CloudKit/CKQueryOperationTest.cs index 7c983936b458..4e8c4219b2f5 100644 --- a/tests/monotouch-test/CloudKit/CKQueryOperationTest.cs +++ b/tests/monotouch-test/CloudKit/CKQueryOperationTest.cs @@ -28,14 +28,14 @@ public void TearDown () public void TestRecordFetchedSetter () { op.RecordFetched = (record) => { Console.WriteLine ("Completed"); }; - Assert.NotNull (op.RecordFetched); + Assert.That (op.RecordFetched, Is.Not.Null); } [Test] public void TestCompletedSetter () { op.Completed = (cursor, e) => { Console.WriteLine ("Completed"); }; - Assert.NotNull (op.Completed); + Assert.That (op.Completed, Is.Not.Null); } } } diff --git a/tests/monotouch-test/CloudKit/CKUserIdentityLookupInfoTest.cs b/tests/monotouch-test/CloudKit/CKUserIdentityLookupInfoTest.cs index 2c329ecdabb5..482c09f3a363 100644 --- a/tests/monotouch-test/CloudKit/CKUserIdentityLookupInfoTest.cs +++ b/tests/monotouch-test/CloudKit/CKUserIdentityLookupInfoTest.cs @@ -15,16 +15,16 @@ public void MinimumSdkCheck () public void TestFromEmail () { var info = CKUserIdentityLookupInfo.FromEmail ("example@test.com"); - Assert.NotNull (info); - Assert.AreNotEqual (info.Handle, IntPtr.Zero); + Assert.That (info, Is.Not.Null); + Assert.That (IntPtr.Zero, Is.Not.EqualTo (info.Handle)); } [Test] public void TestFromPhoneNumber () { var info = CKUserIdentityLookupInfo.FromPhoneNumber ("91899899"); - Assert.NotNull (info); - Assert.AreNotEqual (info.Handle, IntPtr.Zero); + Assert.That (info, Is.Not.Null); + Assert.That (IntPtr.Zero, Is.Not.EqualTo (info.Handle)); } [Test] @@ -32,8 +32,8 @@ public void TestFromRecordID () { var record = new CKRecordID ("recordName"); var info = new CKUserIdentityLookupInfo (record); - Assert.NotNull (info); - Assert.AreNotEqual (info.Handle, IntPtr.Zero); + Assert.That (info, Is.Not.Null); + Assert.That (IntPtr.Zero, Is.Not.EqualTo (info.Handle)); } [Test] @@ -41,7 +41,7 @@ public void TestGetLookupInfosWithEmails () { var emails = new string [] { "example@test.com" }; var result = CKUserIdentityLookupInfo.GetLookupInfosWithEmails (emails); - Assert.AreEqual (1, result.Length); + Assert.That (result.Length, Is.EqualTo (1)); } [Test] @@ -49,7 +49,7 @@ public void TestGetLookupInfosWithPhoneNumbers () { var numbers = new string [] { "9111223" }; var result = CKUserIdentityLookupInfo.GetLookupInfosWithPhoneNumbers (numbers); - Assert.AreEqual (1, result.Length); + Assert.That (result.Length, Is.EqualTo (1)); } [Test] @@ -58,7 +58,7 @@ public void TestGetLookupInfosWithRecordIds () var record = new CKRecordID ("recordName"); var records = new CKRecordID [] { record }; var result = CKUserIdentityLookupInfo.GetLookupInfos (records); - Assert.AreEqual (1, result.Length); + Assert.That (result.Length, Is.EqualTo (1)); } } } diff --git a/tests/monotouch-test/Compression/CompressionStreamTest.cs b/tests/monotouch-test/Compression/CompressionStreamTest.cs index 8b2dfc94e50e..9ccc4c30d867 100644 --- a/tests/monotouch-test/Compression/CompressionStreamTest.cs +++ b/tests/monotouch-test/Compression/CompressionStreamTest.cs @@ -72,8 +72,8 @@ public void CheckCompressDecompress (CompressionAlgorithm algorithm) DeflateStream decompressing = new DeflateStream (backing, CompressionMode.Decompress, algorithm); MemoryStream output = new MemoryStream (); CopyStream (decompressing, output); - Assert.AreNotEqual (0, output.Length, "Length should be more than 0."); - Assert.IsTrue (compare_buffers (data, output.GetBuffer (), (int) output.Length), "Buffers are not equal."); + Assert.That (output.Length, Is.Not.EqualTo (0), "Length should be more than 0."); + Assert.That (compare_buffers (data, output.GetBuffer (), (int) output.Length), Is.True, "Buffers are not equal."); decompressing.Close (); output.Close (); } @@ -86,7 +86,7 @@ public void CheckDecompress () MemoryStream backing = new MemoryStream (compressed_data); DeflateStream decompressing = new DeflateStream (backing, CompressionMode.Decompress, CompressionAlgorithm.Zlib); StreamReader reader = new StreamReader (decompressing); - Assert.AreEqual ("Hello", reader.ReadLine ()); + Assert.That (reader.ReadLine (), Is.EqualTo ("Hello")); decompressing.Close (); } @@ -172,19 +172,19 @@ public void CheckGetCanSeekProp () Assert.Ignore ("Requires iOS 9.0+ or macOS 10.11+"); MemoryStream backing = new MemoryStream (compressed_data); DeflateStream decompress = new DeflateStream (backing, CompressionMode.Decompress, CompressionAlgorithm.Zlib); - Assert.IsFalse (decompress.CanSeek, "#A1"); - Assert.IsTrue (backing.CanSeek, "#A2"); + Assert.That (decompress.CanSeek, Is.False, "#A1"); + Assert.That (backing.CanSeek, Is.True, "#A2"); decompress.Dispose (); - Assert.IsFalse (decompress.CanSeek, "#A3"); - Assert.IsFalse (backing.CanSeek, "#A4"); + Assert.That (decompress.CanSeek, Is.False, "#A3"); + Assert.That (backing.CanSeek, Is.False, "#A4"); backing = new MemoryStream (); DeflateStream compress = new DeflateStream (backing, CompressionMode.Compress, CompressionAlgorithm.Zlib); - Assert.IsFalse (compress.CanSeek, "#B1"); - Assert.IsTrue (backing.CanSeek, "#B2"); + Assert.That (compress.CanSeek, Is.False, "#B1"); + Assert.That (backing.CanSeek, Is.True, "#B2"); compress.Dispose (); - Assert.IsFalse (decompress.CanSeek, "#B3"); - Assert.IsFalse (backing.CanSeek, "#B4"); + Assert.That (decompress.CanSeek, Is.False, "#B3"); + Assert.That (backing.CanSeek, Is.False, "#B4"); } [Test] @@ -194,19 +194,19 @@ public void CheckGetCanReadProp () Assert.Ignore ("Requires iOS 9.0+ or macOS 10.11+"); MemoryStream backing = new MemoryStream (compressed_data); DeflateStream decompress = new DeflateStream (backing, CompressionMode.Decompress, CompressionAlgorithm.Zlib); - Assert.IsTrue (decompress.CanRead, "#A1"); - Assert.IsTrue (backing.CanRead, "#A2"); + Assert.That (decompress.CanRead, Is.True, "#A1"); + Assert.That (backing.CanRead, Is.True, "#A2"); decompress.Dispose (); - Assert.IsFalse (decompress.CanRead, "#A3"); - Assert.IsFalse (backing.CanRead, "#A4"); + Assert.That (decompress.CanRead, Is.False, "#A3"); + Assert.That (backing.CanRead, Is.False, "#A4"); backing = new MemoryStream (); DeflateStream compress = new DeflateStream (backing, CompressionMode.Compress, CompressionAlgorithm.Zlib); - Assert.IsFalse (compress.CanRead, "#B1"); - Assert.IsTrue (backing.CanRead, "#B2"); + Assert.That (compress.CanRead, Is.False, "#B1"); + Assert.That (backing.CanRead, Is.True, "#B2"); compress.Dispose (); - Assert.IsFalse (decompress.CanRead, "#B3"); - Assert.IsFalse (backing.CanRead, "#B4"); + Assert.That (decompress.CanRead, Is.False, "#B3"); + Assert.That (backing.CanRead, Is.False, "#B4"); } [Test] @@ -216,19 +216,19 @@ public void CheckGetCanWriteProp () Assert.Ignore ("Requires iOS 9.0+ or macOS 10.11+"); MemoryStream backing = new MemoryStream (); DeflateStream decompress = new DeflateStream (backing, CompressionMode.Decompress, CompressionAlgorithm.Zlib); - Assert.IsFalse (decompress.CanWrite, "#A1"); - Assert.IsTrue (backing.CanWrite, "#A2"); + Assert.That (decompress.CanWrite, Is.False, "#A1"); + Assert.That (backing.CanWrite, Is.True, "#A2"); decompress.Dispose (); - Assert.IsFalse (decompress.CanWrite, "#A3"); - Assert.IsFalse (backing.CanWrite, "#A4"); + Assert.That (decompress.CanWrite, Is.False, "#A3"); + Assert.That (backing.CanWrite, Is.False, "#A4"); backing = new MemoryStream (); DeflateStream compress = new DeflateStream (backing, CompressionMode.Compress, CompressionAlgorithm.Zlib); - Assert.IsTrue (compress.CanWrite, "#B1"); - Assert.IsTrue (backing.CanWrite, "#B2"); + Assert.That (compress.CanWrite, Is.True, "#B1"); + Assert.That (backing.CanWrite, Is.True, "#B2"); compress.Dispose (); - Assert.IsFalse (decompress.CanWrite, "#B3"); - Assert.IsFalse (backing.CanWrite, "#B4"); + Assert.That (decompress.CanWrite, Is.False, "#B3"); + Assert.That (backing.CanWrite, Is.False, "#B4"); } [Test] @@ -317,7 +317,7 @@ public override int Read (byte [] buffer, int offset, int count) // blocks the thread waiting for at least a byte to return. // This assert guarantees that Read is called only when there // is something to be read. - Assert.IsTrue (Position < Length, "Trying to read empty stream."); + Assert.That (Position < Length, Is.True, "Trying to read empty stream."); return base.Read (buffer, offset, count); } diff --git a/tests/monotouch-test/Compression/ThoroughCompressionStreamTest.cs b/tests/monotouch-test/Compression/ThoroughCompressionStreamTest.cs index 5895ebf0ccf9..0cb832e725d7 100644 --- a/tests/monotouch-test/Compression/ThoroughCompressionStreamTest.cs +++ b/tests/monotouch-test/Compression/ThoroughCompressionStreamTest.cs @@ -63,8 +63,8 @@ void DecodeRealFile (CompressionAlgorithm algorithm, string compressedFile, stri output.Seek (0, SeekOrigin.Begin); StreamReader reader = new StreamReader (output); output.Seek (0, SeekOrigin.Begin); - Assert.AreNotEqual (0, output.Length, "Stream length should not be 0,"); - Assert.IsTrue (compare_buffers (File.ReadAllBytes (uncompressedFile), output.GetBuffer (), (int) output.Length), "Streams are not equal."); + Assert.That (output.Length, Is.Not.EqualTo (0), "Stream length should not be 0,"); + Assert.That (compare_buffers (File.ReadAllBytes (uncompressedFile), output.GetBuffer (), (int) output.Length), Is.True, "Streams are not equal."); decompressing.Close (); output.Close (); } diff --git a/tests/monotouch-test/Contacts/ContactFetchRequestTest.cs b/tests/monotouch-test/Contacts/ContactFetchRequestTest.cs index 71fbbec87888..5caa0c4a00b1 100644 --- a/tests/monotouch-test/Contacts/ContactFetchRequestTest.cs +++ b/tests/monotouch-test/Contacts/ContactFetchRequestTest.cs @@ -47,7 +47,7 @@ public void Ctor_Mixed () { var keys = new INativeObject [] { CNContactKey.GivenName, CNContactVCardSerialization.GetDescriptorFromRequiredKeys () }; using (var cfr = new CNContactFetchRequest (keys)) { - Assert.That ((nuint) 2, Is.EqualTo (cfr.KeysToFetch.Count), "KeysToFetch"); + Assert.That (cfr.KeysToFetch.Count, Is.EqualTo ((nuint) 2), "KeysToFetch"); } } } diff --git a/tests/monotouch-test/Contacts/ContactFormatterTest.cs b/tests/monotouch-test/Contacts/ContactFormatterTest.cs index 35fa3eefa5bd..88a7e245949a 100644 --- a/tests/monotouch-test/Contacts/ContactFormatterTest.cs +++ b/tests/monotouch-test/Contacts/ContactFormatterTest.cs @@ -30,8 +30,8 @@ public void GetDescriptorForRequiredKeys_FullName () // while most input for ICNKeyDescriptor are done with NSString // the output is opaque and an internal type // note: this is not very robust - but I want to know if this changes during the next betas - Assert.True (keys.Description.StartsWith (" [] { new CNLabeledValue ("label", new CNContactRelation ("relation")) }; - Assert.AreEqual (1, contact.ContactRelations.Length, "ContactRelations"); + Assert.That (contact.ContactRelations.Length, Is.EqualTo (1), "ContactRelations"); contact.ContactType = CNContactType.Organization; - Assert.AreEqual (CNContactType.Organization, contact.ContactType, "ContactType"); + Assert.That (contact.ContactType, Is.EqualTo (CNContactType.Organization), "ContactType"); contact.Dates = new CNLabeledValue [] { new CNLabeledValue ("label", new NSDateComponents () { Month = 6 }) }; - Assert.AreEqual (1, contact.Dates.Length, "Dates"); + Assert.That (contact.Dates.Length, Is.EqualTo (1), "Dates"); contact.DepartmentName = "department"; - Assert.AreEqual ("department", contact.DepartmentName, "DepartmentName"); + Assert.That (contact.DepartmentName, Is.EqualTo ("department"), "DepartmentName"); contact.EmailAddresses = new CNLabeledValue [] { new CNLabeledValue ("label", (NSString) "foo@bar.com") }; - Assert.AreEqual (1, contact.EmailAddresses.Length, "EmailAddresses"); + Assert.That (contact.EmailAddresses.Length, Is.EqualTo (1), "EmailAddresses"); contact.FamilyName = "familyName"; - Assert.AreEqual ("familyName", contact.FamilyName, "FamilyName"); + Assert.That (contact.FamilyName, Is.EqualTo ("familyName"), "FamilyName"); contact.GivenName = "givenName"; - Assert.AreEqual ("givenName", contact.GivenName, "GivenName"); + Assert.That (contact.GivenName, Is.EqualTo ("givenName"), "GivenName"); - Assert.AreNotEqual (string.Empty, contact.Identifier, "Identifier"); + Assert.That (contact.Identifier, Is.Not.EqualTo (string.Empty), "Identifier"); contact.ImageData = new NSData (); - Assert.IsNotNull (contact.ImageData, "ImageData-2"); + Assert.That (contact.ImageData, Is.Not.Null, "ImageData-2"); // iOS 10 (beta 1) fixed this bug (if not null then it's available) var avail = TestRuntime.CheckXcodeVersion (8, 0); Assert.That (contact.ImageDataAvailable, Is.EqualTo (avail), "ImageDataAvailable-2"); @@ -102,47 +102,47 @@ public void Properties () contact.InstantMessageAddresses = new CNLabeledValue [] { new CNLabeledValue ("label", new CNInstantMessageAddress ("user", "service")), }; - Assert.AreEqual (1, contact.InstantMessageAddresses.Length, "InstantMessageAddresses"); + Assert.That (contact.InstantMessageAddresses.Length, Is.EqualTo (1), "InstantMessageAddresses"); contact.JobTitle = "title"; - Assert.AreEqual ("title", contact.JobTitle, "JobTitle"); + Assert.That (contact.JobTitle, Is.EqualTo ("title"), "JobTitle"); contact.MiddleName = "middleName"; - Assert.AreEqual ("middleName", contact.MiddleName, "MiddleName"); + Assert.That (contact.MiddleName, Is.EqualTo ("middleName"), "MiddleName"); contact.NamePrefix = "namePrefix"; - Assert.AreEqual ("namePrefix", contact.NamePrefix, "NamePrefix"); + Assert.That (contact.NamePrefix, Is.EqualTo ("namePrefix"), "NamePrefix"); contact.NameSuffix = "nameSuffix"; - Assert.AreEqual ("nameSuffix", contact.NameSuffix, "NameSuffix"); + Assert.That (contact.NameSuffix, Is.EqualTo ("nameSuffix"), "NameSuffix"); contact.Nickname = "nickname"; - Assert.AreEqual ("nickname", contact.Nickname, "Nickname"); + Assert.That (contact.Nickname, Is.EqualTo ("nickname"), "Nickname"); contact.NonGregorianBirthday = new NSDateComponents () { Year = 2099, }; - Assert.AreEqual ((nint) 2099, contact.NonGregorianBirthday.Year, "NonGregorianBirthday"); + Assert.That (contact.NonGregorianBirthday.Year, Is.EqualTo ((nint) 2099), "NonGregorianBirthday"); contact.Note = "note"; - Assert.AreEqual ("note", contact.Note, "Note"); + Assert.That (contact.Note, Is.EqualTo ("note"), "Note"); contact.OrganizationName = "organizationName"; - Assert.AreEqual ("organizationName", contact.OrganizationName, "OrganizationName"); + Assert.That (contact.OrganizationName, Is.EqualTo ("organizationName"), "OrganizationName"); contact.PhoneNumbers = new CNLabeledValue [] { new CNLabeledValue ("label", new CNPhoneNumber ("123-345-456")) }; - Assert.AreEqual (1, contact.PhoneNumbers.Length, "PhoneNumbers"); + Assert.That (contact.PhoneNumbers.Length, Is.EqualTo (1), "PhoneNumbers"); contact.PhoneticFamilyName = "phoneticFamilyName"; - Assert.AreEqual ("phoneticFamilyName", contact.PhoneticFamilyName, "PhoneticFamilyName"); + Assert.That (contact.PhoneticFamilyName, Is.EqualTo ("phoneticFamilyName"), "PhoneticFamilyName"); contact.PhoneticGivenName = "phoneticGivenName"; - Assert.AreEqual ("phoneticGivenName", contact.PhoneticGivenName, "PhoneticGivenName"); + Assert.That (contact.PhoneticGivenName, Is.EqualTo ("phoneticGivenName"), "PhoneticGivenName"); contact.PhoneticMiddleName = "phoneticMiddleName"; - Assert.AreEqual ("phoneticMiddleName", contact.PhoneticMiddleName, "PhoneticMiddleName"); + Assert.That (contact.PhoneticMiddleName, Is.EqualTo ("phoneticMiddleName"), "PhoneticMiddleName"); contact.PostalAddresses = new CNLabeledValue [] { new CNLabeledValue ("label", new CNMutablePostalAddress () @@ -150,20 +150,20 @@ public void Properties () Street = "my Street", }) }; - Assert.AreEqual (1, contact.PostalAddresses.Length, "PostalAddresses"); + Assert.That (contact.PostalAddresses.Length, Is.EqualTo (1), "PostalAddresses"); contact.PreviousFamilyName = "previousFamilyName"; - Assert.AreEqual ("previousFamilyName", contact.PreviousFamilyName, "PreviousFamilyName"); + Assert.That (contact.PreviousFamilyName, Is.EqualTo ("previousFamilyName"), "PreviousFamilyName"); contact.SocialProfiles = new CNLabeledValue [] { new CNLabeledValue ("label", new CNSocialProfile ("url", "username", "useridentifier", "service")) }; - Assert.AreEqual (1, contact.SocialProfiles.Length, "SocialProfiles"); + Assert.That (contact.SocialProfiles.Length, Is.EqualTo (1), "SocialProfiles"); contact.UrlAddresses = new CNLabeledValue [] { new CNLabeledValue ("label", (NSString) "url@address.com") }; - Assert.AreEqual (1, contact.UrlAddresses.Length, "UrlAddresses"); + Assert.That (contact.UrlAddresses.Length, Is.EqualTo (1), "UrlAddresses"); } } } diff --git a/tests/monotouch-test/CoreAnimation/CABasicAnimation.cs b/tests/monotouch-test/CoreAnimation/CABasicAnimation.cs index 81c8a6275293..b5ea95974675 100644 --- a/tests/monotouch-test/CoreAnimation/CABasicAnimation.cs +++ b/tests/monotouch-test/CoreAnimation/CABasicAnimation.cs @@ -15,20 +15,20 @@ public void CABasicAnimation_FromToBy_INativeTests () CABasicAnimation test = CABasicAnimation.FromKeyPath ("bounds"); NSNumber number = new NSNumber (10); test.From = number; - Assert.AreEqual (test.From, number, "NSObject from"); + Assert.That (number, Is.EqualTo (test.From), "NSObject from"); test.To = number; - Assert.AreEqual (test.To, number, "NSObject to"); + Assert.That (number, Is.EqualTo (test.To), "NSObject to"); test.By = number; - Assert.AreEqual (test.By, number, "NSObject by"); + Assert.That (number, Is.EqualTo (test.By), "NSObject by"); CGColor color = new CGColor (.5f, .5f, .5f); test = CABasicAnimation.FromKeyPath ("color"); test.SetFrom (color); - Assert.AreEqual (test.GetFromAs (), color, "INativeObject from"); + Assert.That (color, Is.EqualTo (test.GetFromAs ()), "INativeObject from"); test.SetTo (color); - Assert.AreEqual (test.GetToAs (), color, "INativeObject to"); + Assert.That (color, Is.EqualTo (test.GetToAs ()), "INativeObject to"); test.SetBy (color); - Assert.AreEqual (test.GetByAs (), color, "INativeObject by"); + Assert.That (color, Is.EqualTo (test.GetByAs ()), "INativeObject by"); } } } diff --git a/tests/monotouch-test/CoreAnimation/CAFrameRateRangeTest.cs b/tests/monotouch-test/CoreAnimation/CAFrameRateRangeTest.cs index 9ab666d1270e..f601a332f4f1 100644 --- a/tests/monotouch-test/CoreAnimation/CAFrameRateRangeTest.cs +++ b/tests/monotouch-test/CoreAnimation/CAFrameRateRangeTest.cs @@ -14,10 +14,10 @@ public void SetUp () [Test] public void IsEqualToTest () - => Assert.True (CAFrameRateRange.Default.IsEqualTo (CAFrameRateRange.Default)); + => Assert.That (CAFrameRateRange.Default.IsEqualTo (CAFrameRateRange.Default), Is.True); [Test] public void DefaultTest () - => Assert.IsNotNull (CAFrameRateRange.Default, "Default"); + => Assert.That (CAFrameRateRange.Default, Is.Not.Null, "Default"); } } diff --git a/tests/monotouch-test/CoreAnimation/CAGradientLayerTest.cs b/tests/monotouch-test/CoreAnimation/CAGradientLayerTest.cs index 41b3056a928a..d25e8df70504 100644 --- a/tests/monotouch-test/CoreAnimation/CAGradientLayerTest.cs +++ b/tests/monotouch-test/CoreAnimation/CAGradientLayerTest.cs @@ -18,18 +18,18 @@ public class CAGradientLayerTest { public void Colors_GetSet () { using var layer = new CAGradientLayer (); - Assert.IsNull (layer.Colors, "Colors/default"); + Assert.That (layer.Colors, Is.Null, "Colors/default"); var red = new CGColor (1, 0, 0); var green = new CGColor (0, 1, 0); var blue = new CGColor (0, 0, 1); layer.Colors = new CGColor [] { red, green, blue }; var colors = layer.Colors; - Assert.IsNotNull (colors, "Colors/assigned"); - Assert.AreEqual (3, colors!.Length, "Colors/length"); + Assert.That (colors, Is.Not.Null, "Colors/assigned"); + Assert.That (colors!.Length, Is.EqualTo (3), "Colors/length"); layer.Colors = null; - Assert.IsNull (layer.Colors, "Colors/null"); + Assert.That (layer.Colors, Is.Null, "Colors/null"); } } } diff --git a/tests/monotouch-test/CoreAnimation/CAKeyFrameAnimation.cs b/tests/monotouch-test/CoreAnimation/CAKeyFrameAnimation.cs index 4145c0afb31c..c145318d35b5 100644 --- a/tests/monotouch-test/CoreAnimation/CAKeyFrameAnimation.cs +++ b/tests/monotouch-test/CoreAnimation/CAKeyFrameAnimation.cs @@ -14,9 +14,9 @@ public void CAKeyFrameAnimation_ValuesTests () { CAKeyFrameAnimation keyFrameAni = new CAKeyFrameAnimation (); keyFrameAni.Values = new NSObject [] { new NSNumber (5) }; - Assert.AreEqual (1, keyFrameAni.Values.Length); + Assert.That (keyFrameAni.Values.Length, Is.EqualTo (1)); NSNumber arrayNumber = (NSNumber) keyFrameAni.Values [0]; - Assert.AreEqual (5, arrayNumber.Int32Value); + Assert.That (arrayNumber.Int32Value, Is.EqualTo (5)); CGRect frame = new CGRect (10, 10, 10, 10); @@ -26,9 +26,9 @@ public void CAKeyFrameAnimation_ValuesTests () CGBitmapFlags.ByteOrderDefault | CGBitmapFlags.Last, provider, null, false, CGColorRenderingIntent.Default); keyFrameAni.SetValues (new CGImage [] { image, image }); - Assert.AreEqual (2, keyFrameAni.Values.Length); + Assert.That (keyFrameAni.Values.Length, Is.EqualTo (2)); CGImage arrayImage = (CGImage) keyFrameAni.GetValuesAs () [1]; - Assert.AreEqual (image.Handle, arrayImage.Handle); + Assert.That (arrayImage.Handle, Is.EqualTo (image.Handle)); } } } diff --git a/tests/monotouch-test/CoreAnimation/CALayer.cs b/tests/monotouch-test/CoreAnimation/CALayer.cs index 4cda76ebab25..fe4b90f3fc7a 100644 --- a/tests/monotouch-test/CoreAnimation/CALayer.cs +++ b/tests/monotouch-test/CoreAnimation/CALayer.cs @@ -23,11 +23,11 @@ public void CALayer_ValuesTests () layer.Contents = image; CGImage arrayImage = layer.Contents; - Assert.AreEqual (image.Handle, arrayImage.Handle); + Assert.That (arrayImage.Handle, Is.EqualTo (image.Handle)); layer.SetContents (NSImage); NSImage arrayNSImage = layer.GetContentsAs (); - Assert.AreEqual (NSImage.Handle, arrayNSImage.Handle); + Assert.That (arrayNSImage.Handle, Is.EqualTo (NSImage.Handle)); layer.SetContents (null); // Should not throw layer.Contents = null; // Should not throw diff --git a/tests/monotouch-test/CoreAnimation/CATextLayerTests.cs b/tests/monotouch-test/CoreAnimation/CATextLayerTests.cs index 6976c48cc09f..8e9d7de067fc 100644 --- a/tests/monotouch-test/CoreAnimation/CATextLayerTests.cs +++ b/tests/monotouch-test/CoreAnimation/CATextLayerTests.cs @@ -23,10 +23,10 @@ public void CATextLayerTruncationModeTest () TextTruncationMode = CATextLayerTruncationMode.Middle }; - Assert.AreEqual (CATextLayerTruncationMode.Middle, textLayer.TextTruncationMode, "TextTruncationMode"); + Assert.That (textLayer.TextTruncationMode, Is.EqualTo (CATextLayerTruncationMode.Middle), "TextTruncationMode"); textLayer.TextTruncationMode = CATextLayerTruncationMode.End; - Assert.AreEqual (CATextLayerTruncationMode.End, textLayer.TextTruncationMode, "TextTruncationMode 2"); + Assert.That (textLayer.TextTruncationMode, Is.EqualTo (CATextLayerTruncationMode.End), "TextTruncationMode 2"); } [Test] @@ -37,10 +37,10 @@ public void CATextLayerAlignmentModeTest () TextAlignmentMode = CATextLayerAlignmentMode.Justified }; - Assert.AreEqual (CATextLayerAlignmentMode.Justified, textLayer.TextAlignmentMode, "TextAlignmentMode"); + Assert.That (textLayer.TextAlignmentMode, Is.EqualTo (CATextLayerAlignmentMode.Justified), "TextAlignmentMode"); textLayer.TextAlignmentMode = CATextLayerAlignmentMode.Natural; - Assert.AreEqual (CATextLayerAlignmentMode.Natural, textLayer.TextAlignmentMode, "TextAlignmentMode 2"); + Assert.That (textLayer.TextAlignmentMode, Is.EqualTo (CATextLayerAlignmentMode.Natural), "TextAlignmentMode 2"); } } } diff --git a/tests/monotouch-test/CoreAnimation/EmitterCellTest.cs b/tests/monotouch-test/CoreAnimation/EmitterCellTest.cs index 9583ac6598d2..c16edbd5085c 100644 --- a/tests/monotouch-test/CoreAnimation/EmitterCellTest.cs +++ b/tests/monotouch-test/CoreAnimation/EmitterCellTest.cs @@ -21,12 +21,12 @@ public void XEmitterCellTest () using (var ec = new CAEmitterCell ()) { // ICAMediaTiming Assert.That (ec.BeginTime, Is.EqualTo (0.0d), "BeginTime"); - Assert.True (Double.IsInfinity (ec.Duration), "Duration"); + Assert.That (Double.IsInfinity (ec.Duration), Is.True, "Duration"); Assert.That (ec.Speed, Is.EqualTo (1.0f), "Speed"); Assert.That (ec.TimeOffset, Is.EqualTo (0.0d), "TimeOffset"); Assert.That (ec.RepeatCount, Is.EqualTo (0.0f), "RepeatCount"); Assert.That (ec.RepeatDuration, Is.EqualTo (0.0d), "RepeatDuration"); - Assert.False (ec.AutoReverses, "AutoReverses"); + Assert.That (ec.AutoReverses, Is.False, "AutoReverses"); Assert.That (ec.FillMode, Is.EqualTo ("removed"), "FillMode"); } } diff --git a/tests/monotouch-test/CoreAnimation/LayerTest.cs b/tests/monotouch-test/CoreAnimation/LayerTest.cs index ed7f174462d7..5cf0be59a801 100644 --- a/tests/monotouch-test/CoreAnimation/LayerTest.cs +++ b/tests/monotouch-test/CoreAnimation/LayerTest.cs @@ -23,11 +23,11 @@ public class LayerTest { public void Mask () { using (CALayer layer = new CALayer ()) { - Assert.Null (layer.Mask, "Mask/default"); + Assert.That (layer.Mask, Is.Null, "Mask/default"); layer.Mask = new CALayer (); - Assert.NotNull (layer.Mask, "Mask/assigned"); + Assert.That (layer.Mask, Is.Not.Null, "Mask/assigned"); layer.Mask = null; - Assert.Null (layer.Mask, "Mask/nullable"); + Assert.That (layer.Mask, Is.Null, "Mask/nullable"); } } @@ -36,9 +36,9 @@ public void CAActionTest () { // bug 2441 CAActionTestClass obj = new CAActionTestClass (); - Assert.IsNull (obj.ActionForKey ("animation"), "a"); - Assert.IsNull (obj.Actions, "b"); - Assert.IsNull (CAActionTestClass.DefaultActionForKey ("animation"), "c"); + Assert.That (obj.ActionForKey ("animation"), Is.Null, "a"); + Assert.That (obj.Actions, Is.Null, "b"); + Assert.That (CAActionTestClass.DefaultActionForKey ("animation"), Is.Null, "c"); var animationKey = new NSString ("animation"); var basicAnimationKey = new NSString ("basicAnimation"); @@ -51,8 +51,8 @@ public void CAActionTest () Assert.That (obj.ActionForKey ("animation") == dict [animationKey], "e"); Assert.That (obj.ActionForKey ("basicAnimation") == dict [basicAnimationKey], "f"); - Assert.IsNull (CAActionTestClass.DefaultActionForKey ("animation"), "g"); - Assert.IsNull (CALayer.DefaultActionForKey ("animation"), "h"); + Assert.That (CAActionTestClass.DefaultActionForKey ("animation"), Is.Null, "g"); + Assert.That (CALayer.DefaultActionForKey ("animation"), Is.Null, "h"); } class CAActionTestClass : CALayer { @@ -63,8 +63,8 @@ class CAActionTestClass : CALayer { public void ConvertPoint () { using (CALayer layer = new CALayer ()) { - Assert.True (layer.ConvertPointFromLayer (CGPoint.Empty, null).IsEmpty, "From/Empty/null"); - Assert.True (layer.ConvertPointToLayer (CGPoint.Empty, null).IsEmpty, "To/Empty/null"); + Assert.That (layer.ConvertPointFromLayer (CGPoint.Empty, null).IsEmpty, Is.True, "From/Empty/null"); + Assert.That (layer.ConvertPointToLayer (CGPoint.Empty, null).IsEmpty, Is.True, "To/Empty/null"); } } @@ -72,8 +72,8 @@ public void ConvertPoint () public void ConvertRect () { using (CALayer layer = new CALayer ()) { - Assert.True (layer.ConvertRectFromLayer (CGRect.Empty, null).IsEmpty, "From/Empty/null"); - Assert.True (layer.ConvertRectToLayer (CGRect.Empty, null).IsEmpty, "To/Empty/null"); + Assert.That (layer.ConvertRectFromLayer (CGRect.Empty, null).IsEmpty, Is.True, "From/Empty/null"); + Assert.That (layer.ConvertRectToLayer (CGRect.Empty, null).IsEmpty, Is.True, "To/Empty/null"); } } @@ -91,9 +91,9 @@ public void AddAnimation () { using (var layer = new CALayer ()) { var animation = new CABasicAnimation (); - Assert.IsNull (layer.AnimationForKey ("key"), "#key A"); + Assert.That (layer.AnimationForKey ("key"), Is.Null, "#key A"); layer.AddAnimation (animation, "key"); - Assert.IsNotNull (layer.AnimationForKey ("key"), "#key B"); + Assert.That (layer.AnimationForKey ("key"), Is.Not.Null, "#key B"); } } @@ -122,7 +122,7 @@ public void TestBug26532 () GC.Collect (); foreach (var slayer in layer.Sublayers.OfType ()) { - Assert.AreEqual ("42", slayer.Secret); + Assert.That (slayer.Secret, Is.EqualTo ("42")); } foreach (var slayer in layer.Sublayers.OfType ()) @@ -142,7 +142,7 @@ public void TestBug26532 () NSRunLoop.Main.RunUntil (NSDate.Now.AddSeconds (0.05)); } - Assert.IsNull (ex, "Exceptions"); + Assert.That (ex, Is.Null, "Exceptions"); Assert.That (TextLayersDisposed, Is.AtLeast (layerCount / 2), "disposed text layers"); } diff --git a/tests/monotouch-test/CoreAnimation/ShapeLayerTest.cs b/tests/monotouch-test/CoreAnimation/ShapeLayerTest.cs index c68894fd83db..0139d979d133 100644 --- a/tests/monotouch-test/CoreAnimation/ShapeLayerTest.cs +++ b/tests/monotouch-test/CoreAnimation/ShapeLayerTest.cs @@ -25,23 +25,23 @@ public class ShapeLayerTest { public void NullableProperties () { var sl = new CAShapeLayer (); - Assert.NotNull (sl.FillColor, "FillColor"); + Assert.That (sl.FillColor, Is.Not.Null, "FillColor"); sl.FillColor = null; - Assert.Null (sl.Path, "Path"); + Assert.That (sl.Path, Is.Null, "Path"); sl.Path = null; - Assert.Null (sl.LineDashPattern, "LineDashPattern"); + Assert.That (sl.LineDashPattern, Is.Null, "LineDashPattern"); sl.LineDashPattern = null; - Assert.Null (sl.StrokeColor, "StrokeColor"); + Assert.That (sl.StrokeColor, Is.Null, "StrokeColor"); sl.StrokeColor = null; sl.FillColor = TestRuntime.GetCGColor (UIColor.Black); - Assert.NotNull (sl.FillColor, "FillColor"); + Assert.That (sl.FillColor, Is.Not.Null, "FillColor"); sl.Path = new CGPath (); - Assert.NotNull (sl.Path, "Path"); + Assert.That (sl.Path, Is.Not.Null, "Path"); sl.LineDashPattern = new [] { new NSNumber (5), new NSNumber (10) }; - Assert.NotNull (sl.LineDashPattern, "LineDashPattern"); + Assert.That (sl.LineDashPattern, Is.Not.Null, "LineDashPattern"); sl.StrokeColor = TestRuntime.GetCGColor (UIColor.White); - Assert.NotNull (sl.StrokeColor, "StrokeColor"); + Assert.That (sl.StrokeColor, Is.Not.Null, "StrokeColor"); } } } diff --git a/tests/monotouch-test/CoreAnimation/TransactionTest.cs b/tests/monotouch-test/CoreAnimation/TransactionTest.cs index 53d914050964..0747d5239ff1 100644 --- a/tests/monotouch-test/CoreAnimation/TransactionTest.cs +++ b/tests/monotouch-test/CoreAnimation/TransactionTest.cs @@ -19,7 +19,7 @@ public class TransactionTest { public void CompletionBlock_Null () { CATransaction.CompletionBlock = null; - Assert.Null (CATransaction.CompletionBlock, "CompletionBlock"); + Assert.That (CATransaction.CompletionBlock, Is.Null, "CompletionBlock"); } [Test] @@ -28,7 +28,7 @@ public void AnimationTimingFunction_Null () // NULL is not specified in Apple doc // but since it's the default value it makes sense to be able to set it back CATransaction.AnimationTimingFunction = null; - Assert.Null (CATransaction.AnimationTimingFunction, "AnimationTimingFunction"); + Assert.That (CATransaction.AnimationTimingFunction, Is.Null, "AnimationTimingFunction"); } } } diff --git a/tests/monotouch-test/CoreBluetooth/CentralManagerTest.cs b/tests/monotouch-test/CoreBluetooth/CentralManagerTest.cs index 725f0733e1f0..15c0185d099c 100644 --- a/tests/monotouch-test/CoreBluetooth/CentralManagerTest.cs +++ b/tests/monotouch-test/CoreBluetooth/CentralManagerTest.cs @@ -84,7 +84,7 @@ public void TearDown () public void Constructors () { // Manager creates it, we'll simply check it has a non-null delegate - Assert.NotNull (mgr.Delegate, "Delegate"); + Assert.That (mgr.Delegate, Is.Not.Null, "Delegate"); } [Test] diff --git a/tests/monotouch-test/CoreBluetooth/PeerTest.cs b/tests/monotouch-test/CoreBluetooth/PeerTest.cs index 5b7397579da2..5ed838ead0a8 100644 --- a/tests/monotouch-test/CoreBluetooth/PeerTest.cs +++ b/tests/monotouch-test/CoreBluetooth/PeerTest.cs @@ -24,7 +24,7 @@ public void Constructor () // crash at dispose time in beta 4 (and 5) // the type is undocumented but I think it's should be abstract (not user creatable) // using (var p = new CBPeer ()) { - // Assert.NotNull (p); + // Assert.That (p, Is.Not.Null); // } } } diff --git a/tests/monotouch-test/CoreBluetooth/PeripheralScanningOptionsTest.cs b/tests/monotouch-test/CoreBluetooth/PeripheralScanningOptionsTest.cs index cc8edbe775bb..bf42642dbd03 100644 --- a/tests/monotouch-test/CoreBluetooth/PeripheralScanningOptionsTest.cs +++ b/tests/monotouch-test/CoreBluetooth/PeripheralScanningOptionsTest.cs @@ -20,7 +20,7 @@ public void Defaults () { var options = new PeripheralScanningOptions (); Assert.That (options.Dictionary.Count, Is.EqualTo ((nuint) 0), "Count"); - Assert.False (options.AllowDuplicatesKey, "AllowDuplicatesKey"); + Assert.That (options.AllowDuplicatesKey, Is.False, "AllowDuplicatesKey"); } [Test] @@ -30,7 +30,7 @@ public void AllowDuplicatesKey_True () AllowDuplicatesKey = true }; Assert.That (options.Dictionary.Count, Is.EqualTo ((nuint) 1), "Count"); - Assert.True (options.AllowDuplicatesKey, "AllowDuplicatesKey"); + Assert.That (options.AllowDuplicatesKey, Is.True, "AllowDuplicatesKey"); } [Test] @@ -40,7 +40,7 @@ public void AllowDuplicatesKey_False () AllowDuplicatesKey = false }; Assert.That (options.Dictionary.Count, Is.EqualTo ((nuint) 1), "Count"); - Assert.False (options.AllowDuplicatesKey, "AllowDuplicatesKey"); + Assert.That (options.AllowDuplicatesKey, Is.False, "AllowDuplicatesKey"); } } } diff --git a/tests/monotouch-test/CoreBluetooth/UuidTest.cs b/tests/monotouch-test/CoreBluetooth/UuidTest.cs index aa97e792aedf..2d9ddbdc5313 100644 --- a/tests/monotouch-test/CoreBluetooth/UuidTest.cs +++ b/tests/monotouch-test/CoreBluetooth/UuidTest.cs @@ -28,7 +28,7 @@ public void Roundtrip_16bits () { using (CBUUID uuid = CBUUID.FromString ("1234")) { Assert.That (uuid.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); - Assert.IsNotNull (uuid.Data, "Data"); + Assert.That (uuid.Data, Is.Not.Null, "Data"); var firstExpected = "Unknown (<1234>)"; var secondExpected = "1234"; Assert.That (uuid.Description, Is.EqualTo (firstExpected).Or.EqualTo (secondExpected), "Description"); @@ -45,7 +45,7 @@ public void Roundtrip_128bits () { using (CBUUID uuid = CBUUID.FromString ("12345678-90AB-CDEF-cafe-c80c20443d0b")) { Assert.That (uuid.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); - Assert.IsNotNull (uuid.Data, "Data"); + Assert.That (uuid.Data, Is.Not.Null, "Data"); var firstExpected = "Unknown (<12345678 90abcdef cafec80c 20443d0b>)"; var secondExpected = "12345678-90AB-CDEF-CAFE-C80C20443D0B"; Assert.That (uuid.Description, Is.EqualTo (firstExpected).Or.EqualTo (secondExpected), "Description"); @@ -97,25 +97,25 @@ public void Equality_PartialEquals () var guid = new byte [] { 0xaa, 0xbb }; using (var u1 = CBUUID.FromBytes (guid)) using (var u2 = CBUUID.FromBytes (guid)) { - Assert.True (u1.Equals ((object) u2), "Equals-1a"); - Assert.True (u1.Equals ((NSObject) u2), "Equals-1b"); - Assert.True (u1.Equals ((CBUUID) u2), "Equals-1b"); + Assert.That (u1.Equals ((object) u2), Is.True, "Equals-1a"); + Assert.That (u1.Equals ((NSObject) u2), Is.True, "Equals-1b"); + Assert.That (u1.Equals ((CBUUID) u2), Is.True, "Equals-1b"); Assert.That (u1.GetHashCode (), Is.EqualTo (u2.GetHashCode ()), "GetHashCode-1"); } using (var u1 = CBUUID.FromPartial (0x1234)) using (var u2 = CBUUID.FromPartial (0x1234)) { - Assert.True (u1.Equals ((object) u2), "Equals-2a"); - Assert.True (u1.Equals ((NSObject) u2), "Equals-2b"); - Assert.True (u1.Equals ((CBUUID) u2), "Equals-2b"); + Assert.That (u1.Equals ((object) u2), Is.True, "Equals-2a"); + Assert.That (u1.Equals ((NSObject) u2), Is.True, "Equals-2b"); + Assert.That (u1.Equals ((CBUUID) u2), Is.True, "Equals-2b"); Assert.That (u1.GetHashCode (), Is.EqualTo (u2.GetHashCode ()), "GetHashCode-2"); } using (var u1 = CBUUID.FromString ("1234")) using (var u2 = CBUUID.FromBytes (new byte [] { 0x12, 0x34 })) { - Assert.True (u1.Equals ((object) u2), "Equals-3a"); - Assert.True (u1.Equals ((NSObject) u2), "Equals-3b"); - Assert.True (u1.Equals ((CBUUID) u2), "Equals-3b"); + Assert.That (u1.Equals ((object) u2), Is.True, "Equals-3a"); + Assert.That (u1.Equals ((NSObject) u2), Is.True, "Equals-3b"); + Assert.That (u1.Equals ((CBUUID) u2), Is.True, "Equals-3b"); Assert.That (u1.GetHashCode (), Is.EqualTo (u2.GetHashCode ()), "GetHashCode-3"); } #if MONOMAC @@ -133,25 +133,25 @@ public void Equality_PartialEqualsFull () { using (var u1 = CBUUID.FromPartial (0x0127)) using (var u2 = MakeFull (0x01, 0x27)) { - Assert.True (u1.Equals ((object) u2), "Equals-1a"); - Assert.True (u1.Equals ((NSObject) u2), "Equals-1b"); - Assert.True (u1.Equals ((CBUUID) u2), "Equals-1b"); + Assert.That (u1.Equals ((object) u2), Is.True, "Equals-1a"); + Assert.That (u1.Equals ((NSObject) u2), Is.True, "Equals-1b"); + Assert.That (u1.Equals ((CBUUID) u2), Is.True, "Equals-1b"); Assert.That (u1.GetHashCode (), Is.EqualTo (u2.GetHashCode ()), "GetHashCode-1"); } using (var u1 = CBUUID.FromBytes (new byte [] { 0xab, 0xcd })) using (var u2 = MakeFull (0xab, 0xcd)) { - Assert.True (u1.Equals ((object) u2), "Equals-2a"); - Assert.True (u1.Equals ((NSObject) u2), "Equals-2b"); - Assert.True (u1.Equals ((CBUUID) u2), "Equals-2b"); + Assert.That (u1.Equals ((object) u2), Is.True, "Equals-2a"); + Assert.That (u1.Equals ((NSObject) u2), Is.True, "Equals-2b"); + Assert.That (u1.Equals ((CBUUID) u2), Is.True, "Equals-2b"); Assert.That (u1.GetHashCode (), Is.EqualTo (u2.GetHashCode ()), "GetHashCode-2"); } using (var u1 = CBUUID.FromString ("1234")) using (var u2 = CBUUID.FromString ("00001234-0000-1000-8000-00805f9b34fb")) { - Assert.True (u1.Equals ((object) u2), "Equals-3a"); - Assert.True (u1.Equals ((NSObject) u2), "Equals-3b"); - Assert.True (u1.Equals ((CBUUID) u2), "Equals-3b"); + Assert.That (u1.Equals ((object) u2), Is.True, "Equals-3a"); + Assert.That (u1.Equals ((NSObject) u2), Is.True, "Equals-3b"); + Assert.That (u1.Equals ((CBUUID) u2), Is.True, "Equals-3b"); Assert.That (u1.GetHashCode (), Is.EqualTo (u2.GetHashCode ()), "GetHashCode-3"); } #if MONOMAC diff --git a/tests/monotouch-test/CoreData/AttributeDescriptionTest.cs b/tests/monotouch-test/CoreData/AttributeDescriptionTest.cs index 4406a88bd688..20973f10c150 100644 --- a/tests/monotouch-test/CoreData/AttributeDescriptionTest.cs +++ b/tests/monotouch-test/CoreData/AttributeDescriptionTest.cs @@ -29,7 +29,7 @@ public void DefaultValue () using (var ad = new NSAttributeDescription ()) using (var o = new NSObject ()) { ad.DefaultValue = o; - Assert.AreSame (o, ad.DefaultValue, "DefaultValue"); + Assert.That (ad.DefaultValue, Is.SameAs (o), "DefaultValue"); } } @@ -37,10 +37,9 @@ public void DefaultValue () public void GetSetRenamingIdentifier () { using (var ad = new NSAttributeDescription ()) { - Assert.IsNull (ad.RenamingIdentifier, "An unset RenamingIdentifier should be null."); + Assert.That (ad.RenamingIdentifier, Is.Null, "An unset RenamingIdentifier should be null."); ad.RenamingIdentifier = "Foo"; - Assert.AreEqual ("Foo", ad.RenamingIdentifier, - "RenamingIndentifier was not corrently set."); + Assert.That (ad.RenamingIdentifier, Is.EqualTo ("Foo"), "RenamingIndentifier was not corrently set."); } } } diff --git a/tests/monotouch-test/CoreData/EntityDescriptionTest.cs b/tests/monotouch-test/CoreData/EntityDescriptionTest.cs index 0bf9bdce1a6f..f2002ed82b8f 100644 --- a/tests/monotouch-test/CoreData/EntityDescriptionTest.cs +++ b/tests/monotouch-test/CoreData/EntityDescriptionTest.cs @@ -16,8 +16,8 @@ public void UniquenessConstraints () // Default is an empty array, not null var defaultValue = entity.UniquenessConstraints; - Assert.IsNotNull (defaultValue, "default not null"); - Assert.AreEqual (0, defaultValue!.Length, "default empty"); + Assert.That (defaultValue, Is.Not.Null, "default not null"); + Assert.That (defaultValue!.Length, Is.EqualTo (0), "default empty"); // Add attributes so the entity knows about these property names using var nameAttr = new NSAttributeDescription { Name = "name", AttributeType = NSAttributeType.String }; @@ -32,10 +32,10 @@ public void UniquenessConstraints () entity.UniquenessConstraints = constraints; var result = entity.UniquenessConstraints; - Assert.IsNotNull (result, "result"); - Assert.AreEqual (2, result!.Length, "outer length"); - Assert.AreEqual (2, result [0].Length, "constraint0 length"); - Assert.AreEqual (1, result [1].Length, "constraint1 length"); + Assert.That (result, Is.Not.Null, "result"); + Assert.That (result!.Length, Is.EqualTo (2), "outer length"); + Assert.That (result [0].Length, Is.EqualTo (2), "constraint0 length"); + Assert.That (result [1].Length, Is.EqualTo (1), "constraint1 length"); } } } diff --git a/tests/monotouch-test/CoreData/ExpressionDescriptionTest.cs b/tests/monotouch-test/CoreData/ExpressionDescriptionTest.cs index 9a09f0ee1287..0218c0b5da62 100644 --- a/tests/monotouch-test/CoreData/ExpressionDescriptionTest.cs +++ b/tests/monotouch-test/CoreData/ExpressionDescriptionTest.cs @@ -18,9 +18,9 @@ public void GetSetExpression () { using (var exp = new NSExpressionDescription ()) { exp.Name = "Test"; - Assert.IsNull (exp.Expression, "An unset Expression should be null."); + Assert.That (exp.Expression, Is.Null, "An unset Expression should be null."); exp.Expression = new NSExpression (NSExpressionType.Block); - Assert.IsNotNull (exp.Expression, "Expression was not correctly set."); + Assert.That (exp.Expression, Is.Not.Null, "Expression was not correctly set."); } } @@ -29,11 +29,9 @@ public void GetSetResultType () { using (var exp = new NSExpressionDescription ()) { exp.Name = "Test"; - Assert.AreEqual (exp.ResultType, NSAttributeType.Undefined, - "The default value of an unset ResultType should be 'Undefined'"); + Assert.That (NSAttributeType.Undefined, Is.EqualTo (exp.ResultType), "The default value of an unset ResultType should be 'Undefined'"); exp.ResultType = NSAttributeType.Boolean; - Assert.AreEqual (NSAttributeType.Boolean, exp.ResultType, - "ResultType was not correctly set."); + Assert.That (exp.ResultType, Is.EqualTo (NSAttributeType.Boolean), "ResultType was not correctly set."); } } } diff --git a/tests/monotouch-test/CoreData/FetchRequestExpressionTest.cs b/tests/monotouch-test/CoreData/FetchRequestExpressionTest.cs index 2ade5dbe0ed2..1c94b579d051 100644 --- a/tests/monotouch-test/CoreData/FetchRequestExpressionTest.cs +++ b/tests/monotouch-test/CoreData/FetchRequestExpressionTest.cs @@ -21,7 +21,7 @@ public void GetRequest () using (var exp = new NSExpression (NSExpressionType.Block)) using (var context = new NSExpression (NSExpressionType.EvaluatedObject)) using (var fetch = NSFetchRequestExpression.FromFetch (exp, context, false)) - Assert.NotNull (fetch.Request); + Assert.That (fetch.Request, Is.Not.Null); } [Test] @@ -30,7 +30,7 @@ public void GetContext () using (var exp = new NSExpression (NSExpressionType.Block)) using (var context = new NSExpression (NSExpressionType.EvaluatedObject)) using (var fetch = NSFetchRequestExpression.FromFetch (exp, context, false)) - Assert.NotNull (fetch.Context); + Assert.That (fetch.Context, Is.Not.Null); } [Test] @@ -39,12 +39,12 @@ public void GetIsCountOnly () using (var exp = new NSExpression (NSExpressionType.Block)) using (var context = new NSExpression (NSExpressionType.EvaluatedObject)) using (var fetch = NSFetchRequestExpression.FromFetch (exp, context, false)) - Assert.IsFalse (fetch.IsCountOnly, "IsCountOnly was not correctly set to false."); + Assert.That (fetch.IsCountOnly, Is.False, "IsCountOnly was not correctly set to false."); using (var exp = new NSExpression (NSExpressionType.Block)) using (var context = new NSExpression (NSExpressionType.EvaluatedObject)) using (var fetch = NSFetchRequestExpression.FromFetch (exp, context, true)) - Assert.IsTrue (fetch.IsCountOnly, "IsCountOnly was not correctly set to true."); + Assert.That (fetch.IsCountOnly, Is.True, "IsCountOnly was not correctly set to true."); } } } diff --git a/tests/monotouch-test/CoreData/FetchRequestTest.cs b/tests/monotouch-test/CoreData/FetchRequestTest.cs index 989c968457b3..2262617a2f32 100644 --- a/tests/monotouch-test/CoreData/FetchRequestTest.cs +++ b/tests/monotouch-test/CoreData/FetchRequestTest.cs @@ -19,25 +19,25 @@ public class FetchRequestTest { public void DefaultValues () { using (var fr = new NSFetchRequest ()) { - Assert.Null (fr.AffectedStores, "AffectedStores"); - Assert.Null (fr.Entity, "Entity"); - Assert.Null (fr.EntityName, "EntityName"); + Assert.That (fr.AffectedStores, Is.Null, "AffectedStores"); + Assert.That (fr.Entity, Is.Null, "Entity"); + Assert.That (fr.EntityName, Is.Null, "EntityName"); Assert.That (fr.FetchBatchSize, Is.EqualTo ((nint) 0), "FetchBatchSize"); Assert.That (fr.FetchLimit, Is.EqualTo ((nuint) 0), "FetchLimit"); Assert.That (fr.FetchOffset, Is.EqualTo ((nuint) 0), "FetchOffset"); - Assert.Null (fr.HavingPredicate, "HavingPredicate"); - Assert.True (fr.IncludesPendingChanges, "IncludesPendingChanges"); - Assert.True (fr.IncludesPropertyValues, "IncludesPropertyValues"); - Assert.True (fr.IncludesSubentities, "IncludesSubentities"); - Assert.Null (fr.Predicate, "Predicate"); - Assert.Null (fr.PropertiesToFetch, "PropertiesToFetch"); - Assert.Null (fr.PropertiesToGroupBy, "PropertiesToGroupBy"); - Assert.Null (fr.RelationshipKeyPathsForPrefetching, "RelationshipKeyPathsForPrefetching"); + Assert.That (fr.HavingPredicate, Is.Null, "HavingPredicate"); + Assert.That (fr.IncludesPendingChanges, Is.True, "IncludesPendingChanges"); + Assert.That (fr.IncludesPropertyValues, Is.True, "IncludesPropertyValues"); + Assert.That (fr.IncludesSubentities, Is.True, "IncludesSubentities"); + Assert.That (fr.Predicate, Is.Null, "Predicate"); + Assert.That (fr.PropertiesToFetch, Is.Null, "PropertiesToFetch"); + Assert.That (fr.PropertiesToGroupBy, Is.Null, "PropertiesToGroupBy"); + Assert.That (fr.RelationshipKeyPathsForPrefetching, Is.Null, "RelationshipKeyPathsForPrefetching"); Assert.That (fr.ResultType, Is.EqualTo (NSFetchRequestResultType.ManagedObject), "ResultType"); - Assert.False (fr.ReturnsDistinctResults, "ReturnsDistinctResults"); - Assert.True (fr.ReturnsObjectsAsFaults, "ReturnsObjectsAsFaults"); - Assert.False (fr.ShouldRefreshRefetchedObjects, "ShouldRefreshRefetchedObjects"); - Assert.Null (fr.SortDescriptors, "SortDescriptors"); + Assert.That (fr.ReturnsDistinctResults, Is.False, "ReturnsDistinctResults"); + Assert.That (fr.ReturnsObjectsAsFaults, Is.True, "ReturnsObjectsAsFaults"); + Assert.That (fr.ShouldRefreshRefetchedObjects, Is.False, "ShouldRefreshRefetchedObjects"); + Assert.That (fr.SortDescriptors, Is.Null, "SortDescriptors"); } } @@ -48,7 +48,7 @@ public void CtorString () Assert.That (fr.EntityName, Is.EqualTo ("entityName"), "EntityName"); // Entity is invalid (and throws) so we do not check it - except to see if we can set it to null fr.Entity = null; - Assert.Null (fr.Entity, "Entity"); + Assert.That (fr.Entity, Is.Null, "Entity"); } } diff --git a/tests/monotouch-test/CoreData/FetchedResultsControllerTest.cs b/tests/monotouch-test/CoreData/FetchedResultsControllerTest.cs index fff9593997f5..97e4ce269e0d 100644 --- a/tests/monotouch-test/CoreData/FetchedResultsControllerTest.cs +++ b/tests/monotouch-test/CoreData/FetchedResultsControllerTest.cs @@ -29,8 +29,8 @@ public void Default () { using (NSFetchedResultsController frc = new NSFetchedResultsController ()) { NSError e; - Assert.False (frc.PerformFetch (out e), "PerformFetch"); - Assert.Null (e, "NSError"); + Assert.That (frc.PerformFetch (out e), Is.False, "PerformFetch"); + Assert.That (e, Is.Null, "NSError"); } } @@ -45,7 +45,7 @@ public void PerformFetch_Minimal () r.Entity = new NSEntityDescription (); using (NSFetchedResultsController frc = new NSFetchedResultsController (r, c, null, null)) { NSError e; - Assert.False (frc.PerformFetch (out e), "PerformFetch"); + Assert.That (frc.PerformFetch (out e), Is.False, "PerformFetch"); } } } diff --git a/tests/monotouch-test/CoreData/ManagedObjectContextTest.cs b/tests/monotouch-test/CoreData/ManagedObjectContextTest.cs index 76bcfdf805cf..d471502f9890 100644 --- a/tests/monotouch-test/CoreData/ManagedObjectContextTest.cs +++ b/tests/monotouch-test/CoreData/ManagedObjectContextTest.cs @@ -19,18 +19,18 @@ public class ManagedObjectContextTest { void Default (NSManagedObjectContext moc) { Assert.That (moc.DeletedObjects.Count, Is.EqualTo ((nuint) 0), "DeletedObjects"); - Assert.False (moc.HasChanges, "HasChanges"); + Assert.That (moc.HasChanges, Is.False, "HasChanges"); Assert.That (moc.InsertedObjects.Count, Is.EqualTo ((nuint) 0), "InsertedObjects"); Assert.That (moc.MergePolicy, Is.Not.EqualTo (IntPtr.Zero), "MergePolicy"); - Assert.Null (moc.ParentContext, "ParentContext"); - Assert.Null (moc.PersistentStoreCoordinator, "PersistentStoreCoordinator"); + Assert.That (moc.ParentContext, Is.Null, "ParentContext"); + Assert.That (moc.PersistentStoreCoordinator, Is.Null, "PersistentStoreCoordinator"); Assert.That (moc.RegisteredObjects.Count, Is.EqualTo ((nuint) 0), "RegisteredObjects"); - Assert.False (moc.RetainsRegisteredObjects, "RetainsRegisteredObjects"); + Assert.That (moc.RetainsRegisteredObjects, Is.False, "RetainsRegisteredObjects"); Assert.That (moc.StalenessInterval, Is.EqualTo (-1), "StalenessInterval"); if (TestRuntime.CheckSystemVersion (ApplePlatform.MacOSX, 10, 12, throwIfOtherPlatform: false)) - Assert.Null (moc.UndoManager, "UndoManager"); + Assert.That (moc.UndoManager, Is.Null, "UndoManager"); else - Assert.NotNull (moc.UndoManager, "UndoManager"); + Assert.That (moc.UndoManager, Is.Not.Null, "UndoManager"); Assert.That (moc.UpdatedObjects.Count, Is.EqualTo ((nuint) 0), "UpdatedObjects"); Assert.That (moc.UserInfo.Count, Is.EqualTo ((nuint) 0), "UserInfo"); } diff --git a/tests/monotouch-test/CoreData/ManagedObjectModelTest.cs b/tests/monotouch-test/CoreData/ManagedObjectModelTest.cs index 940bc15fa7ee..a4cb9e9772e2 100644 --- a/tests/monotouch-test/CoreData/ManagedObjectModelTest.cs +++ b/tests/monotouch-test/CoreData/ManagedObjectModelTest.cs @@ -19,7 +19,7 @@ void Default (NSManagedObjectModel moc) { Assert.That (moc.EntitiesByName.Count, Is.EqualTo ((nuint) 0), "EntitiesByName"); Assert.That (moc.Configurations.Length, Is.EqualTo (0), "Configurations"); - Assert.Null (moc.LocalizationDictionary, "LocalizationDictionary"); + Assert.That (moc.LocalizationDictionary, Is.Null, "LocalizationDictionary"); Assert.That (moc.FetchRequestTemplatesByName.Count, Is.EqualTo ((nuint) 0), "FetchRequestTemplatesByName"); Assert.That (moc.VersionIdentifiers.Count, Is.EqualTo ((nuint) 0), "VersionIdentifiers"); Assert.That (moc.EntityVersionHashesByName.Count, Is.EqualTo ((nuint) 0), "EntityVersionHashesByName"); @@ -29,7 +29,7 @@ void Default (NSManagedObjectModel moc) public void IsConfiguration_Null () { using (var moc = new NSManagedObjectModel ()) { - Assert.IsFalse (moc.IsConfigurationCompatibleWithStoreMetadata (null, new NSDictionary ()), "IsConfiguration"); + Assert.That (moc.IsConfigurationCompatibleWithStoreMetadata (null, new NSDictionary ()), Is.False, "IsConfiguration"); Default (moc); } } diff --git a/tests/monotouch-test/CoreData/NSPersistentStoreCoordinatorTest.cs b/tests/monotouch-test/CoreData/NSPersistentStoreCoordinatorTest.cs index bdb9355d09fa..a7ac3b0ba6af 100644 --- a/tests/monotouch-test/CoreData/NSPersistentStoreCoordinatorTest.cs +++ b/tests/monotouch-test/CoreData/NSPersistentStoreCoordinatorTest.cs @@ -70,7 +70,7 @@ public void GetManagedObjectId () managedObjectModel.SetEntities (managedObjectModel.Entities, String.Empty); using var psc = new NSPersistentStoreCoordinator (managedObjectModel); - Assert.IsNull (psc.GetManagedObjectId ("magnitude"), "GetManagedObjectId"); + Assert.That (psc.GetManagedObjectId ("magnitude"), Is.Null, "GetManagedObjectId"); } } } diff --git a/tests/monotouch-test/CoreData/PropertyDescriptionTest.cs b/tests/monotouch-test/CoreData/PropertyDescriptionTest.cs index 288541e917e7..f4961c1b0bd1 100644 --- a/tests/monotouch-test/CoreData/PropertyDescriptionTest.cs +++ b/tests/monotouch-test/CoreData/PropertyDescriptionTest.cs @@ -18,9 +18,9 @@ public void WeakFramework () public void GetSetName () { using (var pd = new NSPropertyDescription ()) { - Assert.IsNull (pd.Name, "An unset Name should be null"); + Assert.That (pd.Name, Is.Null, "An unset Name should be null"); pd.Name = "Name"; - Assert.AreEqual ("Name", pd.Name, "Name was not corretly set."); + Assert.That (pd.Name, Is.EqualTo ("Name"), "Name was not corretly set."); } } @@ -28,9 +28,9 @@ public void GetSetName () public void GetSetOpcional () { using (var pd = new NSPropertyDescription ()) { - Assert.IsTrue (pd.Optional, "A property should be Optional as default."); + Assert.That (pd.Optional, Is.True, "A property should be Optional as default."); pd.Optional = false; - Assert.IsFalse (pd.Optional, "Optional was not correctly set."); + Assert.That (pd.Optional, Is.False, "Optional was not correctly set."); } } @@ -38,9 +38,9 @@ public void GetSetOpcional () public void GetSetTransient () { using (var pd = new NSPropertyDescription ()) { - Assert.IsFalse (pd.Transient, "A property should not be Transient by default."); + Assert.That (pd.Transient, Is.False, "A property should not be Transient by default."); pd.Transient = true; - Assert.IsTrue (pd.Transient, "Transient was not correctly set."); + Assert.That (pd.Transient, Is.True, "Transient was not correctly set."); } } @@ -48,11 +48,9 @@ public void GetSetTransient () public void GetSetRenamingIdentifier () { using (var pd = new NSPropertyDescription ()) { - Assert.IsNull (pd.RenamingIdentifier, - "A property by default should have the RenamingIndentifier set to null"); + Assert.That (pd.RenamingIdentifier, Is.Null, "A property by default should have the RenamingIndentifier set to null"); pd.RenamingIdentifier = "Foo"; - Assert.AreEqual ("Foo", pd.RenamingIdentifier, - "RenamingIdentifier was not correctly set."); + Assert.That (pd.RenamingIdentifier, Is.EqualTo ("Foo"), "RenamingIdentifier was not correctly set."); } } } diff --git a/tests/monotouch-test/CoreFoundation/ArrayTest.cs b/tests/monotouch-test/CoreFoundation/ArrayTest.cs index 2fa248478a6a..56ebf60c12ec 100644 --- a/tests/monotouch-test/CoreFoundation/ArrayTest.cs +++ b/tests/monotouch-test/CoreFoundation/ArrayTest.cs @@ -11,26 +11,26 @@ public class ArrayTest { void VerifyArray (CFArray? a) { - Assert.IsNotNull (a, "NotNull"); - Assert.AreEqual ((nint) 3, a.Count, "Count"); + Assert.That (a, Is.Not.Null, "NotNull"); + Assert.That (a.Count, Is.EqualTo ((nint) 3), "Count"); for (var i = 0; i < a.Count; i++) - Assert.AreEqual (TestArray [i], (string) CFString.FromHandle (a.GetValue (i), false), i.ToString ()); + Assert.That ((string) CFString.FromHandle (a.GetValue (i), false), Is.EqualTo (TestArray [i]), i.ToString ()); } void VerifyArray (NSString []? a) { - Assert.IsNotNull (a, "NotNull"); - Assert.AreEqual (3, a.Length, "Count"); + Assert.That (a, Is.Not.Null, "NotNull"); + Assert.That (a.Length, Is.EqualTo (3), "Count"); for (var i = 0; i < a.Length; i++) - Assert.AreEqual (TestArray [i], (string) a [i], i.ToString ()); + Assert.That ((string) a [i], Is.EqualTo (TestArray [i]), i.ToString ()); } void VerifyArray (string []? a) { - Assert.IsNotNull (a, "NotNull"); - Assert.AreEqual (3, a.Length, "Count"); + Assert.That (a, Is.Not.Null, "NotNull"); + Assert.That (a.Length, Is.EqualTo (3), "Count"); for (var i = 0; i < a.Length; i++) - Assert.AreEqual (TestArray [i], (string) a [i], i.ToString ()); + Assert.That ((string) a [i], Is.EqualTo (TestArray [i]), i.ToString ()); } [Test] @@ -39,7 +39,7 @@ public void CreateTest () var handle = CFArray.Create (TestArray); using var a = Runtime.GetINativeObject (handle, true); VerifyArray (a); - Assert.AreEqual ((nint) 1, CFGetRetainCount (handle), "RC"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo ((nint) 1), "RC"); } [Test] @@ -47,7 +47,7 @@ public void FromStringsTest () { using var a = CFArray.FromStrings (TestArray); VerifyArray (a); - Assert.AreEqual ((nint) 1, CFGetRetainCount (a.Handle), "RC"); + Assert.That (CFGetRetainCount (a.Handle), Is.EqualTo ((nint) 1), "RC"); } [Test] @@ -55,23 +55,23 @@ public void CreateWithNullItemsTest () { var handle = CFArray.Create (new string? [] { "a", null, "b" }); using var a = Runtime.GetINativeObject (handle, true); - Assert.IsNotNull (a, "NotNull"); - Assert.AreEqual ((nint) 3, a!.Count, "Count"); - Assert.AreEqual ("a", CFString.FromHandle (a.GetValue (0), false), "0"); - Assert.AreEqual (NSNull.Null.Handle, a.GetValue (1), "1 - null item is CFNull"); - Assert.AreEqual ("b", CFString.FromHandle (a.GetValue (2), false), "2"); - Assert.AreEqual ((nint) 1, CFGetRetainCount (handle), "RC"); + Assert.That (a, Is.Not.Null, "NotNull"); + Assert.That (a!.Count, Is.EqualTo ((nint) 3), "Count"); + Assert.That (CFString.FromHandle (a.GetValue (0), false), Is.EqualTo ("a"), "0"); + Assert.That (a.GetValue (1), Is.EqualTo (NSNull.Null.Handle), "1 - null item is CFNull"); + Assert.That (CFString.FromHandle (a.GetValue (2), false), Is.EqualTo ("b"), "2"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo ((nint) 1), "RC"); } [Test] public void FromStringsWithNullItemsTest () { using var a = CFArray.FromStrings (new string? [] { "x", null, "y" }); - Assert.IsNotNull (a, "NotNull"); - Assert.AreEqual ((nint) 3, a.Count, "Count"); - Assert.AreEqual ("x", CFString.FromHandle (a.GetValue (0), false), "0"); - Assert.AreEqual (NSNull.Null.Handle, a.GetValue (1), "1 - null item is CFNull"); - Assert.AreEqual ("y", CFString.FromHandle (a.GetValue (2), false), "2"); + Assert.That (a, Is.Not.Null, "NotNull"); + Assert.That (a.Count, Is.EqualTo ((nint) 3), "Count"); + Assert.That (CFString.FromHandle (a.GetValue (0), false), Is.EqualTo ("x"), "0"); + Assert.That (a.GetValue (1), Is.EqualTo (NSNull.Null.Handle), "1 - null item is CFNull"); + Assert.That (CFString.FromHandle (a.GetValue (2), false), Is.EqualTo ("y"), "2"); } [Test] @@ -80,11 +80,11 @@ public void CreateWithIReadOnlyListTest () IReadOnlyList list = new List { "p", null, "q" }; var handle = CFArray.Create (list); using var a = Runtime.GetINativeObject (handle, true); - Assert.IsNotNull (a, "NotNull"); - Assert.AreEqual ((nint) 3, a!.Count, "Count"); - Assert.AreEqual ("p", CFString.FromHandle (a.GetValue (0), false), "0"); - Assert.AreEqual (NSNull.Null.Handle, a.GetValue (1), "1 - null item is CFNull"); - Assert.AreEqual ("q", CFString.FromHandle (a.GetValue (2), false), "2"); + Assert.That (a, Is.Not.Null, "NotNull"); + Assert.That (a!.Count, Is.EqualTo ((nint) 3), "Count"); + Assert.That (CFString.FromHandle (a.GetValue (0), false), Is.EqualTo ("p"), "0"); + Assert.That (a.GetValue (1), Is.EqualTo (NSNull.Null.Handle), "1 - null item is CFNull"); + Assert.That (CFString.FromHandle (a.GetValue (2), false), Is.EqualTo ("q"), "2"); } [Test] @@ -93,7 +93,7 @@ public void ArrayFromHandleTest () var handle = CFArray.Create (TestArray); var a = CFArray.ArrayFromHandle (handle); VerifyArray (a); - Assert.AreEqual ((nint) 1, CFGetRetainCount (handle), "RC"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo ((nint) 1), "RC"); CFRelease (handle); } @@ -104,7 +104,7 @@ public void ArrayFromHandleTest_bool_true () CFRetain (handle); var a = CFArray.ArrayFromHandle (handle, true); VerifyArray (a); - Assert.AreEqual ((nint) 1, CFGetRetainCount (handle), "RC"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo ((nint) 1), "RC"); CFRelease (handle); } @@ -114,7 +114,7 @@ public void ArrayFromHandleTest_bool_false () var handle = CFArray.Create (TestArray); var a = CFArray.ArrayFromHandle (handle, false); VerifyArray (a); - Assert.AreEqual ((nint) 1, CFGetRetainCount (handle), "RC"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo ((nint) 1), "RC"); CFRelease (handle); } @@ -124,7 +124,7 @@ public void ArrayFromHandleFuncTest () var handle = CFArray.Create (TestArray); var a = CFArray.ArrayFromHandleFunc (handle, (v) => CFString.FromHandle (v)); VerifyArray (a); - Assert.AreEqual ((nint) 1, CFGetRetainCount (handle), "RC"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo ((nint) 1), "RC"); CFRelease (handle); } @@ -135,7 +135,7 @@ public void ArrayFromHandleFuncTest_bool_true () CFRetain (handle); var a = CFArray.ArrayFromHandleFunc (handle, (v) => CFString.FromHandle (v), true); VerifyArray (a); - Assert.AreEqual ((nint) 1, CFGetRetainCount (handle), "RC"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo ((nint) 1), "RC"); CFRelease (handle); } @@ -145,7 +145,7 @@ public void ArrayFromHandleFuncTest_bool_false () var handle = CFArray.Create (TestArray); var a = CFArray.ArrayFromHandleFunc (handle, (v) => CFString.FromHandle (v), false); VerifyArray (a); - Assert.AreEqual ((nint) 1, CFGetRetainCount (handle), "RC"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo ((nint) 1), "RC"); CFRelease (handle); } diff --git a/tests/monotouch-test/CoreFoundation/BundleTest.cs b/tests/monotouch-test/CoreFoundation/BundleTest.cs index 69246f32ae6e..6e7cd189b4fe 100644 --- a/tests/monotouch-test/CoreFoundation/BundleTest.cs +++ b/tests/monotouch-test/CoreFoundation/BundleTest.cs @@ -15,10 +15,9 @@ public class BundleTest { public void TestGetAll () { var bundles = CFBundle.GetAll (); - Assert.IsTrue (bundles.Length > 0); + Assert.That (bundles.Length > 0, Is.True); foreach (CFBundle b in bundles) { - Assert.IsFalse (String.IsNullOrEmpty (b.Url.ToString ()), - String.Format ("Found bundle with null url and id {0}", b.Identifier)); + Assert.That (String.IsNullOrEmpty (b.Url.ToString ()), Is.False, String.Format ("Found bundle with null url and id {0}", b.Identifier)); } } @@ -26,7 +25,7 @@ public void TestGetAll () public void TestGetBundleIdMissing () { var bundle = CFBundle.Get ("????"); - Assert.IsNull (bundle); + Assert.That (bundle, Is.Null); } [Test] @@ -34,7 +33,7 @@ public void TestGetBundleId () { // grab all bundles and make sure we do get the correct ones using their id var bundles = CFBundle.GetAll (); - Assert.IsTrue (bundles.Length > 0); + Assert.That (bundles.Length > 0, Is.True); // There may be multiple apps providing the same bundle ID (the typical example is that we usually have multiple Xcodes installed) // So compute a map for bundle id -> bundle paths that's used in the second part here to verify the CFBundle.Get results. @@ -52,11 +51,10 @@ public void TestGetBundleId () var id = b.Identifier; if (!String.IsNullOrEmpty (id)) { var otherBundle = CFBundle.Get (id); - Assert.AreEqual (b.Info.Type, otherBundle.Info.Type, - String.Format ("Found bundle with diff type and id {0}", id)); + Assert.That (otherBundle.Info.Type, Is.EqualTo (b.Info.Type), String.Format ("Found bundle with diff type and id {0}", id)); var bPath = (string) ((NSString) b.Url.Path).ResolveSymlinksInPath (); var list = dict [id]; - Assert.That (list, Does.Contain (bPath), "None of the bundles for {0} matches the path {1}", id, bPath); + Assert.That (list, Does.Contain (bPath), $"None of the bundles for {id} matches the path {bPath}"); } } } @@ -73,8 +71,8 @@ public void TestGetMain () { var main = CFBundle.GetMain (); var expectedBundleId = "com.xamarin.monotouch-test"; - Assert.AreEqual (expectedBundleId, main.Identifier); - Assert.IsTrue (main.HasLoadedExecutable); + Assert.That (main.Identifier, Is.EqualTo (expectedBundleId)); + Assert.That (main.HasLoadedExecutable, Is.True); } [Test] @@ -136,7 +134,7 @@ public void TestSupportFilesDirectoryUrl () public void TestArchitectures () { var main = CFBundle.GetMain (); - Assert.IsTrue (main.Architectures.Length > 0); + Assert.That (main.Architectures.Length > 0, Is.True); } [Test] @@ -150,7 +148,7 @@ public void TestUrl () public void TestDevelopmentRegion () { var main = CFBundle.GetMain (); - Assert.IsTrue (String.IsNullOrEmpty (main.DevelopmentRegion)); + Assert.That (String.IsNullOrEmpty (main.DevelopmentRegion), Is.True); } [Test] @@ -161,7 +159,7 @@ public void TestLocalizations () var expected = new string [] { "Base", "en-AU", "en-UK", "es", "es-AR", "es-ES" }.OrderBy (v => v).ToArray (); - Assert.AreEqual (string.Join (";", expected), string.Join (";", localizations), "Localizations"); + Assert.That (string.Join (";", localizations), Is.EqualTo (string.Join (";", expected)), "Localizations"); } [Test] @@ -175,7 +173,7 @@ public void TestPreferredLocalizations () { var preferred = new string [] { "en", "es" }; var used = CFBundle.GetPreferredLocalizations (preferred); - Assert.IsTrue (used.Length > 0); + Assert.That (used.Length > 0, Is.True); foreach (var u in used) Assert.That (preferred, Contains.Item (u), u); } @@ -199,7 +197,7 @@ public void TestGetAuxiliaryExecutableUrlNull () { var main = CFBundle.GetMain (); var url = main.GetAuxiliaryExecutableUrl ("fake-exe"); - Assert.IsNull (url); + Assert.That (url, Is.Null); } [TestCase ("")] @@ -334,9 +332,9 @@ public void TestGetInfoDictionaryNull () public void TestGetInfoDictionary () { var main = CFBundle.GetMain (); - Assert.NotNull (main.Url, "Url"); + Assert.That (main.Url, Is.Not.Null, "Url"); var dict = CFBundle.GetInfoDictionary (main.Url); - Assert.NotNull (dict, "GetInfoDictionary"); + Assert.That (dict, Is.Not.Null, "GetInfoDictionary"); Assert.That (dict.Count, Is.GreaterThan ((nuint) 0), "Count"); } @@ -382,7 +380,7 @@ public void GetLocalizedString () break; } s = main.GetLocalizedString (key, defaultValue, tableName); - Assert.AreEqual (expectedValue, s, $"{tableName}/{key}"); + Assert.That (s, Is.EqualTo (expectedValue), $"{tableName}/{key}"); } // no matching table, so default value @@ -391,7 +389,7 @@ public void GetLocalizedString () key = "GoodMorning"; expectedValue = "default"; s = main.GetLocalizedString (key, defaultValue, tableName); - Assert.AreEqual (expectedValue, s, $"{tableName}/{key}"); + Assert.That (s, Is.EqualTo (expectedValue), $"{tableName}/{key}"); } tableName = "CustomTable"; @@ -418,7 +416,7 @@ public void GetLocalizedString () break; } s = main.GetLocalizedString (key, defaultValue, tableName); - Assert.AreEqual (expectedValue, s, key); + Assert.That (s, Is.EqualTo (expectedValue), key); }); } @@ -442,112 +440,112 @@ public void GetLocalizedStringWithLanguages () tableName = "CustomTable"; key = "Local Animal"; s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { }); - Assert.AreEqual ("Tiger of the Highlands", s, $"{tableName}/{key}:[]"); + Assert.That (s, Is.EqualTo ("Tiger of the Highlands"), $"{tableName}/{key}:[]"); // There's no en-US translation, so the en-UK one is picked instead s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "en-US" }); - Assert.AreEqual ("Tiger of the Highlands", s, $"{tableName}/{key}:en-US"); + Assert.That (s, Is.EqualTo ("Tiger of the Highlands"), $"{tableName}/{key}:en-US"); // There's no de-DE translation, so the en-UK one is picked instead s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "de-DE" }); - Assert.AreEqual ("Tiger of the Highlands", s, $"{tableName}/{key}:en-US"); + Assert.That (s, Is.EqualTo ("Tiger of the Highlands"), $"{tableName}/{key}:en-US"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "en-AU" }); - Assert.AreEqual ("Quokka", s, $"{tableName}/{key}:en-AU"); + Assert.That (s, Is.EqualTo ("Quokka"), $"{tableName}/{key}:en-AU"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "en-UK" }); - Assert.AreEqual ("Tiger of the Highlands", s, $"{tableName}/{key}:en-UK"); + Assert.That (s, Is.EqualTo ("Tiger of the Highlands"), $"{tableName}/{key}:en-UK"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-ES" }); - Assert.AreEqual ("Lince ibérico", s, $"{tableName}/{key}:es-ES"); + Assert.That (s, Is.EqualTo ("Lince ibérico"), $"{tableName}/{key}:es-ES"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-AR" }); - Assert.AreEqual ("Pato vapor cabeza blanca", s, $"{tableName}/{key}:es-AR"); + Assert.That (s, Is.EqualTo ("Pato vapor cabeza blanca"), $"{tableName}/{key}:es-AR"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es" }); - Assert.AreEqual ("Ocelote", s, $"{tableName}/{key}:es"); + Assert.That (s, Is.EqualTo ("Ocelote"), $"{tableName}/{key}:es"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-MX" }); - Assert.AreEqual ("Ocelote", s, $"{tableName}/{key}:es-MX"); + Assert.That (s, Is.EqualTo ("Ocelote"), $"{tableName}/{key}:es-MX"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-AR", "es-ES" }); - Assert.AreEqual ("Pato vapor cabeza blanca", s, $"{tableName}/{key}:es-AR;es-ES"); + Assert.That (s, Is.EqualTo ("Pato vapor cabeza blanca"), $"{tableName}/{key}:es-AR;es-ES"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-ES", "es-AR" }); - Assert.AreEqual ("Lince ibérico", s, $"{tableName}/{key}:es-ES;es-AR"); + Assert.That (s, Is.EqualTo ("Lince ibérico"), $"{tableName}/{key}:es-ES;es-AR"); foreach (var tn in new string [] { "Localizable", null, "" }) { tableName = tn; key = "GoodMorning"; s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { }); - Assert.AreEqual ("Wakey, wakey, eggs and bakey", s, $"{tableName}/{key}:[]"); + Assert.That (s, Is.EqualTo ("Wakey, wakey, eggs and bakey"), $"{tableName}/{key}:[]"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "en-CA" }); - Assert.AreEqual ("Wakey, wakey, eggs and bakey", s, $"{tableName}/{key}:en-CA"); + Assert.That (s, Is.EqualTo ("Wakey, wakey, eggs and bakey"), $"{tableName}/{key}:en-CA"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "en-US" }); - Assert.AreEqual ("Wakey, wakey, eggs and bakey", s, $"{tableName}/{key}:en-US"); + Assert.That (s, Is.EqualTo ("Wakey, wakey, eggs and bakey"), $"{tableName}/{key}:en-US"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "en-AU" }); - Assert.AreEqual ("G'day mate", s, $"{tableName}/{key}:en-AU"); + Assert.That (s, Is.EqualTo ("G'day mate"), $"{tableName}/{key}:en-AU"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "en-UK" }); - Assert.AreEqual ("Wakey, wakey, eggs and bakey", s, $"{tableName}/{key}:en-UK"); + Assert.That (s, Is.EqualTo ("Wakey, wakey, eggs and bakey"), $"{tableName}/{key}:en-UK"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-ES" }); - Assert.AreEqual ("Buenos días", s, $"{tableName}/{key}:es-ES"); + Assert.That (s, Is.EqualTo ("Buenos días"), $"{tableName}/{key}:es-ES"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-AR" }); - Assert.AreEqual ("Buen día", s, $"{tableName}/{key}:es-AR"); + Assert.That (s, Is.EqualTo ("Buen día"), $"{tableName}/{key}:es-AR"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es" }); - Assert.AreEqual ("Buenas", s, $"{tableName}/{key}:es"); + Assert.That (s, Is.EqualTo ("Buenas"), $"{tableName}/{key}:es"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-MX" }); - Assert.AreEqual ("Buenas", s, $"{tableName}/{key}:es-MX"); + Assert.That (s, Is.EqualTo ("Buenas"), $"{tableName}/{key}:es-MX"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-AR", "es-ES" }); - Assert.AreEqual ("Buen día", s, $"{tableName}/{key}:es-AR;es-ES"); + Assert.That (s, Is.EqualTo ("Buen día"), $"{tableName}/{key}:es-AR;es-ES"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-ES", "es-AR" }); - Assert.AreEqual ("Buenos días", s, $"{tableName}/{key}:es-ES;es-AR"); + Assert.That (s, Is.EqualTo ("Buenos días"), $"{tableName}/{key}:es-ES;es-AR"); } foreach (var tn in new string [] { "Base", "AnythingElse" }) { tableName = tn; key = "GoodMorning"; s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { }); - Assert.AreEqual (defaultValue, s, $"{tableName}/{key}:[]"); + Assert.That (s, Is.EqualTo (defaultValue), $"{tableName}/{key}:[]"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "en-CA" }); - Assert.AreEqual (defaultValue, s, $"{tableName}/{key}:en-CA"); + Assert.That (s, Is.EqualTo (defaultValue), $"{tableName}/{key}:en-CA"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "en-US" }); - Assert.AreEqual (defaultValue, s, $"{tableName}/{key}:en-US"); + Assert.That (s, Is.EqualTo (defaultValue), $"{tableName}/{key}:en-US"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "en-AU" }); - Assert.AreEqual (defaultValue, s, $"{tableName}/{key}:en-AU"); + Assert.That (s, Is.EqualTo (defaultValue), $"{tableName}/{key}:en-AU"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "en-UK" }); - Assert.AreEqual (defaultValue, s, $"{tableName}/{key}:en-UK"); + Assert.That (s, Is.EqualTo (defaultValue), $"{tableName}/{key}:en-UK"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-ES" }); - Assert.AreEqual (defaultValue, s, $"{tableName}/{key}:es-ES"); + Assert.That (s, Is.EqualTo (defaultValue), $"{tableName}/{key}:es-ES"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-AR" }); - Assert.AreEqual (defaultValue, s, $"{tableName}/{key}:es-AR"); + Assert.That (s, Is.EqualTo (defaultValue), $"{tableName}/{key}:es-AR"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es" }); - Assert.AreEqual (defaultValue, s, $"{tableName}/{key}:es"); + Assert.That (s, Is.EqualTo (defaultValue), $"{tableName}/{key}:es"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-MX" }); - Assert.AreEqual (defaultValue, s, $"{tableName}/{key}:es-MX"); + Assert.That (s, Is.EqualTo (defaultValue), $"{tableName}/{key}:es-MX"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-AR", "es-ES" }); - Assert.AreEqual (defaultValue, s, $"{tableName}/{key}:es-AR;es-ES"); + Assert.That (s, Is.EqualTo (defaultValue), $"{tableName}/{key}:es-AR;es-ES"); s = main.GetLocalizedString (key, defaultValue, tableName, new string [] { "es-ES", "es-AR" }); - Assert.AreEqual (defaultValue, s, $"{tableName}/{key}:es-ES;es-AR"); + Assert.That (s, Is.EqualTo (defaultValue), $"{tableName}/{key}:es-ES;es-AR"); } }); } @@ -564,13 +562,13 @@ public void TestIsArchitectureLoadable () bool loadable_x86_64 = CFBundle.IsArchitectureLoadable (CFBundle.Architecture.X86_64); // Due to Rosetta, both x64 and arm64 executables are loadable on Apple Silicon. if (isX64Executable || isArm64Executable) - Assert.IsTrue (loadable_x86_64, "x86_64 Expected => true"); + Assert.That (loadable_x86_64, Is.True, "x86_64 Expected => true"); else - Assert.IsFalse (loadable_x86_64, "x86_64 Expected => false"); + Assert.That (loadable_x86_64, Is.False, "x86_64 Expected => false"); bool loadable_arm64 = CFBundle.IsArchitectureLoadable (CFBundle.Architecture.ARM64); if (isArm64Executable) - Assert.IsTrue (loadable_arm64, "arm64 Expected => true"); + Assert.That (loadable_arm64, Is.True, "arm64 Expected => true"); // Due to Rosetta, we can't determine whether ARM64 is loadable or not if we're an X64 executable ourselves. } @@ -581,10 +579,10 @@ public void TestIsExecutableLoadable () var main = CFBundle.GetMain (); var loadableBundle = CFBundle.IsExecutableLoadable (main); - Assert.IsTrue (loadableBundle, "loadableBundle"); + Assert.That (loadableBundle, Is.True, "loadableBundle"); var loadableBundleUrl = CFBundle.IsExecutableLoadable (main.ExecutableUrl); - Assert.IsTrue (loadableBundleUrl, "loadableBundleUrl"); + Assert.That (loadableBundleUrl, Is.True, "loadableBundleUrl"); } #endif } diff --git a/tests/monotouch-test/CoreFoundation/CFNotificationCenterTest.cs b/tests/monotouch-test/CoreFoundation/CFNotificationCenterTest.cs index 67128cb914a1..6e03b3989858 100644 --- a/tests/monotouch-test/CoreFoundation/CFNotificationCenterTest.cs +++ b/tests/monotouch-test/CoreFoundation/CFNotificationCenterTest.cs @@ -32,22 +32,22 @@ public void TestObservers () }); }); d.PostNotification ("hello", target, null, deliverImmediately: true); - Assert.AreEqual (1, count); + Assert.That (count, Is.EqualTo (1)); d.PostNotification ("hello", target, null, deliverImmediately: true); - Assert.AreEqual (2, count); - Assert.AreEqual (1, count2); + Assert.That (count, Is.EqualTo (2)); + Assert.That (count2, Is.EqualTo (1)); // Remove the first observer, count should not be updated d.RemoveObserver (o1); d.PostNotification ("hello", target, null); - Assert.AreEqual (2, count); - Assert.AreEqual (2, count2); + Assert.That (count, Is.EqualTo (2)); + Assert.That (count2, Is.EqualTo (2)); // Remove the last observer, there should be no change in count d.RemoveObserver (o2); d.PostNotification ("hello", target, null); - Assert.AreEqual (2, count); - Assert.AreEqual (2, count2); + Assert.That (count, Is.EqualTo (2)); + Assert.That (count2, Is.EqualTo (2)); // Test removing all observers count = 0; @@ -58,15 +58,15 @@ public void TestObservers () o2 = d.AddObserver ("hello", target, (y, ee) => { count++; }); d.RemoveEveryObserver (); d.PostNotification ("hello", target, null); - Assert.AreEqual (0, count); + Assert.That (count, Is.EqualTo (0)); // Test removing from a callback count = 0; o2 = d.AddObserver ("hello", target, (y, ee) => { count++; d.RemoveObserver (o2); }); d.PostNotification ("hello", target, null); - Assert.AreEqual (1, count); + Assert.That (count, Is.EqualTo (1)); d.PostNotification ("hello", target, null); - Assert.AreEqual (1, count); + Assert.That (count, Is.EqualTo (1)); } [Test] @@ -85,7 +85,7 @@ public void TestNullNameAndObserver () NSNotificationCenter.DefaultCenter.PostNotificationName ("MornNotification", null); d.RemoveObserver (token); - Assert.IsTrue (mornNotification.WaitOne (TimeSpan.FromSeconds (10)), "Didn't get a notification after waiting 10 seconds."); + Assert.That (mornNotification.WaitOne (TimeSpan.FromSeconds (10)), Is.True, "Didn't get a notification after waiting 10 seconds."); } [Test] @@ -103,22 +103,22 @@ public void TestObservers2 () }); }); d.PostNotification ("hello", null, null, deliverImmediately: true); - Assert.AreEqual (1, count); + Assert.That (count, Is.EqualTo (1)); NSNotificationCenter.DefaultCenter.PostNotificationName ("hello", null); - Assert.AreEqual (2, count); - Assert.AreEqual (1, count2); + Assert.That (count, Is.EqualTo (2)); + Assert.That (count2, Is.EqualTo (1)); // Remove the first observer, count should not be updated d.RemoveObserver (o1); d.PostNotification ("hello", null, null); - Assert.AreEqual (2, count); - Assert.AreEqual (2, count2); + Assert.That (count, Is.EqualTo (2)); + Assert.That (count2, Is.EqualTo (2)); // Remove the last observer, there should be no change in count d.RemoveObserver (o2); NSNotificationCenter.DefaultCenter.PostNotificationName ("hello", null); - Assert.AreEqual (2, count); - Assert.AreEqual (2, count2); + Assert.That (count, Is.EqualTo (2)); + Assert.That (count2, Is.EqualTo (2)); // Test removing all observers count = 0; @@ -128,15 +128,15 @@ public void TestObservers2 () o2 = d.AddObserver (null, null, (y, ee) => { count++; }); d.RemoveEveryObserver (); NSNotificationCenter.DefaultCenter.PostNotificationName ("hello", null); - Assert.AreEqual (0, count); + Assert.That (count, Is.EqualTo (0)); // Test removing from a callback count = 0; o2 = d.AddObserver (null, null, (y, ee) => { count++; d.RemoveObserver (o2); }); d.PostNotification ("hello", null, null); - Assert.AreEqual (1, count); + Assert.That (count, Is.EqualTo (1)); NSNotificationCenter.DefaultCenter.PostNotificationName ("hello", null); - Assert.AreEqual (1, count); + Assert.That (count, Is.EqualTo (1)); } } } diff --git a/tests/monotouch-test/CoreFoundation/CFSocketDataEventArgsTests.cs b/tests/monotouch-test/CoreFoundation/CFSocketDataEventArgsTests.cs index c316e5c2d415..cae8344ad8b4 100644 --- a/tests/monotouch-test/CoreFoundation/CFSocketDataEventArgsTests.cs +++ b/tests/monotouch-test/CoreFoundation/CFSocketDataEventArgsTests.cs @@ -31,12 +31,12 @@ public void Constructor_WithByteArray_SetsPropertiesCorrectly () var args = new CFSocket.CFSocketDataEventArgs (remoteEndPoint, testData); // Assert - Assert.AreSame (remoteEndPoint, args.RemoteEndPoint); + Assert.That (args.RemoteEndPoint, Is.SameAs (remoteEndPoint)); var retrievedData = args.Data; - Assert.IsNotNull (retrievedData); - Assert.AreEqual (testData.Length, retrievedData.Length); + Assert.That (retrievedData, Is.Not.Null); + Assert.That (retrievedData.Length, Is.EqualTo (testData.Length)); for (int i = 0; i < testData.Length; i++) { - Assert.AreEqual (testData [i], retrievedData [i]); + Assert.That (retrievedData [i], Is.EqualTo (testData [i])); } } @@ -50,8 +50,8 @@ public void Constructor_WithNullRemoteEndPoint_AcceptsNull () // Since RemoteEndPoint uses nullable reference types, null should be accepted Assert.DoesNotThrow (() => { var args = new CFSocket.CFSocketDataEventArgs (null, testData); - Assert.IsNull (args.RemoteEndPoint); - Assert.AreSame (testData, args.Data); + Assert.That (args.RemoteEndPoint, Is.Null); + Assert.That (args.Data, Is.SameAs (testData)); }); } @@ -65,10 +65,10 @@ public void Constructor_WithNullByteArray_AcceptsNull () // Since data uses nullable reference types, null should be accepted Assert.DoesNotThrow (() => { var args = new CFSocket.CFSocketDataEventArgs (remoteEndPoint, (byte []) null); - Assert.AreSame (remoteEndPoint, args.RemoteEndPoint); + Assert.That (args.RemoteEndPoint, Is.SameAs (remoteEndPoint)); // Data property should return empty array when null - Assert.IsNotNull (args.Data); - Assert.AreEqual (0, args.Data.Length); + Assert.That (args.Data, Is.Not.Null); + Assert.That (args.Data.Length, Is.EqualTo (0)); }); } @@ -83,8 +83,8 @@ public void Data_WithEmptyByteArray_ReturnsEmptyArray () var args = new CFSocket.CFSocketDataEventArgs (remoteEndPoint, emptyData); // Assert - Assert.AreSame (emptyData, args.Data); - Assert.AreEqual (0, args.Data.Length); + Assert.That (args.Data, Is.SameAs (emptyData)); + Assert.That (args.Data.Length, Is.EqualTo (0)); } [Test] @@ -96,7 +96,7 @@ public void Data_WithEmptyCFData_ReturnsEmptyArray () var remoteEndPoint = new IPEndPoint (IPAddress.Loopback, 8080); var args = new CFSocket.CFSocketDataEventArgs (remoteEndPoint, (byte []) null); - Assert.AreEqual (0, args.Data.Length); + Assert.That (args.Data.Length, Is.EqualTo (0)); } [Test] @@ -114,13 +114,13 @@ public void Data_AccessedMultipleTimes_ReturnsSameInstance () var data2 = args1.Data; // Assert - Assert.AreSame (data1, data2, "Data property should return the same instance when accessed multiple times with byte array"); + Assert.That (data2, Is.SameAs (data1), "Data property should return the same instance when accessed multiple times with byte array"); // Test with null data (should return empty array consistently) var args2 = new CFSocket.CFSocketDataEventArgs (remoteEndPoint, (byte []) null); var emptyData1 = args2.Data; var emptyData2 = args2.Data; - Assert.AreSame (emptyData1, emptyData2, "Data property should return the same empty array instance when accessed multiple times with null data"); + Assert.That (emptyData2, Is.SameAs (emptyData1), "Data property should return the same empty array instance when accessed multiple times with null data"); } [Test] @@ -135,9 +135,9 @@ public void RemoteEndPoint_IPv6Address_SetsCorrectly () var args = new CFSocket.CFSocketDataEventArgs (remoteEndPoint, testData); // Assert - Assert.AreSame (remoteEndPoint, args.RemoteEndPoint); - Assert.AreEqual (ipv6Address, args.RemoteEndPoint.Address); - Assert.AreEqual (9090, args.RemoteEndPoint.Port); + Assert.That (args.RemoteEndPoint, Is.SameAs (remoteEndPoint)); + Assert.That (args.RemoteEndPoint.Address, Is.EqualTo (ipv6Address)); + Assert.That (args.RemoteEndPoint.Port, Is.EqualTo (9090)); } [Test] @@ -154,7 +154,7 @@ public void RemoteEndPoint_DifferentPorts_SetsCorrectly () var args = new CFSocket.CFSocketDataEventArgs (remoteEndPoint, testData); // Assert - Assert.AreEqual (port, args.RemoteEndPoint.Port, $"Port {port} should be set correctly"); + Assert.That (args.RemoteEndPoint.Port, Is.EqualTo (port), $"Port {port} should be set correctly"); } } @@ -169,7 +169,7 @@ public void InheritsFromEventArgs () var args = new CFSocket.CFSocketDataEventArgs (remoteEndPoint, testData); // Assert - Assert.IsInstanceOf (args, "CFSocketDataEventArgs should inherit from EventArgs"); + Assert.That (args, Is.InstanceOf (), "CFSocketDataEventArgs should inherit from EventArgs"); } [Test] @@ -186,13 +186,13 @@ public void LargeDataArray_HandledCorrectly () var args = new CFSocket.CFSocketDataEventArgs (remoteEndPoint, largeData); // Assert - Assert.AreSame (largeData, args.Data); - Assert.AreEqual (1024 * 1024, args.Data.Length); + Assert.That (args.Data, Is.SameAs (largeData)); + Assert.That (args.Data.Length, Is.EqualTo (1024 * 1024)); // Verify a few sample bytes - Assert.AreEqual (0, args.Data [0]); - Assert.AreEqual (255, args.Data [255]); - Assert.AreEqual (0, args.Data [256]); + Assert.That (args.Data [0], Is.EqualTo (0)); + Assert.That (args.Data [255], Is.EqualTo (255)); + Assert.That (args.Data [256], Is.EqualTo (0)); } [Test] @@ -208,12 +208,12 @@ public void CFData_LazyLoading_WorksCorrectly () // Act & Assert // First access to Data should trigger the lazy loading (should return empty array) var retrievedData = args.Data; - Assert.IsNotNull (retrievedData); - Assert.AreEqual (0, retrievedData.Length); + Assert.That (retrievedData, Is.Not.Null); + Assert.That (retrievedData.Length, Is.EqualTo (0)); // Subsequent accesses should return the same cached instance var retrievedData2 = args.Data; - Assert.AreSame (retrievedData, retrievedData2); + Assert.That (retrievedData2, Is.SameAs (retrievedData)); } } } diff --git a/tests/monotouch-test/CoreFoundation/DispatchBlockTests.cs b/tests/monotouch-test/CoreFoundation/DispatchBlockTests.cs index 80fb6b2ae5f5..8d9248d8e360 100644 --- a/tests/monotouch-test/CoreFoundation/DispatchBlockTests.cs +++ b/tests/monotouch-test/CoreFoundation/DispatchBlockTests.cs @@ -28,20 +28,20 @@ public void Invoke () var callback = new Action (() => called = true); using (var db = new DispatchBlock (callback)) { db.Invoke (); - Assert.IsTrue (called, "Called"); + Assert.That (called, Is.True, "Called"); } } [Test] public void ExplicitActionConversionInvoke () { - Assert.IsNull ((Action) ((DispatchBlock) null), "Null conversion"); + Assert.That ((Action) ((DispatchBlock) null), Is.Null, "Null conversion"); var called = false; var callback = new Action (() => called = true); using (var db = new DispatchBlock (callback)) { ((Action) db) (); - Assert.IsTrue (called, "Called"); + Assert.That (called, Is.True, "Called"); } } @@ -58,7 +58,7 @@ public void NotifyAction () db.Notify (DispatchQueue.MainQueue, notification); DispatchQueue.MainQueue.DispatchAsync (db); TestRuntime.RunAsync (TimeSpan.FromSeconds (5), () => { }, () => notified); - Assert.IsTrue (called, "Called"); + Assert.That (called, Is.True, "Called"); } } @@ -76,7 +76,7 @@ public void NotifyDispatchBlock () db.Notify (DispatchQueue.MainQueue, notification_block); DispatchQueue.MainQueue.DispatchAsync (db); TestRuntime.RunAsync (TimeSpan.FromSeconds (5), () => { }, () => notified); - Assert.IsTrue (called, "Called"); + Assert.That (called, Is.True, "Called"); } } } @@ -92,12 +92,12 @@ public void Wait_DispatchTime () using (var queue = new DispatchQueue ("Background")) { queue.Activate (); var rv = (int) db.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (0.1))); - Assert.AreNotEqual (0, rv, "Timed Out"); + Assert.That (rv, Is.Not.EqualTo (0), "Timed Out"); queue.DispatchAsync (db); rv = (int) db.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (5))); - Assert.AreEqual (0, rv, "Timed Out 2"); - Assert.IsTrue (called, "Called"); + Assert.That (rv, Is.EqualTo (0), "Timed Out 2"); + Assert.That (called, Is.True, "Called"); } } } @@ -113,12 +113,12 @@ public void Wait_TimeSpan () using (var queue = new DispatchQueue ("Background")) { queue.Activate (); var rv = (int) db.Wait (TimeSpan.FromSeconds (0.1)); - Assert.AreNotEqual (0, rv, "Timed Out"); + Assert.That (rv, Is.Not.EqualTo (0), "Timed Out"); queue.DispatchAsync (db); rv = (int) db.Wait (TimeSpan.FromSeconds (5)); - Assert.AreEqual (0, rv, "Timed Out 2"); - Assert.IsTrue (called, "Called"); + Assert.That (rv, Is.EqualTo (0), "Timed Out 2"); + Assert.That (called, Is.True, "Called"); } } } @@ -129,12 +129,12 @@ public void Cancellation () var called = false; var callback = new Action (() => called = true); using (var db = new DispatchBlock (callback)) { - Assert.AreEqual ((nint) 0, db.TestCancel (), "TestCancel 1"); - Assert.IsFalse (db.Cancelled, "Cancelled 1"); + Assert.That (db.TestCancel (), Is.EqualTo ((nint) 0), "TestCancel 1"); + Assert.That (db.Cancelled, Is.False, "Cancelled 1"); db.Cancel (); - Assert.AreNotEqual ((nint) 0, db.TestCancel (), "TestCancel 2"); - Assert.IsTrue (db.Cancelled, "Cancelled 2"); - Assert.IsFalse (called, "Called"); // The dispatch block was never submitted to a dispatch queue, so it shouldn't have executed. + Assert.That (db.TestCancel (), Is.Not.EqualTo ((nint) 0), "TestCancel 2"); + Assert.That (db.Cancelled, Is.True, "Cancelled 2"); + Assert.That (called, Is.False, "Called"); // The dispatch block was never submitted to a dispatch queue, so it shouldn't have executed. } } @@ -163,8 +163,8 @@ public void Constructors () queue.Activate (); queue.DispatchAsync (db); var rv = (int) db.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (5))); - Assert.AreEqual (0, rv, "Timed Out A"); - Assert.IsTrue (called, "Called A"); + Assert.That (rv, Is.EqualTo (0), "Timed Out A"); + Assert.That (called, Is.True, "Called A"); } } @@ -175,8 +175,8 @@ public void Constructors () queue.Activate (); queue.DispatchAsync (db); var rv = (int) db.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (5))); - Assert.AreEqual (0, rv, "Timed Out " + flags); - Assert.IsTrue (called, "Called " + flags); + Assert.That (rv, Is.EqualTo (0), "Timed Out " + flags); + Assert.That (called, Is.True, "Called " + flags); } } @@ -187,8 +187,8 @@ public void Constructors () queue.Activate (); queue.DispatchAsync (db); var rv = (int) db.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (5))); - Assert.AreEqual (0, rv, "Timed Out " + flags); - Assert.IsTrue (called, "Called " + flags); + Assert.That (rv, Is.EqualTo (0), "Timed Out " + flags); + Assert.That (called, Is.True, "Called " + flags); } } @@ -200,8 +200,8 @@ public void Constructors () queue.Activate (); queue.DispatchAsync (db); var rv = (int) db.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (5))); - Assert.AreEqual (0, rv, "Timed Out " + flags); - Assert.IsTrue (called, "Called " + flags); + Assert.That (rv, Is.EqualTo (0), "Timed Out " + flags); + Assert.That (called, Is.True, "Called " + flags); } } @@ -212,8 +212,8 @@ public void Constructors () queue.Activate (); queue.DispatchAsync (db); var rv = (int) db.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (5))); - Assert.AreEqual (0, rv, "Timed Out Background 8" + flags); - Assert.IsTrue (called, "Called Background 8" + flags); + Assert.That (rv, Is.EqualTo (0), "Timed Out Background 8" + flags); + Assert.That (called, Is.True, "Called Background 8" + flags); } } } @@ -243,8 +243,8 @@ public void Create () queue.Activate (); queue.DispatchAsync (db); var rv = (int) db.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (5))); - Assert.AreEqual (0, rv, "Timed Out A"); - Assert.IsTrue (called, "Called A"); + Assert.That (rv, Is.EqualTo (0), "Timed Out A"); + Assert.That (called, Is.True, "Called A"); } } @@ -255,8 +255,8 @@ public void Create () queue.Activate (); queue.DispatchAsync (db); var rv = (int) db.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (5))); - Assert.AreEqual (0, rv, "Timed Out " + flags); - Assert.IsTrue (called, "Called " + flags); + Assert.That (rv, Is.EqualTo (0), "Timed Out " + flags); + Assert.That (called, Is.True, "Called " + flags); } } @@ -267,8 +267,8 @@ public void Create () queue.Activate (); queue.DispatchAsync (db); var rv = (int) db.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (5))); - Assert.AreEqual (0, rv, "Timed Out " + flags); - Assert.IsTrue (called, "Called " + flags); + Assert.That (rv, Is.EqualTo (0), "Timed Out " + flags); + Assert.That (called, Is.True, "Called " + flags); } } @@ -280,8 +280,8 @@ public void Create () queue.Activate (); queue.DispatchAsync (db); var rv = (int) db.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (5))); - Assert.AreEqual (0, rv, "Timed Out " + flags); - Assert.IsTrue (called, "Called " + flags); + Assert.That (rv, Is.EqualTo (0), "Timed Out " + flags); + Assert.That (called, Is.True, "Called " + flags); } } @@ -292,8 +292,8 @@ public void Create () queue.Activate (); queue.DispatchAsync (db); var rv = (int) db.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (5))); - Assert.AreEqual (0, rv, "Timed Out Background 8" + flags); - Assert.IsTrue (called, "Called Background 8" + flags); + Assert.That (rv, Is.EqualTo (0), "Timed Out Background 8" + flags); + Assert.That (called, Is.True, "Called Background 8" + flags); } } @@ -305,8 +305,8 @@ public void Create () queue.Activate (); queue.DispatchAsync (db2); var rv = (int) db2.Wait (new DispatchTime (DispatchTime.Now, TimeSpan.FromSeconds (5))); - Assert.AreEqual (0, rv, "Timed Out Background DB" + flags); - Assert.IsTrue (called, "Called Background DB" + flags); + Assert.That (rv, Is.EqualTo (0), "Timed Out Background DB" + flags); + Assert.That (called, Is.True, "Called Background DB" + flags); } } } diff --git a/tests/monotouch-test/CoreFoundation/DispatchDataTest.cs b/tests/monotouch-test/CoreFoundation/DispatchDataTest.cs index 4e32da2464a9..0e34b7d05ac8 100644 --- a/tests/monotouch-test/CoreFoundation/DispatchDataTest.cs +++ b/tests/monotouch-test/CoreFoundation/DispatchDataTest.cs @@ -20,7 +20,7 @@ public void FromByteBufferTest () { using (var dd = DispatchData.FromByteBuffer (testData)) { var ddString = Encoding.UTF8.GetString (dd.ToArray ()); - Assert.AreEqual (testString, ddString); + Assert.That (ddString, Is.EqualTo (testString)); } } @@ -31,7 +31,7 @@ public void FromReadOnlySpanTest () using (var dd = DispatchData.FromReadOnlySpan (readOnlySpan)) { var data = dd.ToArray (); var ddString = Encoding.UTF8.GetString (dd.ToArray ()); - Assert.AreEqual (testString, ddString); + Assert.That (ddString, Is.EqualTo (testString)); } } diff --git a/tests/monotouch-test/CoreFoundation/DispatchGroupTest.cs b/tests/monotouch-test/CoreFoundation/DispatchGroupTest.cs index 771e42661424..cee8f872f752 100644 --- a/tests/monotouch-test/CoreFoundation/DispatchGroupTest.cs +++ b/tests/monotouch-test/CoreFoundation/DispatchGroupTest.cs @@ -25,7 +25,7 @@ public void WaitTest () Console.WriteLine ("Inside dispatch"); }); - Assert.IsTrue (dg.Wait (DispatchTime.Forever)); + Assert.That (dg.Wait (DispatchTime.Forever), Is.True); dq.Dispose (); } } @@ -35,9 +35,9 @@ public void EnterLeaveTest () { using (var dg = DispatchGroup.Create ()) { dg.Enter (); - Assert.IsFalse (dg.Wait (new DispatchTime (1000 * 1000 * 1000)), "#1"); + Assert.That (dg.Wait (new DispatchTime (1000 * 1000 * 1000)), Is.False, "#1"); dg.Leave (); - Assert.IsTrue (dg.Wait (DispatchTime.Forever), "#2"); + Assert.That (dg.Wait (DispatchTime.Forever), Is.True, "#2"); } } @@ -53,7 +53,7 @@ public void NotifyWithDispatchBlock () using (var block = new DispatchBlock (callback)) { dg.Notify (DispatchQueue.MainQueue, block); TestRuntime.RunAsync (TimeSpan.FromSeconds (5), () => { }, () => called); - Assert.IsTrue (called, "Called"); + Assert.That (called, Is.True, "Called"); } } } @@ -66,7 +66,7 @@ public void NotifyWithAction () var callback = new Action (() => called = true); dg.Notify (DispatchQueue.MainQueue, callback); TestRuntime.RunAsync (TimeSpan.FromSeconds (5), () => { }, () => called); - Assert.IsTrue (called, "Called"); + Assert.That (called, Is.True, "Called"); } } } diff --git a/tests/monotouch-test/CoreFoundation/DispatchQueueTest.cs b/tests/monotouch-test/CoreFoundation/DispatchQueueTest.cs index 0565463f4668..9bacda8c29f5 100644 --- a/tests/monotouch-test/CoreFoundation/DispatchQueueTest.cs +++ b/tests/monotouch-test/CoreFoundation/DispatchQueueTest.cs @@ -30,21 +30,21 @@ public void CtorWithAttributes () using (var queue = new DispatchQueue ("1", new DispatchQueue.Attributes { AutoreleaseFrequency = DispatchQueue.AutoreleaseFrequency.Inherit, })) { - Assert.AreNotEqual (IntPtr.Zero, queue.Handle, "Handle 1"); + Assert.That (queue.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle 1"); } using (var queue = new DispatchQueue ("2", new DispatchQueue.Attributes { IsInitiallyInactive = true, })) { queue.Activate (); // must activate the queue before it can be released according to Apple's documentation - Assert.AreNotEqual (IntPtr.Zero, queue.Handle, "Handle 2"); + Assert.That (queue.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle 2"); } using (var queue = new DispatchQueue ("3", new DispatchQueue.Attributes { QualityOfService = DispatchQualityOfService.Utility, })) { - Assert.AreNotEqual (IntPtr.Zero, queue.Handle, "Handle 3"); - Assert.AreEqual (DispatchQualityOfService.Utility, queue.QualityOfService, "QualityOfService 3"); + Assert.That (queue.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle 3"); + Assert.That (queue.QualityOfService, Is.EqualTo (DispatchQualityOfService.Utility), "QualityOfService 3"); } using (var target_queue = new DispatchQueue ("4 - target")) { @@ -53,9 +53,9 @@ public void CtorWithAttributes () AutoreleaseFrequency = DispatchQueue.AutoreleaseFrequency.WorkItem, RelativePriority = -1, }, target_queue)) { - Assert.AreNotEqual (IntPtr.Zero, queue.Handle, "Handle 4"); - Assert.AreEqual (DispatchQualityOfService.Background, queue.GetQualityOfService (out var relative_priority), "QualityOfService 4"); - Assert.AreEqual (-1, relative_priority, "RelativePriority 4"); + Assert.That (queue.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle 4"); + Assert.That (queue.GetQualityOfService (out var relative_priority), Is.EqualTo (DispatchQualityOfService.Background), "QualityOfService 4"); + Assert.That (relative_priority, Is.EqualTo (-1), "RelativePriority 4"); } } } @@ -66,7 +66,7 @@ public void Specific () using (var queue = new DispatchQueue ("Specific")) { var key = (IntPtr) 0x31415926; queue.SetSpecific (key, "hello world"); - Assert.AreEqual ("hello world", queue.GetSpecific (key), "Key"); + Assert.That (queue.GetSpecific (key), Is.EqualTo ("hello world"), "Key"); } } @@ -80,12 +80,12 @@ public void DispatchSync () var called = false; var callback = new Action (() => called = true); queue.DispatchSync (callback); - Assert.IsTrue (called, "Called"); + Assert.That (called, Is.True, "Called"); called = false; using (var dg = new DispatchBlock (callback)) queue.DispatchSync (dg); - Assert.IsTrue (called, "Called DispatchBlock"); + Assert.That (called, Is.True, "Called DispatchBlock"); } } @@ -99,12 +99,12 @@ public void DispatchBarrierSync () var called = false; var callback = new Action (() => called = true); queue.DispatchBarrierSync (callback); - Assert.IsTrue (called, "Called"); + Assert.That (called, Is.True, "Called"); called = false; using (var dg = new DispatchBlock (callback)) queue.DispatchBarrierSync (dg); - Assert.IsTrue (called, "Called DispatchBlock"); + Assert.That (called, Is.True, "Called DispatchBlock"); } } @@ -120,7 +120,7 @@ public void DispatchAsync () var callback = new Action (() => called.SetResult (true)); queue.DispatchAsync (callback); TestRuntime.RunAsync (TimeSpan.FromSeconds (5), called.Task); - Assert.IsTrue (called.Task.Result, "Called"); + Assert.That (called.Task.Result, Is.True, "Called"); } { var called = new TaskCompletionSource (); @@ -129,7 +129,7 @@ public void DispatchAsync () queue.DispatchAsync (dg); dg.Wait (TimeSpan.FromSeconds (5)); } - Assert.IsTrue (called.Task.Result, "Called DispatchBlock"); + Assert.That (called.Task.Result, Is.True, "Called DispatchBlock"); } } } @@ -146,7 +146,7 @@ public void DispatchBarrierAsync () var callback = new Action (() => called.SetResult (true)); queue.DispatchBarrierAsync (callback); TestRuntime.RunAsync (TimeSpan.FromSeconds (5), called.Task); - Assert.IsTrue (called.Task.Result, "Called"); + Assert.That (called.Task.Result, Is.True, "Called"); } { var called = new TaskCompletionSource (); @@ -155,7 +155,7 @@ public void DispatchBarrierAsync () queue.DispatchBarrierAsync (dg); dg.Wait (TimeSpan.FromSeconds (5)); } - Assert.IsTrue (called.Task.Result, "Called DispatchBlock"); + Assert.That (called.Task.Result, Is.True, "Called DispatchBlock"); } } } @@ -163,7 +163,7 @@ public void DispatchBarrierAsync () [Test] public void MainQueue () { - Assert.AreEqual (DispatchQueue.CurrentQueue, DispatchQueue.MainQueue, "MainQueue"); + Assert.That (DispatchQueue.MainQueue, Is.EqualTo (DispatchQueue.CurrentQueue), "MainQueue"); } } } diff --git a/tests/monotouch-test/CoreFoundation/DispatchTests.cs b/tests/monotouch-test/CoreFoundation/DispatchTests.cs index 8165af96b641..957a1ed98ffe 100644 --- a/tests/monotouch-test/CoreFoundation/DispatchTests.cs +++ b/tests/monotouch-test/CoreFoundation/DispatchTests.cs @@ -72,9 +72,9 @@ public void MainQueueDispatch () while (hit == false) { NSRunLoop.Current.RunUntil (NSDate.FromTimeIntervalSinceNow (0.5)); } - Assert.IsNotNull (ex, "main ex"); + Assert.That (ex, Is.Not.Null, "main ex"); Assert.That (ex.GetType (), Is.SameAs (typeof (NullReferenceException)), "no thread check hit"); - Assert.IsNotNull (queue_ex, "queue ex"); + Assert.That (queue_ex, Is.Not.Null, "queue ex"); Assert.That (queue_ex.GetType (), Is.SameAs (typeof (UIKitThreadAccessException)), "thread check hit"); Assert.That (uiThread, Is.EqualTo (mainQthread), "mainq thread is equal to uithread"); Assert.That (queueThread, Is.Not.EqualTo (mainQthread), "queueThread is not the same as the UI thread"); @@ -129,9 +129,9 @@ public void MainQueueDispatchQualityOfService () while (hit == false) { NSRunLoop.Current.RunUntil (NSDate.FromTimeIntervalSinceNow (0.5)); } - Assert.IsNotNull (ex, "main ex"); + Assert.That (ex, Is.Not.Null, "main ex"); Assert.That (ex.GetType (), Is.SameAs (typeof (NullReferenceException)), "no thread check hit"); - Assert.IsNotNull (queue_ex, "queue ex"); + Assert.That (queue_ex, Is.Not.Null, "queue ex"); Assert.That (queue_ex.GetType (), Is.SameAs (typeof (UIKitThreadAccessException)), "thread check hit"); Assert.That (uiThread, Is.EqualTo (mainQthread), "mainq thread is equal to uithread"); Assert.That (queueThread, Is.Not.EqualTo (mainQthread), "queueThread is not the same as the UI thread"); @@ -206,9 +206,9 @@ public void Main () public void GetGlobalQueue_Priority () { // values changes in OS versions (and even in arch) but we only want to make sure we get a valid string so the prefix is enough - Assert.True (DispatchQueue.GetGlobalQueue (DispatchQueuePriority.Default).Label.StartsWith ("com.apple.root."), "Default"); - Assert.True (DispatchQueue.GetGlobalQueue (DispatchQueuePriority.Low).Label.StartsWith ("com.apple.root."), "Low"); - Assert.True (DispatchQueue.GetGlobalQueue (DispatchQueuePriority.High).Label.StartsWith ("com.apple.root."), "High"); + Assert.That (DispatchQueue.GetGlobalQueue (DispatchQueuePriority.Default).Label.StartsWith ("com.apple.root."), Is.True, "Default"); + Assert.That (DispatchQueue.GetGlobalQueue (DispatchQueuePriority.Low).Label.StartsWith ("com.apple.root."), Is.True, "Low"); + Assert.That (DispatchQueue.GetGlobalQueue (DispatchQueuePriority.High).Label.StartsWith ("com.apple.root."), Is.True, "High"); } [Test] @@ -217,9 +217,9 @@ public void GetGlobalQueue_QualityOfService () TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 10, 10, throwIfOtherPlatform: false); // values changes in OS versions (and even in arch) but we only want to make sure we get a valid string so the prefix is enough - Assert.True (DispatchQueue.GetGlobalQueue (DispatchQualityOfService.Default).Label.StartsWith ("com.apple.root."), "Default"); - Assert.True (DispatchQueue.GetGlobalQueue (DispatchQualityOfService.Utility).Label.StartsWith ("com.apple.root."), "Low"); - Assert.True (DispatchQueue.GetGlobalQueue (DispatchQualityOfService.UserInitiated).Label.StartsWith ("com.apple.root."), "High"); + Assert.That (DispatchQueue.GetGlobalQueue (DispatchQualityOfService.Default).Label.StartsWith ("com.apple.root."), Is.True, "Default"); + Assert.That (DispatchQueue.GetGlobalQueue (DispatchQualityOfService.Utility).Label.StartsWith ("com.apple.root."), Is.True, "Low"); + Assert.That (DispatchQueue.GetGlobalQueue (DispatchQualityOfService.UserInitiated).Label.StartsWith ("com.apple.root."), Is.True, "High"); } [Test] @@ -287,9 +287,9 @@ public void EverAfter () while (hit == false) { NSRunLoop.Current.RunUntil (NSDate.FromTimeIntervalSinceNow (0.5)); } - Assert.IsNotNull (ex, "main ex"); + Assert.That (ex, Is.Not.Null, "main ex"); Assert.That (ex.GetType (), Is.SameAs (typeof (NullReferenceException)), "no thread check hit"); - Assert.IsNotNull (queue_ex, "queue ex"); + Assert.That (queue_ex, Is.Not.Null, "queue ex"); Assert.That (queue_ex.GetType (), Is.SameAs (typeof (UIKitThreadAccessException)), "thread check hit"); Assert.That (uiThread, Is.EqualTo (mainQthread), "mainq thread is equal to uithread"); Assert.That (queueThread, Is.Not.EqualTo (mainQthread), "queueThread is not the same as the UI thread"); @@ -343,9 +343,9 @@ public void EverAfterQualityOfService () while (hit == false) { NSRunLoop.Current.RunUntil (NSDate.FromTimeIntervalSinceNow (0.5)); } - Assert.IsNotNull (ex, "main ex"); + Assert.That (ex, Is.Not.Null, "main ex"); Assert.That (ex.GetType (), Is.SameAs (typeof (NullReferenceException)), "no thread check hit"); - Assert.IsNotNull (queue_ex, "queue ex"); + Assert.That (queue_ex, Is.Not.Null, "queue ex"); Assert.That (queue_ex.GetType (), Is.SameAs (typeof (UIKitThreadAccessException)), "thread check hit"); Assert.That (uiThread, Is.EqualTo (mainQthread), "mainq thread is equal to uithread"); Assert.That (queueThread, Is.Not.EqualTo (mainQthread), "queueThread is not the same as the UI thread"); diff --git a/tests/monotouch-test/CoreFoundation/MutableString.cs b/tests/monotouch-test/CoreFoundation/MutableString.cs index 5883b9e37b69..658fb35abb80 100644 --- a/tests/monotouch-test/CoreFoundation/MutableString.cs +++ b/tests/monotouch-test/CoreFoundation/MutableString.cs @@ -93,10 +93,10 @@ public void AppendString_RtL () public void TransformNoRangeEnum () { using (var s = new CFMutableString ("Bonjour à tous!")) { - Assert.True (s.Transform (CFStringTransform.ToXmlHex, false), "Transform-1"); + Assert.That (s.Transform (CFStringTransform.ToXmlHex, false), Is.True, "Transform-1"); Assert.That (s.ToString (), Is.EqualTo ("Bonjour à tous!"), "ToString-1"); - Assert.True (s.Transform (CFStringTransform.ToXmlHex, true), "Transform-2"); + Assert.That (s.Transform (CFStringTransform.ToXmlHex, true), Is.True, "Transform-2"); Assert.That (s.ToString (), Is.EqualTo ("Bonjour à tous!"), "ToString-2"); } } @@ -120,11 +120,11 @@ public void TransformRangeEnum () { var r = new CFRange (0, 15); using (var s = new CFMutableString ("Bonjour à tous!")) { - Assert.True (s.Transform (ref r, CFStringTransform.ToXmlHex, false), "Transform-1"); + Assert.That (s.Transform (ref r, CFStringTransform.ToXmlHex, false), Is.True, "Transform-1"); Assert.That (s.ToString (), Is.EqualTo ("Bonjour à tous!"), "ToString-1"); Assert.That (r.Length, Is.EqualTo (20), "Length-1"); - Assert.True (s.Transform (ref r, CFStringTransform.ToXmlHex, true), "Transform-2"); + Assert.That (s.Transform (ref r, CFStringTransform.ToXmlHex, true), Is.True, "Transform-2"); Assert.That (s.ToString (), Is.EqualTo ("Bonjour à tous!"), "ToString-2"); Assert.That (r.Length, Is.EqualTo (15), "Length-2"); } @@ -134,10 +134,10 @@ public void TransformRangeEnum () public void TransformICU () { using (var s = new CFMutableString ("hello world")) { - Assert.True (s.Transform ("Title", false), "Transform-1"); + Assert.That (s.Transform ("Title", false), Is.True, "Transform-1"); Assert.That (s.ToString (), Is.EqualTo ("Hello World"), "ToString-1"); - Assert.True (s.Transform ((NSString) "Title", true), "Transform-2"); + Assert.That (s.Transform ((NSString) "Title", true), Is.True, "Transform-2"); Assert.That (s.ToString (), Is.EqualTo ("hello world"), "ToString-2"); } } diff --git a/tests/monotouch-test/CoreFoundation/NativeObjectTest.cs b/tests/monotouch-test/CoreFoundation/NativeObjectTest.cs index 42df872e372c..26e382a7bfbd 100644 --- a/tests/monotouch-test/CoreFoundation/NativeObjectTest.cs +++ b/tests/monotouch-test/CoreFoundation/NativeObjectTest.cs @@ -116,13 +116,13 @@ public void Equals () { // overriden Equals with weird behavior to confirm it can't be anything else using (var x = new FakeNativeObject ((IntPtr) 42, true)) { - Assert.False (x.Equals (x), "self"); - Assert.True (x.Equals (null), "null"); + Assert.That (x.Equals (x), Is.False, "self"); + Assert.That (x.Equals (null), Is.True, "null"); } // check that equality is based on handle only (and not System.Object.Equals) using (var n1 = new NativeObjectPoker ((IntPtr) 42)) using (var n2 = new NativeObjectPoker ((IntPtr) 42)) - Assert.True (n1.Equals (n2), "1"); + Assert.That (n1.Equals (n2), Is.True, "1"); } [Test] @@ -135,8 +135,8 @@ public void GetHashCodeValue () // check that only the handle is used to compute the hash code of the selector // which means DisposableObject base implementation (not System.Object) is used using (var n = new NativeObjectPoker ((IntPtr) 42)) { - Assert.AreNotEqual (n.GetHashCode (), RuntimeHelpers.GetHashCode (n), "GetHashCode-old"); - Assert.AreEqual (n.GetHashCode (), n.Handle.GetHashCode (), "GetHashCode-net"); + Assert.That (RuntimeHelpers.GetHashCode (n), Is.Not.EqualTo (n.GetHashCode ()), "GetHashCode-old"); + Assert.That (n.Handle.GetHashCode (), Is.EqualTo (n.GetHashCode ()), "GetHashCode-net"); } } } diff --git a/tests/monotouch-test/CoreFoundation/NetworkTest.cs b/tests/monotouch-test/CoreFoundation/NetworkTest.cs index a02509ac2c32..42c18d52d3fc 100644 --- a/tests/monotouch-test/CoreFoundation/NetworkTest.cs +++ b/tests/monotouch-test/CoreFoundation/NetworkTest.cs @@ -31,7 +31,7 @@ public class NetworkTest { public void WebProxy () { IWebProxy proxy = PlatformCFNetwork.GetDefaultProxy (); - Assert.True (proxy.IsBypassed (uri), "IsBypassed"); + Assert.That (proxy.IsBypassed (uri), Is.True, "IsBypassed"); Assert.That (proxy.GetProxy (uri), Is.SameAs (uri), "GetProxy"); } @@ -41,13 +41,13 @@ public void GetProxiesForUri () var proxies = PlatformCFNetwork.GetProxiesForUri (uri, settings); Assert.That (proxies.Length, Is.EqualTo (1), "single"); var p = proxies [0]; - Assert.Null (p.AutoConfigurationJavaScript, "AutoConfigurationJavaScript"); - Assert.Null (p.AutoConfigurationUrl, "AutoConfigurationUrl"); - Assert.Null (p.HostName, "HostName"); + Assert.That (p.AutoConfigurationJavaScript, Is.Null, "AutoConfigurationJavaScript"); + Assert.That (p.AutoConfigurationUrl, Is.Null, "AutoConfigurationUrl"); + Assert.That (p.HostName, Is.Null, "HostName"); Assert.That (p.Port, Is.EqualTo (0), "Port"); - Assert.Null (p.Password, "Password"); + Assert.That (p.Password, Is.Null, "Password"); Assert.That (p.ProxyType, Is.EqualTo (CFProxyType.None), "Type"); - Assert.Null (p.Username, "Username"); + Assert.That (p.Username, Is.Null, "Username"); } [Test] diff --git a/tests/monotouch-test/CoreFoundation/NotificationCenterTest.cs b/tests/monotouch-test/CoreFoundation/NotificationCenterTest.cs index 32842b0f7a71..e9c90453931b 100644 --- a/tests/monotouch-test/CoreFoundation/NotificationCenterTest.cs +++ b/tests/monotouch-test/CoreFoundation/NotificationCenterTest.cs @@ -16,8 +16,8 @@ public class NotificationCenterTest { [Test] public void Static () { - Assert.NotNull (CFNotificationCenter.Darwin, "Darwin"); - Assert.NotNull (CFNotificationCenter.Local, "Local"); + Assert.That (CFNotificationCenter.Darwin, Is.Not.Null, "Darwin"); + Assert.That (CFNotificationCenter.Local, Is.Not.Null, "Local"); } } } diff --git a/tests/monotouch-test/CoreFoundation/PropertyListTests.cs b/tests/monotouch-test/CoreFoundation/PropertyListTests.cs index 2de0479afe5c..3013bde7e755 100644 --- a/tests/monotouch-test/CoreFoundation/PropertyListTests.cs +++ b/tests/monotouch-test/CoreFoundation/PropertyListTests.cs @@ -32,12 +32,12 @@ public void CreateFromData () "; var rv = CFPropertyList.FromData (NSData.FromString (plist)); - Assert.IsNull (rv.Error, "Error 1"); - Assert.IsNotNull (rv.PropertyList, "PropertyList 1"); - Assert.AreEqual (CFPropertyListFormat.XmlFormat1, rv.Format, "Format 1"); - Assert.IsTrue (rv.PropertyList.IsValid (CFPropertyListFormat.BinaryFormat1), "IsValid Binary 1"); - Assert.IsTrue (rv.PropertyList.IsValid (CFPropertyListFormat.OpenStep), "IsValid OpenStep 1"); - Assert.IsTrue (rv.PropertyList.IsValid (CFPropertyListFormat.XmlFormat1), "IsValid Xml 1"); + Assert.That (rv.Error, Is.Null, "Error 1"); + Assert.That (rv.PropertyList, Is.Not.Null, "PropertyList 1"); + Assert.That (rv.Format, Is.EqualTo (CFPropertyListFormat.XmlFormat1), "Format 1"); + Assert.That (rv.PropertyList.IsValid (CFPropertyListFormat.BinaryFormat1), Is.True, "IsValid Binary 1"); + Assert.That (rv.PropertyList.IsValid (CFPropertyListFormat.OpenStep), Is.True, "IsValid OpenStep 1"); + Assert.That (rv.PropertyList.IsValid (CFPropertyListFormat.XmlFormat1), Is.True, "IsValid Xml 1"); } [Test] @@ -46,16 +46,16 @@ public void Constructors () using (var dummy = CreateDummy ()) { var rc = CFGetRetainCount (dummy.Handle); using (var clone = Runtime.GetINativeObject (dummy.Handle, false)) { - Assert.AreEqual (clone.Handle, dummy.Handle, "Handle 1"); - Assert.AreEqual (rc + 1, CFGetRetainCount (clone.Handle), "RC 1"); + Assert.That (dummy.Handle, Is.EqualTo (clone.Handle), "Handle 1"); + Assert.That (CFGetRetainCount (clone.Handle), Is.EqualTo (rc + 1), "RC 1"); } } using (var dummy = CreateDummy ()) { var rc = CFGetRetainCount (dummy.Handle); using (var clone = Runtime.GetINativeObject (dummy.Handle, false)) { - Assert.AreEqual (clone.Handle, dummy.Handle, "Handle 2"); - Assert.AreEqual (rc + 1, CFGetRetainCount (clone.Handle), "RC 2"); + Assert.That (dummy.Handle, Is.EqualTo (clone.Handle), "Handle 2"); + Assert.That (CFGetRetainCount (clone.Handle), Is.EqualTo (rc + 1), "RC 2"); } } @@ -63,8 +63,8 @@ public void Constructors () CFRetain (dummy.Handle); var rc = CFGetRetainCount (dummy.Handle); using (var clone = Runtime.GetINativeObject (dummy.Handle, true)) { - Assert.AreEqual (clone.Handle, dummy.Handle, "Handle 3"); - Assert.AreEqual (rc, CFGetRetainCount (clone.Handle), "RC 3"); + Assert.That (dummy.Handle, Is.EqualTo (clone.Handle), "Handle 3"); + Assert.That (CFGetRetainCount (clone.Handle), Is.EqualTo (rc), "RC 3"); } } } @@ -74,8 +74,8 @@ public void DeepCopy () { using (var dummy = CreateDummy ()) { using (var clone = dummy.DeepCopy ()) { - Assert.AreNotEqual (dummy.Handle, clone.Handle, "Handle"); - Assert.AreEqual (dummy.Value.ToString (), clone.Value.ToString (), "Value comparison"); + Assert.That (clone.Handle, Is.Not.EqualTo (dummy.Handle), "Handle"); + Assert.That (clone.Value.ToString (), Is.EqualTo (dummy.Value.ToString ()), "Value comparison"); } } } @@ -85,8 +85,8 @@ public void AsData () { using (var dummy = CreateDummy ()) { var data = dummy.AsData (CFPropertyListFormat.XmlFormat1); - Assert.IsNull (data.Error, "Error"); - Assert.IsNotNull (data.Data, "Data"); + Assert.That (data.Error, Is.Null, "Error"); + Assert.That (data.Data, Is.Not.Null, "Data"); Assert.That (new StreamReader (data.Data.AsStream ()).ReadToEnd (), Does.StartWith ("SomeStringArrayValue")) { var value = dummy.Value; - Assert.AreEqual (typeof (NSMutableArray), value.GetType (), "Array Value Type"); + Assert.That (value.GetType (), Is.EqualTo (typeof (NSMutableArray)), "Array Value Type"); var arr = (NSArray) value; - Assert.AreEqual ((nuint) 1, arr.Count, "Array Count"); - Assert.AreEqual ("SomeStringArrayValue", arr.GetItem (0).ToString (), "Array First Value"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 1), "Array Count"); + Assert.That (arr.GetItem (0).ToString (), Is.EqualTo ("SomeStringArrayValue"), "Array First Value"); } using (var dummy = CreateDummy ("U29tZURhdGFWYWx1ZQ==")) { var value = dummy.Value; - Assert.AreEqual (typeof (NSMutableData), value.GetType (), "Data Value Type"); - Assert.AreEqual ("SomeDataValue", new StreamReader (((NSData) value).AsStream ()).ReadToEnd (), "Data Value"); + Assert.That (value.GetType (), Is.EqualTo (typeof (NSMutableData)), "Data Value Type"); + Assert.That (new StreamReader (((NSData) value).AsStream ()).ReadToEnd (), Is.EqualTo ("SomeDataValue"), "Data Value"); } using (var dummy = CreateDummy ("SomeKeySomeStringValue")) { var value = dummy.Value; - Assert.AreEqual (typeof (NSMutableDictionary), value.GetType (), "Dictionary Value Type"); + Assert.That (value.GetType (), Is.EqualTo (typeof (NSMutableDictionary)), "Dictionary Value Type"); var dict = (NSDictionary) value; - Assert.AreEqual ((nuint) 1, dict.Count, "Dictionary Count"); - Assert.AreEqual ("SomeKey", dict.Keys [0].ToString (), "Dictionary Key Value"); - Assert.AreEqual ("SomeStringValue", dict ["SomeKey"].ToString (), "Dictionary Entry Value"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 1), "Dictionary Count"); + Assert.That (dict.Keys [0].ToString (), Is.EqualTo ("SomeKey"), "Dictionary Key Value"); + Assert.That (dict ["SomeKey"].ToString (), Is.EqualTo ("SomeStringValue"), "Dictionary Entry Value"); } using (var dummy = CreateDummy ("SomeStringValue")) { var value = dummy.Value; - Assert.AreEqual (typeof (NSMutableString), value.GetType (), "String Value Type"); - Assert.AreEqual ("SomeStringValue", ((NSString) value).ToString (), "String Value"); + Assert.That (value.GetType (), Is.EqualTo (typeof (NSMutableString)), "String Value Type"); + Assert.That (((NSString) value).ToString (), Is.EqualTo ("SomeStringValue"), "String Value"); } using (var dummy = CreateDummy ("2018-08-01T01:00:00Z")) { var value = dummy.Value; - Assert.AreEqual (typeof (NSDate), value.GetType (), "Date Value Type"); + Assert.That (value.GetType (), Is.EqualTo (typeof (NSDate)), "Date Value Type"); var date = (NSDate) value; - Assert.AreEqual (554778000.0, date.SecondsSinceReferenceDate, "Date Value"); + Assert.That (date.SecondsSinceReferenceDate, Is.EqualTo (554778000.0), "Date Value"); } using (var dummy = CreateDummy ("42")) { var value = dummy.Value; - Assert.AreEqual (typeof (NSNumber), value.GetType (), "Int Value Type"); - Assert.AreEqual (42, ((NSNumber) value).Int32Value, "Int Value"); + Assert.That (value.GetType (), Is.EqualTo (typeof (NSNumber)), "Int Value Type"); + Assert.That (((NSNumber) value).Int32Value, Is.EqualTo (42), "Int Value"); } using (var dummy = CreateDummy ($"{long.MaxValue}")) { var value = dummy.Value; - Assert.AreEqual (typeof (NSNumber), value.GetType (), "Long Value Type"); - Assert.AreEqual (long.MaxValue, ((NSNumber) value).Int64Value, "Long Value"); + Assert.That (value.GetType (), Is.EqualTo (typeof (NSNumber)), "Long Value Type"); + Assert.That (((NSNumber) value).Int64Value, Is.EqualTo (long.MaxValue), "Long Value"); } using (var dummy = CreateDummy ($"3.1415926")) { var value = dummy.Value; - Assert.AreEqual (typeof (NSNumber), value.GetType (), "Real Value Type"); - Assert.AreEqual (3.1415926, ((NSNumber) value).FloatValue, 0.001, "Real PI Value"); + Assert.That (value.GetType (), Is.EqualTo (typeof (NSNumber)), "Real Value Type"); + Assert.That (((NSNumber) value).FloatValue, Is.EqualTo (3.1415926).Within (0.001), "Real PI Value"); } using (var dummy = CreateDummy ($"")) { var value = dummy.Value; - Assert.AreEqual (typeof (bool), value.GetType (), "Bool True Value Type"); - Assert.AreEqual (true, (bool) value, "Bool True Value"); + Assert.That (value.GetType (), Is.EqualTo (typeof (bool)), "Bool True Value Type"); + Assert.That ((bool) value, Is.EqualTo (true), "Bool True Value"); } using (var dummy = CreateDummy ($"")) { var value = dummy.Value; - Assert.AreEqual (typeof (bool), value.GetType (), "Bool True Value Type"); - Assert.AreEqual (false, (bool) value, "Bool True Value"); + Assert.That (value.GetType (), Is.EqualTo (typeof (bool)), "Bool True Value Type"); + Assert.That ((bool) value, Is.EqualTo (false), "Bool True Value"); } } @@ -180,7 +180,7 @@ CFPropertyList CreateDummy (string data = "SomeKeySomeS {data} "; var dummy = CFPropertyList.FromData (NSData.FromString (plist)); - Assert.IsNull (dummy.Error, "Dummy Error"); + Assert.That (dummy.Error, Is.Null, "Dummy Error"); return dummy.PropertyList; } } diff --git a/tests/monotouch-test/CoreFoundation/ProxyTest.cs b/tests/monotouch-test/CoreFoundation/ProxyTest.cs index 99c7c214d68b..3bd156d05b2e 100644 --- a/tests/monotouch-test/CoreFoundation/ProxyTest.cs +++ b/tests/monotouch-test/CoreFoundation/ProxyTest.cs @@ -18,23 +18,6 @@ namespace MonoTouchFixtures.CoreFoundation { [TestFixture] [Preserve (AllMembers = true)] public class ProxyTest { - - [Test] - public void Fields () - { - // documented but symbols are missing - // this test will fail if Apple decide to include them in the future - IntPtr lib = Dlfcn.dlopen (Constants.CoreFoundationLibrary, 0); - try { - // http://developer.apple.com/library/ios/documentation/CoreFoundation/Reference/CFProxySupport/Reference/reference.html#//apple_ref/doc/c_ref/kCFProxyAutoConfigurationHTTPResponseKey - Assert.That (Dlfcn.dlsym (lib, "kCFProxyAutoConfigurationHTTPResponseKey"), Is.EqualTo (IntPtr.Zero), "kCFProxyAutoConfigurationHTTPResponseKey"); - // http://developer.apple.com/library/ios/documentation/CoreFoundation/Reference/CFProxySupport/Reference/reference.html#//apple_ref/doc/c_ref/kCFNetworkProxiesProxyAutoConfigJavaScript - Assert.That (Dlfcn.dlsym (lib, "kCFNetworkProxiesProxyAutoConfigJavaScript"), Is.EqualTo (IntPtr.Zero), "kCFNetworkProxiesProxyAutoConfigJavaScript"); - } finally { - Dlfcn.dlclose (lib); - } - } - #if !MONOMAC HttpListener listener; int port; @@ -119,10 +102,10 @@ public void TestPACParsingScript () var script = File.ReadAllText (pacPath); var targetUri = NetworkResources.XamarinUri; var proxies = global::CoreFoundation.CFNetwork.ExecuteProxyAutoConfigurationScript (script, targetUri, out error); - Assert.IsNull (error, "Null error"); - Assert.AreEqual (1, proxies.Length, "Length"); + Assert.That (error, Is.Null, "Null error"); + Assert.That (proxies.Length, Is.EqualTo (1), "Length"); // assert the data of the proxy, although we are really testing the js used - Assert.AreEqual (8080, proxies [0].Port, "Port"); + Assert.That (proxies [0].Port, Is.EqualTo (8080), "Port"); } [Test] @@ -133,10 +116,10 @@ public void TestPACParsingScriptNoProxy () var script = File.ReadAllText (pacPath); var targetUri = NetworkResources.MicrosoftUri; var proxies = global::CoreFoundation.CFNetwork.ExecuteProxyAutoConfigurationScript (script, targetUri, out error); - Assert.IsNull (error, "Null error"); - Assert.IsNotNull (proxies, "Not null proxies"); - Assert.AreEqual (1, proxies.Length, "Proxies length"); - Assert.AreEqual (CFProxyType.None, proxies [0].ProxyType); + Assert.That (error, Is.Null, "Null error"); + Assert.That (proxies, Is.Not.Null, "Not null proxies"); + Assert.That (proxies.Length, Is.EqualTo (1), "Proxies length"); + Assert.That (proxies [0].ProxyType, Is.EqualTo (CFProxyType.None)); } [Test] @@ -146,8 +129,8 @@ public void TestPACParsingScriptError () var script = "Not VALID js"; var targetUri = NetworkResources.MicrosoftUri; var proxies = global::CoreFoundation.CFNetwork.ExecuteProxyAutoConfigurationScript (script, targetUri, out error); - Assert.IsNotNull (error, "Not null error"); - Assert.IsNull (proxies, "Null proxies"); + Assert.That (error, Is.Not.Null, "Not null error"); + Assert.That (proxies, Is.Null, "Null proxies"); } [Test] @@ -177,12 +160,12 @@ public void TestPACParsingAsync () done = true; } }, () => done); - Assert.IsNull (cbClient, "Null client"); - Assert.IsNull (error, "Null error"); - Assert.IsNotNull (proxies, "Not null proxies"); - Assert.AreEqual (1, proxies.Length, "Length"); + Assert.That (cbClient, Is.Null, "Null client"); + Assert.That (error, Is.Null, "Null error"); + Assert.That (proxies, Is.Not.Null, "Not null proxies"); + Assert.That (proxies.Length, Is.EqualTo (1), "Length"); // assert the data of the proxy, although we are really testing the js used - Assert.AreEqual (8080, proxies [0].Port, "Port"); + Assert.That (proxies [0].Port, Is.EqualTo (8080), "Port"); } [Test] @@ -214,11 +197,11 @@ public void TestPACParsingAsyncNoProxy () done = true; } }, () => done); - Assert.IsNull (cbClient, "Null client"); - Assert.IsNull (error, "Null error"); - Assert.IsNotNull (proxies, "Not null proxies"); - Assert.AreEqual (1, proxies.Length, "Proxies length"); - Assert.AreEqual (CFProxyType.None, proxies [0].ProxyType); + Assert.That (cbClient, Is.Null, "Null client"); + Assert.That (error, Is.Null, "Null error"); + Assert.That (proxies, Is.Not.Null, "Not null proxies"); + Assert.That (proxies.Length, Is.EqualTo (1), "Proxies length"); + Assert.That (proxies [0].ProxyType, Is.EqualTo (CFProxyType.None)); } [Test] @@ -228,10 +211,10 @@ public void TestPACParsingUrl () var pacUri = new Uri ($"http://localhost:{port}/example.pac"); var targetUri = NetworkResources.XamarinUri; var proxies = global::CoreFoundation.CFNetwork.ExecuteProxyAutoConfigurationUrl (pacUri, targetUri, out error); - Assert.IsNull (error, "Null error"); - Assert.AreEqual (1, proxies.Length, "Length"); + Assert.That (error, Is.Null, "Null error"); + Assert.That (proxies.Length, Is.EqualTo (1), "Length"); // assert the data of the proxy, although we are really testing the js used - Assert.AreEqual (8080, proxies [0].Port, "Port"); + Assert.That (proxies [0].Port, Is.EqualTo (8080), "Port"); } [Test] @@ -241,10 +224,10 @@ public void TestPacParsingUrlNoProxy () var pacUri = new Uri ($"http://localhost:{port}/example.pac"); var targetUri = NetworkResources.MicrosoftUri; var proxies = global::CoreFoundation.CFNetwork.ExecuteProxyAutoConfigurationUrl (pacUri, targetUri, out error); - Assert.IsNull (error, "Null error"); - Assert.IsNotNull (proxies, "Not null proxies"); - Assert.AreEqual (1, proxies.Length, "Proxies length"); - Assert.AreEqual (CFProxyType.None, proxies [0].ProxyType); + Assert.That (error, Is.Null, "Null error"); + Assert.That (proxies, Is.Not.Null, "Not null proxies"); + Assert.That (proxies.Length, Is.EqualTo (1), "Proxies length"); + Assert.That (proxies [0].ProxyType, Is.EqualTo (CFProxyType.None)); } [Test] @@ -272,12 +255,12 @@ public void TestPACParsingUrlAsync () done = true; } }, () => done); - Assert.IsNull (cbClient, "Null client"); - Assert.IsNull (error, "Null error"); - Assert.IsNotNull (proxies, "Not null proxies"); - Assert.AreEqual (1, proxies.Length, "Length"); + Assert.That (cbClient, Is.Null, "Null client"); + Assert.That (error, Is.Null, "Null error"); + Assert.That (proxies, Is.Not.Null, "Not null proxies"); + Assert.That (proxies.Length, Is.EqualTo (1), "Length"); // assert the data of the proxy, although we are really testing the js used - Assert.AreEqual (8080, proxies [0].Port, "Port"); + Assert.That (proxies [0].Port, Is.EqualTo (8080), "Port"); } [Test] @@ -306,11 +289,11 @@ public void TestPACParsingUrlAsyncNoProxy () done = true; } }, () => done); - Assert.IsNull (cbClient, "Null client"); - Assert.IsNull (error, "Null error"); - Assert.IsNotNull (proxies, "Not null proxies"); - Assert.AreEqual (1, proxies.Length, "Proxies length"); - Assert.AreEqual (CFProxyType.None, proxies [0].ProxyType); + Assert.That (cbClient, Is.Null, "Null client"); + Assert.That (error, Is.Null, "Null error"); + Assert.That (proxies, Is.Not.Null, "Not null proxies"); + Assert.That (proxies.Length, Is.EqualTo (1), "Proxies length"); + Assert.That (proxies [0].ProxyType, Is.EqualTo (CFProxyType.None)); } #endif } diff --git a/tests/monotouch-test/CoreFoundation/SocketTest.cs b/tests/monotouch-test/CoreFoundation/SocketTest.cs index 055a17b56f56..2e4a7c6cbb90 100644 --- a/tests/monotouch-test/CoreFoundation/SocketTest.cs +++ b/tests/monotouch-test/CoreFoundation/SocketTest.cs @@ -30,9 +30,9 @@ public void RetainCount () receiver.DataEvent += (o, a) => { var data = a.Data; - Assert.AreEqual (dataToSend.Length, data.Length); + Assert.That (data.Length, Is.EqualTo (dataToSend.Length)); for (int i = 0; i < data.Length; ++i) - Assert.AreEqual (dataToSend [i], data [i]); + Assert.That (data [i], Is.EqualTo (dataToSend [i])); received.Set (); }; @@ -79,9 +79,9 @@ public void Collected () receiver.SetAddress (IPAddress.Loopback, 0); receiver.DataEvent += (o, a) => { var data = a.Data; - Assert.AreEqual (dataToSend.Length, data.Length); + Assert.That (data.Length, Is.EqualTo (dataToSend.Length)); for (int i = 0; i < data.Length; ++i) - Assert.AreEqual (dataToSend [i], data [i]); + Assert.That (data [i], Is.EqualTo (dataToSend [i])); received.Set (); }; @@ -106,8 +106,8 @@ public void Collected () }; thread.Start (); - Assert.IsTrue (thread.Join (TimeSpan.FromSeconds (socketCount * 2)), "Completed"); - Assert.IsNull (ex, "No exceptions"); + Assert.That (thread.Join (TimeSpan.FromSeconds (socketCount * 2)), Is.True, "Completed"); + Assert.That (ex, Is.Null, "No exceptions"); GC.Collect (); GC.WaitForPendingFinalizers (); GC.Collect (); diff --git a/tests/monotouch-test/CoreFoundation/StringTest.cs b/tests/monotouch-test/CoreFoundation/StringTest.cs index 6a10688c42f2..885152896f7c 100644 --- a/tests/monotouch-test/CoreFoundation/StringTest.cs +++ b/tests/monotouch-test/CoreFoundation/StringTest.cs @@ -34,7 +34,7 @@ public void Index () using var nativeStr = new CFString (str); var array = str.ToCharArray (); for (int i = 0; i < array.Length; i++) { - Assert.AreEqual (str [i], nativeStr [i], $"{str [i]} != {nativeStr [i]}"); + Assert.That (nativeStr [i], Is.EqualTo (str [i]), $"{str [i]} != {nativeStr [i]}"); } } } diff --git a/tests/monotouch-test/CoreGraphics/AffineTransformTest.cs b/tests/monotouch-test/CoreGraphics/AffineTransformTest.cs index e16da0416ac7..fc01d11ddb80 100644 --- a/tests/monotouch-test/CoreGraphics/AffineTransformTest.cs +++ b/tests/monotouch-test/CoreGraphics/AffineTransformTest.cs @@ -19,20 +19,20 @@ public class AffineTransformTest { public void Ctor () { var transform = new CGAffineTransform (); - Assert.AreEqual ((nfloat) 0, transform.A); - Assert.AreEqual ((nfloat) 0, transform.B); - Assert.AreEqual ((nfloat) 0, transform.C); - Assert.AreEqual ((nfloat) 0, transform.D); - Assert.AreEqual ((nfloat) 0, transform.Tx); - Assert.AreEqual ((nfloat) 0, transform.Ty); + Assert.That (transform.A, Is.EqualTo ((nfloat) 0)); + Assert.That (transform.B, Is.EqualTo ((nfloat) 0)); + Assert.That (transform.C, Is.EqualTo ((nfloat) 0)); + Assert.That (transform.D, Is.EqualTo ((nfloat) 0)); + Assert.That (transform.Tx, Is.EqualTo ((nfloat) 0)); + Assert.That (transform.Ty, Is.EqualTo ((nfloat) 0)); transform = new CGAffineTransform (1, 2, 3, 4, 5, 6); - Assert.AreEqual ((nfloat) 1, transform.A); - Assert.AreEqual ((nfloat) 2, transform.B); - Assert.AreEqual ((nfloat) 3, transform.C); - Assert.AreEqual ((nfloat) 4, transform.D); - Assert.AreEqual ((nfloat) 5, transform.Tx); - Assert.AreEqual ((nfloat) 6, transform.Ty); + Assert.That (transform.A, Is.EqualTo ((nfloat) 1)); + Assert.That (transform.B, Is.EqualTo ((nfloat) 2)); + Assert.That (transform.C, Is.EqualTo ((nfloat) 3)); + Assert.That (transform.D, Is.EqualTo ((nfloat) 4)); + Assert.That (transform.Tx, Is.EqualTo ((nfloat) 5)); + Assert.That (transform.Ty, Is.EqualTo ((nfloat) 6)); } [Test] @@ -40,14 +40,14 @@ public void MakeIdentity () { var transform = CGAffineTransform.MakeIdentity (); - Assert.AreEqual ((nfloat) 1, transform.A, "A"); - Assert.AreEqual ((nfloat) 0, transform.B, "B"); - Assert.AreEqual ((nfloat) 0, transform.C, "C"); - Assert.AreEqual ((nfloat) 1, transform.D, "D"); - Assert.AreEqual ((nfloat) 0, transform.Tx, "Tx"); - Assert.AreEqual ((nfloat) 0, transform.Ty, "Ty"); + Assert.That (transform.A, Is.EqualTo ((nfloat) 1), "A"); + Assert.That (transform.B, Is.EqualTo ((nfloat) 0), "B"); + Assert.That (transform.C, Is.EqualTo ((nfloat) 0), "C"); + Assert.That (transform.D, Is.EqualTo ((nfloat) 1), "D"); + Assert.That (transform.Tx, Is.EqualTo ((nfloat) 0), "Tx"); + Assert.That (transform.Ty, Is.EqualTo ((nfloat) 0), "Ty"); - Assert.IsTrue (transform.IsIdentity, "identity"); + Assert.That (transform.IsIdentity, Is.True, "identity"); } [Test] @@ -55,10 +55,10 @@ public void MakeRotation () { var transform = CGAffineTransform.MakeRotation ((nfloat) Math.PI); - Assert.AreEqual ((nfloat) (-1), transform.A, "A"); + Assert.That (transform.A, Is.EqualTo ((nfloat) (-1)), "A"); Assert.That ((double) 0, Is.EqualTo ((double) transform.B).Within (0.0000001), "B"); Assert.That ((double) 0, Is.EqualTo ((double) transform.C).Within (0.0000001), "C"); - Assert.AreEqual ((nfloat) (-1), transform.D, "D"); + Assert.That (transform.D, Is.EqualTo ((nfloat) (-1)), "D"); Assert.That ((double) 0, Is.EqualTo ((double) transform.Tx).Within (0.0000001), "Tx"); Assert.That ((double) 0, Is.EqualTo ((double) transform.Ty).Within (0.0000001), "Ty"); } @@ -67,12 +67,12 @@ public void MakeRotation () public void MakeScale () { var transform = CGAffineTransform.MakeScale (314, 413); - Assert.AreEqual ((nfloat) 314, transform.A); - Assert.AreEqual ((nfloat) 0, transform.B); - Assert.AreEqual ((nfloat) 0, transform.C); - Assert.AreEqual ((nfloat) 413, transform.D); - Assert.AreEqual ((nfloat) 0, transform.Tx); - Assert.AreEqual ((nfloat) 0, transform.Ty); + Assert.That (transform.A, Is.EqualTo ((nfloat) 314)); + Assert.That (transform.B, Is.EqualTo ((nfloat) 0)); + Assert.That (transform.C, Is.EqualTo ((nfloat) 0)); + Assert.That (transform.D, Is.EqualTo ((nfloat) 413)); + Assert.That (transform.Tx, Is.EqualTo ((nfloat) 0)); + Assert.That (transform.Ty, Is.EqualTo ((nfloat) 0)); } [Test] @@ -80,12 +80,12 @@ public void MakeTranslation () { var transform = CGAffineTransform.MakeTranslation (12, 23); - Assert.AreEqual ((nfloat) 1, transform.A, "A"); - Assert.AreEqual ((nfloat) 0, transform.B, "B"); - Assert.AreEqual ((nfloat) 0, transform.C, "C"); - Assert.AreEqual ((nfloat) 1, transform.D, "D"); - Assert.AreEqual ((nfloat) 12, transform.Tx, "Tx"); - Assert.AreEqual ((nfloat) 23, transform.Ty, "Ty"); + Assert.That (transform.A, Is.EqualTo ((nfloat) 1), "A"); + Assert.That (transform.B, Is.EqualTo ((nfloat) 0), "B"); + Assert.That (transform.C, Is.EqualTo ((nfloat) 0), "C"); + Assert.That (transform.D, Is.EqualTo ((nfloat) 1), "D"); + Assert.That (transform.Tx, Is.EqualTo ((nfloat) 12), "Tx"); + Assert.That (transform.Ty, Is.EqualTo ((nfloat) 23), "Ty"); } [Test] @@ -95,12 +95,12 @@ public void Multiply () var transform = new CGAffineTransform (9, 8, 7, 6, 5, 4); transform.Multiply (a); - Assert.AreEqual ((nfloat) 33, transform.A, "A"); - Assert.AreEqual ((nfloat) 50, transform.B, "B"); - Assert.AreEqual ((nfloat) 25, transform.C, "C"); - Assert.AreEqual ((nfloat) 38, transform.D, "D"); - Assert.AreEqual ((nfloat) 22, transform.Tx, "Tx"); - Assert.AreEqual ((nfloat) 32, transform.Ty, "Ty"); + Assert.That (transform.A, Is.EqualTo ((nfloat) 33), "A"); + Assert.That (transform.B, Is.EqualTo ((nfloat) 50), "B"); + Assert.That (transform.C, Is.EqualTo ((nfloat) 25), "C"); + Assert.That (transform.D, Is.EqualTo ((nfloat) 38), "D"); + Assert.That (transform.Tx, Is.EqualTo ((nfloat) 22), "Tx"); + Assert.That (transform.Ty, Is.EqualTo ((nfloat) 32), "Ty"); } [Test] @@ -110,12 +110,12 @@ public void StaticMultiply () var b = new CGAffineTransform (9, 8, 7, 6, 5, 4); var transform = CGAffineTransform.Multiply (a, b); - Assert.AreEqual ((nfloat) 23, transform.A, "A"); - Assert.AreEqual ((nfloat) 20, transform.B, "B"); - Assert.AreEqual ((nfloat) 55, transform.C, "C"); - Assert.AreEqual ((nfloat) 48, transform.D, "D"); - Assert.AreEqual ((nfloat) 92, transform.Tx, "Tx"); - Assert.AreEqual ((nfloat) 80, transform.Ty, "Ty"); + Assert.That (transform.A, Is.EqualTo ((nfloat) 23), "A"); + Assert.That (transform.B, Is.EqualTo ((nfloat) 20), "B"); + Assert.That (transform.C, Is.EqualTo ((nfloat) 55), "C"); + Assert.That (transform.D, Is.EqualTo ((nfloat) 48), "D"); + Assert.That (transform.Tx, Is.EqualTo ((nfloat) 92), "Tx"); + Assert.That (transform.Ty, Is.EqualTo ((nfloat) 80), "Ty"); } [Test] public void Scale () @@ -124,23 +124,23 @@ public void Scale () // t' = t * [ sx 0 0 sy 0 0 ] transform1.Scale (3, 4); // MatrixOrder.Append by default - Assert.AreEqual ((nfloat) 3, transform1.A); - Assert.AreEqual ((nfloat) 0, transform1.B); - Assert.AreEqual ((nfloat) 0, transform1.C); - Assert.AreEqual ((nfloat) 4, transform1.D); - Assert.AreEqual ((nfloat) 3, transform1.Tx); - Assert.AreEqual ((nfloat) 8, transform1.Ty); + Assert.That (transform1.A, Is.EqualTo ((nfloat) 3)); + Assert.That (transform1.B, Is.EqualTo ((nfloat) 0)); + Assert.That (transform1.C, Is.EqualTo ((nfloat) 0)); + Assert.That (transform1.D, Is.EqualTo ((nfloat) 4)); + Assert.That (transform1.Tx, Is.EqualTo ((nfloat) 3)); + Assert.That (transform1.Ty, Is.EqualTo ((nfloat) 8)); var transform2 = CGAffineTransform.MakeTranslation (1, 2); // t' = [ sx 0 0 sy 0 0 ] * t – Swift equivalent transform2.Scale (3, 4, MatrixOrder.Prepend); - Assert.AreEqual ((nfloat) 3, transform2.A); - Assert.AreEqual ((nfloat) 0, transform2.B); - Assert.AreEqual ((nfloat) 0, transform2.C); - Assert.AreEqual ((nfloat) 4, transform2.D); - Assert.AreEqual ((nfloat) 1, transform2.Tx); - Assert.AreEqual ((nfloat) 2, transform2.Ty); + Assert.That (transform2.A, Is.EqualTo ((nfloat) 3)); + Assert.That (transform2.B, Is.EqualTo ((nfloat) 0)); + Assert.That (transform2.C, Is.EqualTo ((nfloat) 0)); + Assert.That (transform2.D, Is.EqualTo ((nfloat) 4)); + Assert.That (transform2.Tx, Is.EqualTo ((nfloat) 1)); + Assert.That (transform2.Ty, Is.EqualTo ((nfloat) 2)); } [Test] @@ -149,12 +149,12 @@ public void StaticScale () var transformM = CGAffineTransform.Scale (CGAffineTransform.MakeTranslation (0, 200), 1, -1); var transformN = CGAffineTransformScale (CGAffineTransform.MakeTranslation (0, 200), 1, -1); - Assert.IsTrue (transformM == transformN, "1"); + Assert.That (transformM == transformN, Is.True, "1"); transformM = CGAffineTransform.Scale (CGAffineTransform.MakeTranslation (1, 2), -3, -4); transformN = CGAffineTransformScale (CGAffineTransform.MakeTranslation (1, 2), -3, -4); - Assert.IsTrue (transformM == transformN, "2"); + Assert.That (transformM == transformN, Is.True, "2"); } [DllImport (global::ObjCRuntime.Constants.CoreGraphicsLibrary)] @@ -166,32 +166,32 @@ public void Translate () var transform = CGAffineTransform.MakeIdentity (); transform.Translate (1, -1); // MatrixOrder.Append by default - Assert.AreEqual ((nfloat) 1, transform.A, "A"); - Assert.AreEqual ((nfloat) 0, transform.B, "B"); - Assert.AreEqual ((nfloat) 0, transform.C, "C"); - Assert.AreEqual ((nfloat) 1, transform.D, "D"); - Assert.AreEqual ((nfloat) 1, transform.Tx, "Tx"); - Assert.AreEqual ((nfloat) (-1), transform.Ty, "Ty"); + Assert.That (transform.A, Is.EqualTo ((nfloat) 1), "A"); + Assert.That (transform.B, Is.EqualTo ((nfloat) 0), "B"); + Assert.That (transform.C, Is.EqualTo ((nfloat) 0), "C"); + Assert.That (transform.D, Is.EqualTo ((nfloat) 1), "D"); + Assert.That (transform.Tx, Is.EqualTo ((nfloat) 1), "Tx"); + Assert.That (transform.Ty, Is.EqualTo ((nfloat) (-1)), "Ty"); transform = new CGAffineTransform (1, 2, 3, 4, 5, 6); transform.Translate (2, -3); - Assert.AreEqual ((nfloat) 1, transform.A, "A"); - Assert.AreEqual ((nfloat) 2, transform.B, "B"); - Assert.AreEqual ((nfloat) 3, transform.C, "C"); - Assert.AreEqual ((nfloat) 4, transform.D, "D"); - Assert.AreEqual ((nfloat) 7, transform.Tx, "Tx"); - Assert.AreEqual ((nfloat) 3, transform.Ty, "Ty"); + Assert.That (transform.A, Is.EqualTo ((nfloat) 1), "A"); + Assert.That (transform.B, Is.EqualTo ((nfloat) 2), "B"); + Assert.That (transform.C, Is.EqualTo ((nfloat) 3), "C"); + Assert.That (transform.D, Is.EqualTo ((nfloat) 4), "D"); + Assert.That (transform.Tx, Is.EqualTo ((nfloat) 7), "Tx"); + Assert.That (transform.Ty, Is.EqualTo ((nfloat) 3), "Ty"); transform = new CGAffineTransform (1, 2, 3, 4, 5, 6); transform.Translate (2, -3, MatrixOrder.Prepend); - Assert.AreEqual ((nfloat) 1, transform.A, "A"); - Assert.AreEqual ((nfloat) 2, transform.B, "B"); - Assert.AreEqual ((nfloat) 3, transform.C, "C"); - Assert.AreEqual ((nfloat) 4, transform.D, "D"); - Assert.AreEqual ((nfloat) (-2), transform.Tx, "Tx"); - Assert.AreEqual ((nfloat) (-2), transform.Ty, "Ty"); + Assert.That (transform.A, Is.EqualTo ((nfloat) 1), "A"); + Assert.That (transform.B, Is.EqualTo ((nfloat) 2), "B"); + Assert.That (transform.C, Is.EqualTo ((nfloat) 3), "C"); + Assert.That (transform.D, Is.EqualTo ((nfloat) 4), "D"); + Assert.That (transform.Tx, Is.EqualTo ((nfloat) (-2)), "Tx"); + Assert.That (transform.Ty, Is.EqualTo ((nfloat) (-2)), "Ty"); } [Test] @@ -201,25 +201,25 @@ public void StaticTranslate () var transformM = CGAffineTransform.Translate (origin, 1, -1); var transformN = CGAffineTransformTranslate (origin, 1, -1); - Assert.AreEqual ((nfloat) 1, transformM.A, "A"); - Assert.AreEqual ((nfloat) 0, transformM.B, "B"); - Assert.AreEqual ((nfloat) 0, transformM.C, "C"); - Assert.AreEqual ((nfloat) 1, transformM.D, "D"); - Assert.AreEqual ((nfloat) 1, transformM.Tx, "Tx"); - Assert.AreEqual ((nfloat) (-1), transformM.Ty, "Ty"); - Assert.IsTrue (transformN == transformM); + Assert.That (transformM.A, Is.EqualTo ((nfloat) 1), "A"); + Assert.That (transformM.B, Is.EqualTo ((nfloat) 0), "B"); + Assert.That (transformM.C, Is.EqualTo ((nfloat) 0), "C"); + Assert.That (transformM.D, Is.EqualTo ((nfloat) 1), "D"); + Assert.That (transformM.Tx, Is.EqualTo ((nfloat) 1), "Tx"); + Assert.That (transformM.Ty, Is.EqualTo ((nfloat) (-1)), "Ty"); + Assert.That (transformN == transformM, Is.True); origin = new CGAffineTransform (1, 2, 3, 4, 5, 6); transformM = CGAffineTransform.Translate (origin, 2, -3); transformN = CGAffineTransformTranslate (origin, 2, -3); - Assert.AreEqual ((nfloat) 1, transformM.A, "A"); - Assert.AreEqual ((nfloat) 2, transformM.B, "B"); - Assert.AreEqual ((nfloat) 3, transformM.C, "C"); - Assert.AreEqual ((nfloat) 4, transformM.D, "D"); - Assert.AreEqual ((nfloat) (-2), transformM.Tx, "Tx"); - Assert.AreEqual ((nfloat) (-2), transformM.Ty, "Ty"); - Assert.IsTrue (transformN == transformM); + Assert.That (transformM.A, Is.EqualTo ((nfloat) 1), "A"); + Assert.That (transformM.B, Is.EqualTo ((nfloat) 2), "B"); + Assert.That (transformM.C, Is.EqualTo ((nfloat) 3), "C"); + Assert.That (transformM.D, Is.EqualTo ((nfloat) 4), "D"); + Assert.That (transformM.Tx, Is.EqualTo ((nfloat) (-2)), "Tx"); + Assert.That (transformM.Ty, Is.EqualTo ((nfloat) (-2)), "Ty"); + Assert.That (transformN == transformM, Is.True); } [DllImport (global::ObjCRuntime.Constants.CoreGraphicsLibrary)] @@ -276,8 +276,8 @@ public void StaticRotate () [Test] public void IsIdentity () { - Assert.IsTrue (CGAffineTransform.MakeIdentity ().IsIdentity, "MakeIdentity"); - Assert.IsFalse (new CGAffineTransform (1, 2, 3, 4, 5, 6).IsIdentity, "123456"); + Assert.That (CGAffineTransform.MakeIdentity ().IsIdentity, Is.True, "MakeIdentity"); + Assert.That (new CGAffineTransform (1, 2, 3, 4, 5, 6).IsIdentity, Is.False, "123456"); } [Test] @@ -286,8 +286,8 @@ public void TransformPoint () var transform = new CGAffineTransform (1, 2, 3, 4, 5, 6); var point = transform.TransformPoint (new CGPoint (4, 5)); - Assert.AreEqual ((nfloat) 24, point.X, "X"); - Assert.AreEqual ((nfloat) 34, point.Y, "Y"); + Assert.That (point.X, Is.EqualTo ((nfloat) 24), "X"); + Assert.That (point.Y, Is.EqualTo ((nfloat) 34), "Y"); } [Test] @@ -296,10 +296,10 @@ public void TransformRect () var transform = new CGAffineTransform (1, 2, 3, 4, 5, 6); var rect = transform.TransformRect (new CGRect (4, 5, 6, 7)); - Assert.AreEqual ((nfloat) 24, rect.X, "X"); - Assert.AreEqual ((nfloat) 34, rect.Y, "Y"); - Assert.AreEqual ((nfloat) 27, rect.Width, "Width"); - Assert.AreEqual ((nfloat) 40, rect.Height, "Height"); + Assert.That (rect.X, Is.EqualTo ((nfloat) 24), "X"); + Assert.That (rect.Y, Is.EqualTo ((nfloat) 34), "Y"); + Assert.That (rect.Width, Is.EqualTo ((nfloat) 27), "Width"); + Assert.That (rect.Height, Is.EqualTo ((nfloat) 40), "Height"); } [Test] @@ -307,12 +307,12 @@ public void Invert () { var transform = new CGAffineTransform (1, 2, 3, 4, 5, 6).Invert (); - Assert.AreEqual ((nfloat) (-2), transform.A, "A"); - Assert.AreEqual ((nfloat) 1, transform.B, "B"); - Assert.AreEqual ((nfloat) 1.5, transform.C, "C"); - Assert.AreEqual ((nfloat) (-0.5), transform.D, "D"); - Assert.AreEqual ((nfloat) 1.0, transform.Tx, "Tx"); - Assert.AreEqual ((nfloat) (-2.0), transform.Ty, "Ty"); + Assert.That (transform.A, Is.EqualTo ((nfloat) (-2)), "A"); + Assert.That (transform.B, Is.EqualTo ((nfloat) 1), "B"); + Assert.That (transform.C, Is.EqualTo ((nfloat) 1.5), "C"); + Assert.That (transform.D, Is.EqualTo ((nfloat) (-0.5)), "D"); + Assert.That (transform.Tx, Is.EqualTo ((nfloat) 1.0), "Tx"); + Assert.That (transform.Ty, Is.EqualTo ((nfloat) (-2.0)), "Ty"); } [Test] @@ -321,10 +321,10 @@ public void Decompose () TestRuntime.AssertXcodeVersion (14, 0); var components = new CGAffineTransform (1, 2, 3, 4, 5, 6).Decompose (); - Assert.AreNotEqual (0.0, components.Scale); - Assert.AreNotEqual (0.0, components.HorizontalShear); - Assert.AreNotEqual (0.0, components.Rotation); - Assert.AreNotEqual (new CGVector ((nfloat) 0, (nfloat) 0), components.Translation); + Assert.That (components.Scale, Is.Not.EqualTo (0.0)); + Assert.That (components.HorizontalShear, Is.Not.EqualTo (0.0)); + Assert.That (components.Rotation, Is.Not.EqualTo (0.0)); + Assert.That (components.Translation, Is.Not.EqualTo (new CGVector ((nfloat) 0, (nfloat) 0))); } [Test] @@ -339,12 +339,12 @@ public void MakeWithComponents () Translation = new CGVector ((nfloat) 5.0, (nfloat) 6.0), }; var transform = CGAffineTransform.MakeWithComponents (components); - Assert.AreNotEqual (0.0, transform.A); - Assert.AreNotEqual (0.0, transform.B); - Assert.AreNotEqual (0.0, transform.C); - Assert.AreNotEqual (0.0, transform.D); - Assert.AreNotEqual (0.0, transform.Tx); - Assert.AreNotEqual (0.0, transform.Ty); + Assert.That (transform.A, Is.Not.EqualTo (0.0)); + Assert.That (transform.B, Is.Not.EqualTo (0.0)); + Assert.That (transform.C, Is.Not.EqualTo (0.0)); + Assert.That (transform.D, Is.Not.EqualTo (0.0)); + Assert.That (transform.Tx, Is.Not.EqualTo (0.0)); + Assert.That (transform.Ty, Is.Not.EqualTo (0.0)); } [Test] @@ -354,26 +354,26 @@ public void NSValueRoundtrip () // looks simplistic but that NSValue logic is implemented by "us" on macOS using (var nsv = NSValue.FromCGAffineTransform (transform)) { var tback = nsv.CGAffineTransformValue; - Assert.AreEqual ((nfloat) 1, tback.A, "A"); - Assert.AreEqual ((nfloat) 2, tback.B, "B"); - Assert.AreEqual ((nfloat) 3, tback.C, "C"); - Assert.AreEqual ((nfloat) 4, tback.D, "D"); - Assert.AreEqual ((nfloat) 5, tback.Tx, "Tx"); - Assert.AreEqual ((nfloat) 6, tback.Ty, "Ty"); + Assert.That (tback.A, Is.EqualTo ((nfloat) 1), "A"); + Assert.That (tback.B, Is.EqualTo ((nfloat) 2), "B"); + Assert.That (tback.C, Is.EqualTo ((nfloat) 3), "C"); + Assert.That (tback.D, Is.EqualTo ((nfloat) 4), "D"); + Assert.That (tback.Tx, Is.EqualTo ((nfloat) 5), "Tx"); + Assert.That (tback.Ty, Is.EqualTo ((nfloat) 6), "Ty"); } } [Test] public unsafe void SizeOfTest () { - Assert.AreEqual (sizeof (CGAffineTransform), Marshal.SizeOf ()); + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (CGAffineTransform))); } [Test] public void ToStringTest () { var transform = new CGAffineTransform ((nfloat) 1, (nfloat) 2, (nfloat) 3, (nfloat) 4, (nfloat) 5, (nfloat) 6); - Assert.AreEqual ("[1, 2, 3, 4, 5, 6]", transform.ToString (), "ToString"); + Assert.That (transform.ToString (), Is.EqualTo ("[1, 2, 3, 4, 5, 6]"), "ToString"); } } diff --git a/tests/monotouch-test/CoreGraphics/BitmapContextTest.cs b/tests/monotouch-test/CoreGraphics/BitmapContextTest.cs index 65808abd2093..b82d8e942434 100644 --- a/tests/monotouch-test/CoreGraphics/BitmapContextTest.cs +++ b/tests/monotouch-test/CoreGraphics/BitmapContextTest.cs @@ -91,7 +91,7 @@ public void Ctor_CGColorSpace_Null () // OTOH a null colorspace is possible with the valid parameters, e.g. bug #25600, so we can't throw a ANE blindly using (var context = new CGBitmapContext (null, 16, 32, 8, 0, null, CGImageAlphaInfo.Only)) { Assert.That (context.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); - Assert.Null (context.ColorSpace, "ColorSpace"); + Assert.That (context.ColorSpace, Is.Null, "ColorSpace"); } } @@ -102,9 +102,9 @@ public void ToImage () using (CGColorSpace space = CGColorSpace.CreateDeviceRGB ()) { CGBitmapContext c = new CGBitmapContext (data, 10, 10, 8, 40, space, CGImageAlphaInfo.PremultipliedLast); using (var img = c.ToImage ()) - Assert.NotNull (img, "ToImage"); + Assert.That (img, Is.Not.Null, "ToImage"); c.Dispose (); // Handle is now 0x0 - Assert.Null (c.ToImage (), "ToImage/Disposed"); + Assert.That (c.ToImage (), Is.Null, "ToImage/Disposed"); } } @@ -118,7 +118,7 @@ public void CreateAdaptive_1 () using (var pool = new NSAutoreleasePool ()) { using var context = CGBitmapContext.Create (width, height, (NSDictionary?) null, null, null, null, null); - Assert.NotNull (context, "Context#1"); + Assert.That (context, Is.Not.Null, "Context#1"); } } @@ -177,10 +177,10 @@ public void CreateAdaptive_2 () calledOnError = true; }); - Assert.NotNull (context, "Context#2"); + Assert.That (context, Is.Not.Null, "Context#2"); using var img = context.ToImage (); - Assert.NotNull (img, "ToImage"); + Assert.That (img, Is.Not.Null, "ToImage"); } Assert.That (calledOnResolve, Is.True, "calledOnResolve#2"); @@ -252,10 +252,10 @@ public void CreateAdaptive_3 () calledOnError = true; }); - Assert.NotNull (context, "Context#3"); + Assert.That (context, Is.Not.Null, "Context#3"); using var img = context.ToImage (); - Assert.NotNull (img, "ToImage"); + Assert.That (img, Is.Not.Null, "ToImage"); } Assert.That (calledOnResolve, Is.True, "calledOnResolve#3"); @@ -328,10 +328,10 @@ public void CreateAdaptive_4 () calledOnError = true; })) { - Assert.NotNull (context, "Context#4"); + Assert.That (context, Is.Not.Null, "Context#4"); using var img = context.ToImage (); - Assert.NotNull (img, "ToImage"); + Assert.That (img, Is.Not.Null, "ToImage"); } Assert.That (calledOnResolve, Is.True, "calledOnResolve#4"); diff --git a/tests/monotouch-test/CoreGraphics/CGBitmapInfoTest.cs b/tests/monotouch-test/CoreGraphics/CGBitmapInfoTest.cs index beb200179142..9ed174008732 100644 --- a/tests/monotouch-test/CoreGraphics/CGBitmapInfoTest.cs +++ b/tests/monotouch-test/CoreGraphics/CGBitmapInfoTest.cs @@ -11,10 +11,10 @@ public class CGBitmapInfoTest { [Test] public void Extensions () { - Assert.AreEqual (CGImageAlphaInfo.PremultipliedLast, ((CGBitmapInfo) CGImageAlphaInfo.PremultipliedLast).GetAlphaInfo (), "GetAlphaInfo"); - Assert.AreEqual (CGImageComponentInfo.Float, ((CGBitmapInfo) CGImageComponentInfo.Float).GetComponentInfo (), "CGImageComponentInfo"); - Assert.AreEqual (CGImageByteOrderInfo.ByteOrder32Little, ((CGBitmapInfo) CGImageByteOrderInfo.ByteOrder32Little).GetByteOrderInfo (), "CGImageByteOrderInfo"); - Assert.AreEqual (CGImagePixelFormatInfo.Rgb101010, ((CGBitmapInfo) CGImagePixelFormatInfo.Rgb101010).GetPixelFormatInfo (), "CGImagePixelFormatInfo"); + Assert.That (((CGBitmapInfo) CGImageAlphaInfo.PremultipliedLast).GetAlphaInfo (), Is.EqualTo (CGImageAlphaInfo.PremultipliedLast), "GetAlphaInfo"); + Assert.That (((CGBitmapInfo) CGImageComponentInfo.Float).GetComponentInfo (), Is.EqualTo (CGImageComponentInfo.Float), "CGImageComponentInfo"); + Assert.That (((CGBitmapInfo) CGImageByteOrderInfo.ByteOrder32Little).GetByteOrderInfo (), Is.EqualTo (CGImageByteOrderInfo.ByteOrder32Little), "CGImageByteOrderInfo"); + Assert.That (((CGBitmapInfo) CGImagePixelFormatInfo.Rgb101010).GetPixelFormatInfo (), Is.EqualTo (CGImagePixelFormatInfo.Rgb101010), "CGImagePixelFormatInfo"); } } } diff --git a/tests/monotouch-test/CoreGraphics/CGBitmapParametersTest.cs b/tests/monotouch-test/CoreGraphics/CGBitmapParametersTest.cs index 8cb40d127e82..12b01a981e7b 100644 --- a/tests/monotouch-test/CoreGraphics/CGBitmapParametersTest.cs +++ b/tests/monotouch-test/CoreGraphics/CGBitmapParametersTest.cs @@ -16,17 +16,17 @@ public void DefaultValuesTest () { Assert.Multiple (() => { var p = new CGBitmapParameters (); - Assert.AreEqual ((nuint) 0u, p.Width, "Width"); - Assert.AreEqual ((nuint) 0u, p.Height, "Height"); - Assert.AreEqual ((nuint) 0u, p.BytesPerPixel, "BytesPerPixel"); - Assert.AreEqual ((nuint) 0u, p.AlignedBytesPerRow, "AlignedBytesPerRow"); - Assert.AreEqual (default (CGComponent), p.Component, "Component"); - Assert.AreEqual (default (CGBitmapLayout), p.Layout, "Layout"); - Assert.AreEqual (default (CGImagePixelFormatInfo), p.Format, "Format"); - Assert.AreEqual (IntPtr.Zero, p.ColorSpaceHandle, "ColorSpaceHandle"); - Assert.AreEqual (false, p.HasPremultipliedAlpha, "HasPremultipliedAlpha"); - Assert.AreEqual ((CFByteOrder) 0, p.ByteOrder, "ByteOrder"); - Assert.AreEqual (0f, p.EdrTargetHeadroom, "EdrTargetHeadroom"); + Assert.That (p.Width, Is.EqualTo ((nuint) 0u), "Width"); + Assert.That (p.Height, Is.EqualTo ((nuint) 0u), "Height"); + Assert.That (p.BytesPerPixel, Is.EqualTo ((nuint) 0u), "BytesPerPixel"); + Assert.That (p.AlignedBytesPerRow, Is.EqualTo ((nuint) 0u), "AlignedBytesPerRow"); + Assert.That (p.Component, Is.EqualTo (default (CGComponent)), "Component"); + Assert.That (p.Layout, Is.EqualTo (default (CGBitmapLayout)), "Layout"); + Assert.That (p.Format, Is.EqualTo (default (CGImagePixelFormatInfo)), "Format"); + Assert.That (p.ColorSpaceHandle, Is.EqualTo (IntPtr.Zero), "ColorSpaceHandle"); + Assert.That (p.HasPremultipliedAlpha, Is.EqualTo (false), "HasPremultipliedAlpha"); + Assert.That (p.ByteOrder, Is.EqualTo ((CFByteOrder) 0), "ByteOrder"); + Assert.That (p.EdrTargetHeadroom, Is.EqualTo (0f), "EdrTargetHeadroom"); }); } @@ -47,17 +47,17 @@ public void PropertySetGetTest () p.ByteOrder = CFByteOrder.LittleEndian; p.EdrTargetHeadroom = 1.5f; - Assert.AreEqual ((nuint) 123u, p.Width, "Width"); - Assert.AreEqual ((nuint) 456u, p.Height, "Height"); - Assert.AreEqual ((nuint) 4u, p.BytesPerPixel, "BytesPerPixel"); - Assert.AreEqual ((nuint) 512u, p.AlignedBytesPerRow, "AlignedBytesPerRow"); - Assert.AreEqual ((CGComponent) 1, p.Component, "Component"); - Assert.AreEqual ((CGBitmapLayout) 2, p.Layout, "Layout"); - Assert.AreEqual ((CGImagePixelFormatInfo) 3, p.Format, "Format"); - Assert.AreEqual (new IntPtr (0xDEADBEEF), p.ColorSpaceHandle, "ColorSpaceHandle"); - Assert.IsTrue (p.HasPremultipliedAlpha, "HasPremultipliedAlpha"); - Assert.AreEqual (CFByteOrder.LittleEndian, p.ByteOrder, "ByteOrder"); - Assert.AreEqual (1.5f, p.EdrTargetHeadroom, "EdrTargetHeadroom"); + Assert.That (p.Width, Is.EqualTo ((nuint) 123u), "Width"); + Assert.That (p.Height, Is.EqualTo ((nuint) 456u), "Height"); + Assert.That (p.BytesPerPixel, Is.EqualTo ((nuint) 4u), "BytesPerPixel"); + Assert.That (p.AlignedBytesPerRow, Is.EqualTo ((nuint) 512u), "AlignedBytesPerRow"); + Assert.That (p.Component, Is.EqualTo ((CGComponent) 1), "Component"); + Assert.That (p.Layout, Is.EqualTo ((CGBitmapLayout) 2), "Layout"); + Assert.That (p.Format, Is.EqualTo ((CGImagePixelFormatInfo) 3), "Format"); + Assert.That (p.ColorSpaceHandle, Is.EqualTo (new IntPtr (0xDEADBEEF)), "ColorSpaceHandle"); + Assert.That (p.HasPremultipliedAlpha, Is.True, "HasPremultipliedAlpha"); + Assert.That (p.ByteOrder, Is.EqualTo (CFByteOrder.LittleEndian), "ByteOrder"); + Assert.That (p.EdrTargetHeadroom, Is.EqualTo (1.5f), "EdrTargetHeadroom"); }); } @@ -66,7 +66,7 @@ public void HasPremultipliedAlphaFalseTest () { var p = new CGBitmapParameters (); p.HasPremultipliedAlpha = false; - Assert.IsFalse (p.HasPremultipliedAlpha, "HasPremultipliedAlpha"); + Assert.That (p.HasPremultipliedAlpha, Is.False, "HasPremultipliedAlpha"); } [Test] @@ -74,9 +74,9 @@ public void ByteOrderTest () { var p = new CGBitmapParameters (); p.ByteOrder = CFByteOrder.BigEndian; - Assert.AreEqual (CFByteOrder.BigEndian, p.ByteOrder, "ByteOrder"); + Assert.That (p.ByteOrder, Is.EqualTo (CFByteOrder.BigEndian), "ByteOrder"); p.ByteOrder = CFByteOrder.LittleEndian; - Assert.AreEqual (CFByteOrder.LittleEndian, p.ByteOrder, "ByteOrder"); + Assert.That (p.ByteOrder, Is.EqualTo (CFByteOrder.LittleEndian), "ByteOrder"); } } } diff --git a/tests/monotouch-test/CoreGraphics/CGContentInfoTest.cs b/tests/monotouch-test/CoreGraphics/CGContentInfoTest.cs index 0e0416e93e00..67c68886c8cc 100644 --- a/tests/monotouch-test/CoreGraphics/CGContentInfoTest.cs +++ b/tests/monotouch-test/CoreGraphics/CGContentInfoTest.cs @@ -15,11 +15,11 @@ public class CGContentInfoTest { public void DefaultValuesTest () { var c = new CGContentInfo (); - Assert.AreEqual (default (CGComponent), c.DeepestImageComponent, "DeepestImageComponent"); - Assert.AreEqual (default (CGColorModel), c.ContentColorModels, "ContentColorModels"); - Assert.IsFalse (c.HasWideGamut, "HasWideGamut"); - Assert.IsFalse (c.HasTransparency, "HasTransparency"); - Assert.AreEqual (0f, c.LargestContentHeadroom, "LargestContentHeadroom"); + Assert.That (c.DeepestImageComponent, Is.EqualTo (default (CGComponent)), "DeepestImageComponent"); + Assert.That (c.ContentColorModels, Is.EqualTo (default (CGColorModel)), "ContentColorModels"); + Assert.That (c.HasWideGamut, Is.False, "HasWideGamut"); + Assert.That (c.HasTransparency, Is.False, "HasTransparency"); + Assert.That (c.LargestContentHeadroom, Is.EqualTo (0f), "LargestContentHeadroom"); } [Test] @@ -32,11 +32,11 @@ public void PropertySetGetTest () c.HasTransparency = true; c.LargestContentHeadroom = 1.25f; - Assert.AreEqual ((CGComponent) 2, c.DeepestImageComponent, "DeepestImageComponent"); - Assert.AreEqual ((CGColorModel) 3, c.ContentColorModels, "ContentColorModels"); - Assert.IsTrue (c.HasWideGamut, "HasWideGamut"); - Assert.IsTrue (c.HasTransparency, "HasTransparency"); - Assert.AreEqual (1.25f, c.LargestContentHeadroom, "LargestContentHeadroom"); + Assert.That (c.DeepestImageComponent, Is.EqualTo ((CGComponent) 2), "DeepestImageComponent"); + Assert.That (c.ContentColorModels, Is.EqualTo ((CGColorModel) 3), "ContentColorModels"); + Assert.That (c.HasWideGamut, Is.True, "HasWideGamut"); + Assert.That (c.HasTransparency, Is.True, "HasTransparency"); + Assert.That (c.LargestContentHeadroom, Is.EqualTo (1.25f), "LargestContentHeadroom"); } [Test] @@ -44,7 +44,7 @@ public void HasWideGamutFalseTest () { var c = new CGContentInfo (); c.HasWideGamut = false; - Assert.IsFalse (c.HasWideGamut, "HasWideGamut"); + Assert.That (c.HasWideGamut, Is.False, "HasWideGamut"); } [Test] @@ -52,7 +52,7 @@ public void HasTransparencyFalseTest () { var c = new CGContentInfo (); c.HasTransparency = false; - Assert.IsFalse (c.HasTransparency, "HasTransparency"); + Assert.That (c.HasTransparency, Is.False, "HasTransparency"); } } } diff --git a/tests/monotouch-test/CoreGraphics/CGContentToneMappingInfoTest.cs b/tests/monotouch-test/CoreGraphics/CGContentToneMappingInfoTest.cs index c98155dea2b0..b02af632abfc 100644 --- a/tests/monotouch-test/CoreGraphics/CGContentToneMappingInfoTest.cs +++ b/tests/monotouch-test/CoreGraphics/CGContentToneMappingInfoTest.cs @@ -17,9 +17,9 @@ public void DefaultValuesTest () TestRuntime.AssertXcodeVersion (16, 0); var t = new CGContentToneMappingInfo (); - Assert.AreEqual (CGToneMapping.Default, t.Method, "Method"); - Assert.IsNull (t.Options, "Options"); - Assert.IsNull (t.ToneMappingOptions, "ToneMappingOptions"); + Assert.That (t.Method, Is.EqualTo (CGToneMapping.Default), "Method"); + Assert.That (t.Options, Is.Null, "Options"); + Assert.That (t.ToneMappingOptions, Is.Null, "ToneMappingOptions"); } [Test] @@ -29,37 +29,37 @@ public void PropertySetGetTest () var t = new CGContentToneMappingInfo (); t.Method = CGToneMapping.ImageSpecificLumaScaling; - Assert.AreEqual (CGToneMapping.ImageSpecificLumaScaling, t.Method, "Method#1"); + Assert.That (t.Method, Is.EqualTo (CGToneMapping.ImageSpecificLumaScaling), "Method#1"); t.Method = CGToneMapping.Default; - Assert.AreEqual (CGToneMapping.Default, t.Method, "Method#2"); + Assert.That (t.Method, Is.EqualTo (CGToneMapping.Default), "Method#2"); using var dict = new NSDictionary (); t.Options = dict; - Assert.AreSame (dict, t.Options, "Options#1"); + Assert.That (t.Options, Is.SameAs (dict), "Options#1"); var toneMappingOptions = t.ToneMappingOptions!; - Assert.AreSame (dict, toneMappingOptions.Dictionary, "ToneMappingOptions#1"); + Assert.That (toneMappingOptions.Dictionary, Is.SameAs (dict), "ToneMappingOptions#1"); - Assert.IsFalse (toneMappingOptions.Use100nitsHlgOotf.HasValue, "ToneMappingOptions.Use100nitsHlgOotf #1"); - Assert.IsFalse (toneMappingOptions.UseBT1886ForCoreVideoGamma.HasValue, "ToneMappingOptions.UseBT1886ForCoreVideoGamma #1"); - Assert.IsFalse (toneMappingOptions.SkipBoostToHdr.HasValue, "ToneMappingOptions.SkipBoostToHdr #1"); - Assert.IsFalse (toneMappingOptions.ExrToneMappingGammaDefog.HasValue, "ToneMappingOptions.ExrToneMappingGammaDefog #1"); - Assert.IsFalse (toneMappingOptions.ExrToneMappingGammaExposure.HasValue, "ToneMappingOptions.ExrToneMappingGammaExposure #1"); - Assert.IsFalse (toneMappingOptions.ExrToneMappingGammaKneeLow.HasValue, "ToneMappingOptions.ExrToneMappingGammaKneeLow #1"); - Assert.IsFalse (toneMappingOptions.ExrToneMappingGammaKneeHigh.HasValue, "ToneMappingOptions.ExrToneMappingGammaKneeHigh #1"); + Assert.That (toneMappingOptions.Use100nitsHlgOotf.HasValue, Is.False, "ToneMappingOptions.Use100nitsHlgOotf #1"); + Assert.That (toneMappingOptions.UseBT1886ForCoreVideoGamma.HasValue, Is.False, "ToneMappingOptions.UseBT1886ForCoreVideoGamma #1"); + Assert.That (toneMappingOptions.SkipBoostToHdr.HasValue, Is.False, "ToneMappingOptions.SkipBoostToHdr #1"); + Assert.That (toneMappingOptions.ExrToneMappingGammaDefog.HasValue, Is.False, "ToneMappingOptions.ExrToneMappingGammaDefog #1"); + Assert.That (toneMappingOptions.ExrToneMappingGammaExposure.HasValue, Is.False, "ToneMappingOptions.ExrToneMappingGammaExposure #1"); + Assert.That (toneMappingOptions.ExrToneMappingGammaKneeLow.HasValue, Is.False, "ToneMappingOptions.ExrToneMappingGammaKneeLow #1"); + Assert.That (toneMappingOptions.ExrToneMappingGammaKneeHigh.HasValue, Is.False, "ToneMappingOptions.ExrToneMappingGammaKneeHigh #1"); using var mutableDict = new NSMutableDictionary (); t.Options = mutableDict; - Assert.AreSame (mutableDict, t.Options, "Options#2"); + Assert.That (t.Options, Is.SameAs (mutableDict), "Options#2"); toneMappingOptions = t.ToneMappingOptions!; - Assert.AreSame (mutableDict, toneMappingOptions.Dictionary, "ToneMappingOptions#2"); + Assert.That (toneMappingOptions.Dictionary, Is.SameAs (mutableDict), "ToneMappingOptions#2"); - Assert.IsFalse (toneMappingOptions.Use100nitsHlgOotf.HasValue, "ToneMappingOptions.Use100nitsHlgOotf #2"); - Assert.IsFalse (toneMappingOptions.UseBT1886ForCoreVideoGamma.HasValue, "ToneMappingOptions.UseBT1886ForCoreVideoGamma #2"); - Assert.IsFalse (toneMappingOptions.SkipBoostToHdr.HasValue, "ToneMappingOptions.SkipBoostToHdr #2"); - Assert.IsFalse (toneMappingOptions.ExrToneMappingGammaDefog.HasValue, "ToneMappingOptions.ExrToneMappingGammaDefog #2"); - Assert.IsFalse (toneMappingOptions.ExrToneMappingGammaExposure.HasValue, "ToneMappingOptions.ExrToneMappingGammaExposure #2"); - Assert.IsFalse (toneMappingOptions.ExrToneMappingGammaKneeLow.HasValue, "ToneMappingOptions.ExrToneMappingGammaKneeLow #2"); - Assert.IsFalse (toneMappingOptions.ExrToneMappingGammaKneeHigh.HasValue, "ToneMappingOptions.ExrToneMappingGammaKneeHigh #2"); + Assert.That (toneMappingOptions.Use100nitsHlgOotf.HasValue, Is.False, "ToneMappingOptions.Use100nitsHlgOotf #2"); + Assert.That (toneMappingOptions.UseBT1886ForCoreVideoGamma.HasValue, Is.False, "ToneMappingOptions.UseBT1886ForCoreVideoGamma #2"); + Assert.That (toneMappingOptions.SkipBoostToHdr.HasValue, Is.False, "ToneMappingOptions.SkipBoostToHdr #2"); + Assert.That (toneMappingOptions.ExrToneMappingGammaDefog.HasValue, Is.False, "ToneMappingOptions.ExrToneMappingGammaDefog #2"); + Assert.That (toneMappingOptions.ExrToneMappingGammaExposure.HasValue, Is.False, "ToneMappingOptions.ExrToneMappingGammaExposure #2"); + Assert.That (toneMappingOptions.ExrToneMappingGammaKneeLow.HasValue, Is.False, "ToneMappingOptions.ExrToneMappingGammaKneeLow #2"); + Assert.That (toneMappingOptions.ExrToneMappingGammaKneeHigh.HasValue, Is.False, "ToneMappingOptions.ExrToneMappingGammaKneeHigh #2"); toneMappingOptions.Use100nitsHlgOotf = false; toneMappingOptions.UseBT1886ForCoreVideoGamma = true; @@ -69,13 +69,13 @@ public void PropertySetGetTest () toneMappingOptions.ExrToneMappingGammaKneeLow = 0.0f; toneMappingOptions.ExrToneMappingGammaKneeHigh = null; - Assert.IsFalse (toneMappingOptions.Use100nitsHlgOotf.Value, "ToneMappingOptions.Use100nitsHlgOotf #3"); - Assert.IsTrue (toneMappingOptions.UseBT1886ForCoreVideoGamma.Value, "ToneMappingOptions.UseBT1886ForCoreVideoGamma #3"); - Assert.IsFalse (toneMappingOptions.SkipBoostToHdr.HasValue, "ToneMappingOptions.SkipBoostToHdr #3"); - Assert.AreEqual (1.0f, toneMappingOptions.ExrToneMappingGammaDefog.Value, "ToneMappingOptions.ExrToneMappingGammaDefog #3"); - Assert.AreEqual (-1.0f, toneMappingOptions.ExrToneMappingGammaExposure.Value, "ToneMappingOptions.ExrToneMappingGammaExposure #3"); - Assert.AreEqual (0.0f, toneMappingOptions.ExrToneMappingGammaKneeLow.Value, "ToneMappingOptions.ExrToneMappingGammaKneeLow #3"); - Assert.IsFalse (toneMappingOptions.ExrToneMappingGammaKneeHigh.HasValue, "ToneMappingOptions.ExrToneMappingGammaKneeHigh #3"); + Assert.That (toneMappingOptions.Use100nitsHlgOotf.Value, Is.False, "ToneMappingOptions.Use100nitsHlgOotf #3"); + Assert.That (toneMappingOptions.UseBT1886ForCoreVideoGamma.Value, Is.True, "ToneMappingOptions.UseBT1886ForCoreVideoGamma #3"); + Assert.That (toneMappingOptions.SkipBoostToHdr.HasValue, Is.False, "ToneMappingOptions.SkipBoostToHdr #3"); + Assert.That (toneMappingOptions.ExrToneMappingGammaDefog.Value, Is.EqualTo (1.0f), "ToneMappingOptions.ExrToneMappingGammaDefog #3"); + Assert.That (toneMappingOptions.ExrToneMappingGammaExposure.Value, Is.EqualTo (-1.0f), "ToneMappingOptions.ExrToneMappingGammaExposure #3"); + Assert.That (toneMappingOptions.ExrToneMappingGammaKneeLow.Value, Is.EqualTo (0.0f), "ToneMappingOptions.ExrToneMappingGammaKneeLow #3"); + Assert.That (toneMappingOptions.ExrToneMappingGammaKneeHigh.HasValue, Is.False, "ToneMappingOptions.ExrToneMappingGammaKneeHigh #3"); } } } diff --git a/tests/monotouch-test/CoreGraphics/CGEventTests.cs b/tests/monotouch-test/CoreGraphics/CGEventTests.cs index a1ba48dee301..796905b533b3 100644 --- a/tests/monotouch-test/CoreGraphics/CGEventTests.cs +++ b/tests/monotouch-test/CoreGraphics/CGEventTests.cs @@ -28,7 +28,7 @@ public void CreateTap () { tapCalled = false; using var tapPort = CGEvent.CreateTap (CGEventTapLocation.AnnotatedSession, CGEventTapPlacement.HeadInsert, CGEventTapOptions.Default, CGEventMask.KeyDown, callBack, IntPtr.Zero); - Assert.IsFalse (tapCalled, "tap was mistakenly called."); + Assert.That (tapCalled, Is.False, "tap was mistakenly called."); } [Test] @@ -37,7 +37,7 @@ public void CreateTapPSN () tapCalled = false; var psn = (IntPtr) 2; // kCurrentProcess using var tapPort = CGEvent.CreateTap (psn, CGEventTapPlacement.HeadInsert, CGEventTapOptions.Default, CGEventMask.KeyDown, callBack, IntPtr.Zero); - Assert.IsFalse (tapCalled, "tap was mistakenly called."); + Assert.That (tapCalled, Is.False, "tap was mistakenly called."); } #endif @@ -46,15 +46,15 @@ public void CreateTapPSN () public void Constructor_CGEventSourceStateID_0 () { var ex = Assert.Throws (() => new CGEvent (null, CGScrollEventUnit.Pixel), "ArgumentException"); - Assert.AreEqual ("At least one wheel must be provided", ex.Message, "Message"); + Assert.That (ex.Message, Is.EqualTo ("At least one wheel must be provided"), "Message"); } [Test] public void Constructor_CGEventSourceStateID_1 () { using var evt = new CGEvent (null, CGScrollEventUnit.Pixel, 0); - Assert.AreEqual (CGEventType.ScrollWheel, evt.EventType, "EventType"); - Assert.AreEqual (0, evt.Timestamp, "Timestamp"); + Assert.That (evt.EventType, Is.EqualTo (CGEventType.ScrollWheel), "EventType"); + Assert.That (evt.Timestamp, Is.EqualTo (0), "Timestamp"); // There doesn't seem to be any way to validate any creation // arguments, except using CGEvent.ToData which returns an opaque // byte array. Unfortunately the byte array changes randomly @@ -66,8 +66,8 @@ public void Constructor_CGEventSourceStateID_1 () public void Constructor_CGEventSourceStateID_2 () { using var evt = new CGEvent (null, CGScrollEventUnit.Pixel, 0, 3); - Assert.AreEqual (CGEventType.ScrollWheel, evt.EventType, "EventType"); - Assert.AreEqual (0, evt.Timestamp, "Timestamp"); + Assert.That (evt.EventType, Is.EqualTo (CGEventType.ScrollWheel), "EventType"); + Assert.That (evt.Timestamp, Is.EqualTo (0), "Timestamp"); // There doesn't seem to be any way to validate any creation // arguments, except using CGEvent.ToData which returns an opaque // byte array. Unfortunately the byte array changes randomly @@ -79,8 +79,8 @@ public void Constructor_CGEventSourceStateID_2 () public void Constructor_CGEventSourceStateID_3 () { using var evt = new CGEvent (null, CGScrollEventUnit.Pixel, 0, 3, 9); - Assert.AreEqual (CGEventType.ScrollWheel, evt.EventType, "EventType"); - Assert.AreEqual (0, evt.Timestamp, "Timestamp"); + Assert.That (evt.EventType, Is.EqualTo (CGEventType.ScrollWheel), "EventType"); + Assert.That (evt.Timestamp, Is.EqualTo (0), "Timestamp"); // There doesn't seem to be any way to validate any creation // arguments, except using CGEvent.ToData which returns an opaque // byte array. Unfortunately the byte array changes randomly @@ -92,7 +92,7 @@ public void Constructor_CGEventSourceStateID_3 () public void Constructor_CGEventSourceStateID_4 () { var ex = Assert.Throws (() => new CGEvent (null, CGScrollEventUnit.Pixel, 0, 3, 9, 42), "ArgumentException"); - Assert.AreEqual ("Only one to three wheels are supported on this constructor", ex.Message, "Message"); + Assert.That (ex.Message, Is.EqualTo ("Only one to three wheels are supported on this constructor"), "Message"); } public void PostToPid () @@ -107,7 +107,7 @@ public void PostToPid () public void PostToPSN () { var pid = Process.GetCurrentProcess ().Id; - Assert.AreEqual (0, GetProcessForPID (pid, out var psn), "GetProcessForPID"); + Assert.That (GetProcessForPID (pid, out var psn), Is.EqualTo (0), "GetProcessForPID"); using var evt = new CGEvent (null, (ushort) 1, true); unsafe { IntPtr* psnPtr = &psn; @@ -124,7 +124,7 @@ public void ToData () { using var evt = new CGEvent (null, CGScrollEventUnit.Pixel, 0); using var data = evt.ToData (); - Assert.NotNull (data, "data"); + Assert.That (data, Is.Not.Null, "data"); Assert.That (data.Length, Is.GreaterThan ((nuint) 0), "Length"); } #endif // __MACOS__ || __MACCATALYST__ diff --git a/tests/monotouch-test/CoreGraphics/CGImageMetadataTests.cs b/tests/monotouch-test/CoreGraphics/CGImageMetadataTests.cs index 6801d4d497c8..1c0ca4ba3929 100644 --- a/tests/monotouch-test/CoreGraphics/CGImageMetadataTests.cs +++ b/tests/monotouch-test/CoreGraphics/CGImageMetadataTests.cs @@ -34,8 +34,8 @@ public void EnumerateMetadata () tags.Add (tag); return true; }); - Assert.AreEqual (2, keys.Count, "key count mismatch"); - Assert.AreEqual (2, tags.Count, "tag count mistmatch"); + Assert.That (keys.Count, Is.EqualTo (2), "key count mismatch"); + Assert.That (tags.Count, Is.EqualTo (2), "tag count mistmatch"); } } } diff --git a/tests/monotouch-test/CoreGraphics/CGImageTest.cs b/tests/monotouch-test/CoreGraphics/CGImageTest.cs index d09372141921..6ff4a085bdd0 100644 --- a/tests/monotouch-test/CoreGraphics/CGImageTest.cs +++ b/tests/monotouch-test/CoreGraphics/CGImageTest.cs @@ -34,7 +34,7 @@ public void FromPNG () #else using (var ui = new UIImage (img, 1.0f, UIImageOrientation.Up)) { #endif - Assert.IsNotNull (ui.CGImage, "CGImage"); + Assert.That (ui.CGImage, Is.Not.Null, "CGImage"); if (TestRuntime.CheckXcodeVersion (7, 0)) Assert.That (img.UTType.ToString (), Is.EqualTo ("public.png"), "UTType"); } @@ -50,18 +50,18 @@ public void ContentHeadroom () using var provider = new CGDataProvider (new byte [(int) frame.Width * (int) frame.Height * 4]); using var colorSpace = CGColorSpace.CreateWithName (CGColorSpaceNames.Itur_2100_PQ); using var img = new CGImage (0.0f, (int) frame.Width, (int) frame.Height, 8, 32, 4 * (int) frame.Width, colorSpace, CGBitmapFlags.ByteOrderDefault | CGBitmapFlags.Last, provider, null, false, CGColorRenderingIntent.Default); - Assert.IsNotNull (img, "Image"); - Assert.AreEqual (4.92610836f, img.ContentHeadroom, "ContentHeadroom A"); - Assert.IsTrue (img.ShouldToneMap, "ShouldToneMap A"); - Assert.IsFalse (img.ContainsImageSpecificToneMappingMetadata, "ContainsImageSpecificToneMappingMetadata A"); + Assert.That (img, Is.Not.Null, "Image"); + Assert.That (img.ContentHeadroom, Is.EqualTo (4.92610836f), "ContentHeadroom A"); + Assert.That (img.ShouldToneMap, Is.True, "ShouldToneMap A"); + Assert.That (img.ContainsImageSpecificToneMappingMetadata, Is.False, "ContainsImageSpecificToneMappingMetadata A"); using var copy = img.Copy (3.0f); - Assert.IsNotNull (copy, "Copy"); - Assert.AreEqual (3.0f, copy.ContentHeadroom, "ContentHeadroom B"); - Assert.IsTrue (copy.ShouldToneMap, "ShouldToneMap B"); - Assert.IsFalse (copy.ContainsImageSpecificToneMappingMetadata, "ContainsImageSpecificToneMappingMetadata B"); + Assert.That (copy, Is.Not.Null, "Copy"); + Assert.That (copy.ContentHeadroom, Is.EqualTo (3.0f), "ContentHeadroom B"); + Assert.That (copy.ShouldToneMap, Is.True, "ShouldToneMap B"); + Assert.That (copy.ContainsImageSpecificToneMappingMetadata, Is.False, "ContainsImageSpecificToneMappingMetadata B"); - Assert.AreEqual (4.92610836f, CGImage.DefaultHdrImageContentHeadroom, "DefaultHdrImageContentHeadroom"); + Assert.That (CGImage.DefaultHdrImageContentHeadroom, Is.EqualTo (4.92610836f), "DefaultHdrImageContentHeadroom"); if (TestRuntime.CheckXcodeVersion (26, 0)) { Assert.That (copy.CalculatedContentHeadroom, Is.EqualTo (0.0f), "CalculatedContentHeadroom B"); diff --git a/tests/monotouch-test/CoreGraphics/CGPointDictionaryTests.cs b/tests/monotouch-test/CoreGraphics/CGPointDictionaryTests.cs index e669514f2c37..1f81dd8fc7b0 100644 --- a/tests/monotouch-test/CoreGraphics/CGPointDictionaryTests.cs +++ b/tests/monotouch-test/CoreGraphics/CGPointDictionaryTests.cs @@ -22,19 +22,19 @@ public void PropertiesTest () var point = new CGPoint ((nfloat) 1, (nfloat) 2); using var dict = point.ToDictionary (); var strongDict = new CGPointDictionary (dict); - Assert.AreEqual (point.X, strongDict.X, "X"); - Assert.AreEqual (point.Y, strongDict.Y, "Y"); + Assert.That (strongDict.X, Is.EqualTo (point.X), "X"); + Assert.That (strongDict.Y, Is.EqualTo (point.Y), "Y"); var point2 = strongDict.ToPoint (); - Assert.AreEqual (point, point2, "Point"); + Assert.That (point2, Is.EqualTo (point), "Point"); strongDict = new CGPointDictionary (); strongDict.X = 3; - Assert.AreEqual ((nfloat) 3, strongDict.X, "X 2"); + Assert.That (strongDict.X, Is.EqualTo ((nfloat) 3), "X 2"); strongDict.Y = 4; - Assert.AreEqual ((nfloat) 4, strongDict.Y, "Y 2"); + Assert.That (strongDict.Y, Is.EqualTo ((nfloat) 4), "Y 2"); point2 = strongDict.ToPoint (); - Assert.AreEqual (new CGPoint (3, 4), point2, "Point 2"); + Assert.That (point2, Is.EqualTo (new CGPoint (3, 4)), "Point 2"); }); } @@ -42,18 +42,18 @@ public void PropertiesTest () public void Default () { var strongDict = new CGPointDictionary (); - Assert.IsNull (strongDict.X, "X"); - Assert.IsNull (strongDict.Y, "Y"); + Assert.That (strongDict.X, Is.Null, "X"); + Assert.That (strongDict.Y, Is.Null, "Y"); var point = strongDict.ToPoint (); - Assert.AreEqual (default (CGPoint), point, "Point"); + Assert.That (point, Is.EqualTo (default (CGPoint)), "Point"); } [Test] public void ToStringTest1 () { var strongDict = new CGPointDictionary (); - Assert.AreEqual ("CoreGraphics.CGPointDictionary", strongDict.ToString (), "A"); - Assert.AreEqual ("{\n}", strongDict.Dictionary.ToString (), "B"); + Assert.That (strongDict.ToString (), Is.EqualTo ("CoreGraphics.CGPointDictionary"), "A"); + Assert.That (strongDict.Dictionary.ToString (), Is.EqualTo ("{\n}"), "B"); } [Test] @@ -62,7 +62,7 @@ public void ToStringTest2 () var strongDict = new CGPointDictionary (); strongDict.X = 3; strongDict.Y = 4; - Assert.AreEqual ("CoreGraphics.CGPointDictionary", strongDict.ToString (), "A"); - Assert.AreEqual ("{\n X = 3;\n Y = 4;\n}", strongDict.Dictionary.ToString (), "B"); + Assert.That (strongDict.ToString (), Is.EqualTo ("CoreGraphics.CGPointDictionary"), "A"); + Assert.That (strongDict.Dictionary.ToString (), Is.EqualTo ("{\n X = 3;\n Y = 4;\n}"), "B"); } } diff --git a/tests/monotouch-test/CoreGraphics/CGRectDictionaryTests.cs b/tests/monotouch-test/CoreGraphics/CGRectDictionaryTests.cs index 12ac9255d660..022e248213cb 100644 --- a/tests/monotouch-test/CoreGraphics/CGRectDictionaryTests.cs +++ b/tests/monotouch-test/CoreGraphics/CGRectDictionaryTests.cs @@ -22,25 +22,25 @@ public void PropertiesTest () var rect = new CGRect (1, 2, 3, 4); using var dict = rect.ToDictionary (); var strongDict = new CGRectDictionary (dict); - Assert.AreEqual (rect.X, strongDict.X, "X"); - Assert.AreEqual (rect.Y, strongDict.Y, "Y"); - Assert.AreEqual (rect.Height, strongDict.Height, "Height"); - Assert.AreEqual (rect.Width, strongDict.Width, "Width"); + Assert.That (strongDict.X, Is.EqualTo (rect.X), "X"); + Assert.That (strongDict.Y, Is.EqualTo (rect.Y), "Y"); + Assert.That (strongDict.Height, Is.EqualTo (rect.Height), "Height"); + Assert.That (strongDict.Width, Is.EqualTo (rect.Width), "Width"); var rect2 = strongDict.ToRect (); - Assert.AreEqual (rect, rect2, "Rect"); + Assert.That (rect2, Is.EqualTo (rect), "Rect"); strongDict = new CGRectDictionary (); strongDict.X = 3; - Assert.AreEqual ((nfloat) 3, strongDict.X, "X 2"); + Assert.That (strongDict.X, Is.EqualTo ((nfloat) 3), "X 2"); strongDict.Y = 4; - Assert.AreEqual ((nfloat) 4, strongDict.Y, "Y 2"); + Assert.That (strongDict.Y, Is.EqualTo ((nfloat) 4), "Y 2"); strongDict.Width = 5; - Assert.AreEqual ((nfloat) 5, strongDict.Width, "Width 2"); + Assert.That (strongDict.Width, Is.EqualTo ((nfloat) 5), "Width 2"); strongDict.Height = 6; - Assert.AreEqual ((nfloat) 6, strongDict.Height, "Height 2"); + Assert.That (strongDict.Height, Is.EqualTo ((nfloat) 6), "Height 2"); rect2 = strongDict.ToRect (); - Assert.AreEqual (new CGRect (3, 4, 5, 6), rect2, "Rect 2"); + Assert.That (rect2, Is.EqualTo (new CGRect (3, 4, 5, 6)), "Rect 2"); }); } @@ -49,12 +49,12 @@ public void Default () { Assert.Multiple (() => { var strongDict = new CGRectDictionary (); - Assert.IsNull (strongDict.X, "X"); - Assert.IsNull (strongDict.Y, "Y"); - Assert.IsNull (strongDict.Width, "Width"); - Assert.IsNull (strongDict.Height, "Height"); + Assert.That (strongDict.X, Is.Null, "X"); + Assert.That (strongDict.Y, Is.Null, "Y"); + Assert.That (strongDict.Width, Is.Null, "Width"); + Assert.That (strongDict.Height, Is.Null, "Height"); var rect = strongDict.ToRect (); - Assert.AreEqual (default (CGRect), rect, "Rect"); + Assert.That (rect, Is.EqualTo (default (CGRect)), "Rect"); }); } @@ -62,8 +62,8 @@ public void Default () public void ToStringTest1 () { var strongDict = new CGRectDictionary (); - Assert.AreEqual ("CoreGraphics.CGRectDictionary", strongDict.ToString (), "A"); - Assert.AreEqual ("{\n}", strongDict.Dictionary.ToString (), "B"); + Assert.That (strongDict.ToString (), Is.EqualTo ("CoreGraphics.CGRectDictionary"), "A"); + Assert.That (strongDict.Dictionary.ToString (), Is.EqualTo ("{\n}"), "B"); } [Test] @@ -74,7 +74,7 @@ public void ToStringTest2 () strongDict.Y = 4; strongDict.Width = 5; strongDict.Height = 6; - Assert.AreEqual ("CoreGraphics.CGRectDictionary", strongDict.ToString (), "A"); - Assert.AreEqual ("{\n Height = 6;\n Width = 5;\n X = 3;\n Y = 4;\n}", strongDict.Dictionary.ToString (), "B"); + Assert.That (strongDict.ToString (), Is.EqualTo ("CoreGraphics.CGRectDictionary"), "A"); + Assert.That (strongDict.Dictionary.ToString (), Is.EqualTo ("{\n Height = 6;\n Width = 5;\n X = 3;\n Y = 4;\n}"), "B"); } } diff --git a/tests/monotouch-test/CoreGraphics/CGSizeDictionaryTests.cs b/tests/monotouch-test/CoreGraphics/CGSizeDictionaryTests.cs index ebb69d0e46c7..65ea93bf2e43 100644 --- a/tests/monotouch-test/CoreGraphics/CGSizeDictionaryTests.cs +++ b/tests/monotouch-test/CoreGraphics/CGSizeDictionaryTests.cs @@ -22,19 +22,19 @@ public void PropertiesTest () var size = new CGSize ((nfloat) 1, (nfloat) 2); using var dict = size.ToDictionary (); var strongDict = new CGSizeDictionary (dict); - Assert.AreEqual (size.Width, strongDict.Width, "Width"); - Assert.AreEqual (size.Height, strongDict.Height, "Height"); + Assert.That (strongDict.Width, Is.EqualTo (size.Width), "Width"); + Assert.That (strongDict.Height, Is.EqualTo (size.Height), "Height"); var size2 = strongDict.ToSize (); - Assert.AreEqual (size, size2, "Size"); + Assert.That (size2, Is.EqualTo (size), "Size"); strongDict = new CGSizeDictionary (); strongDict.Width = 3; - Assert.AreEqual ((nfloat) 3, strongDict.Width, "Width 2"); + Assert.That (strongDict.Width, Is.EqualTo ((nfloat) 3), "Width 2"); strongDict.Height = 4; - Assert.AreEqual ((nfloat) 4, strongDict.Height, "Height 2"); + Assert.That (strongDict.Height, Is.EqualTo ((nfloat) 4), "Height 2"); size2 = strongDict.ToSize (); - Assert.AreEqual (new CGSize (3, 4), size2, "Size 2"); + Assert.That (size2, Is.EqualTo (new CGSize (3, 4)), "Size 2"); }); } @@ -43,10 +43,10 @@ public void Default () { Assert.Multiple (() => { var strongDict = new CGSizeDictionary (); - Assert.IsNull (strongDict.Width, "Width"); - Assert.IsNull (strongDict.Height, "Height"); + Assert.That (strongDict.Width, Is.Null, "Width"); + Assert.That (strongDict.Height, Is.Null, "Height"); var size = strongDict.ToSize (); - Assert.AreEqual (default (CGSize), size, "Size"); + Assert.That (size, Is.EqualTo (default (CGSize)), "Size"); }); } @@ -54,8 +54,8 @@ public void Default () public void ToStringTest1 () { var strongDict = new CGSizeDictionary (); - Assert.AreEqual ("CoreGraphics.CGSizeDictionary", strongDict.ToString (), "A"); - Assert.AreEqual ("{\n}", strongDict.Dictionary.ToString (), "B"); + Assert.That (strongDict.ToString (), Is.EqualTo ("CoreGraphics.CGSizeDictionary"), "A"); + Assert.That (strongDict.Dictionary.ToString (), Is.EqualTo ("{\n}"), "B"); } [Test] @@ -64,7 +64,7 @@ public void ToStringTest2 () var strongDict = new CGSizeDictionary (); strongDict.Width = 3; strongDict.Height = 4; - Assert.AreEqual ("CoreGraphics.CGSizeDictionary", strongDict.ToString (), "A"); - Assert.AreEqual ("{\n Height = 4;\n Width = 3;\n}", strongDict.Dictionary.ToString (), "B"); + Assert.That (strongDict.ToString (), Is.EqualTo ("CoreGraphics.CGSizeDictionary"), "A"); + Assert.That (strongDict.Dictionary.ToString (), Is.EqualTo ("{\n Height = 4;\n Width = 3;\n}"), "B"); } } diff --git a/tests/monotouch-test/CoreGraphics/ColorSpaceTest.cs b/tests/monotouch-test/CoreGraphics/ColorSpaceTest.cs index 95c7b3bb0852..4d92d1b1ba63 100644 --- a/tests/monotouch-test/CoreGraphics/ColorSpaceTest.cs +++ b/tests/monotouch-test/CoreGraphics/ColorSpaceTest.cs @@ -35,16 +35,16 @@ public void CreateDeviceGray () using (var cs = CGColorSpace.CreateDeviceGray ()) { Assert.That (cs.Components, Is.EqualTo ((nint) 1), "1"); Assert.That (cs.Model, Is.EqualTo (CGColorSpaceModel.Monochrome), "Monochrome"); - Assert.Null (cs.GetBaseColorSpace (), "GetBaseColorSpace"); + Assert.That (cs.GetBaseColorSpace (), Is.Null, "GetBaseColorSpace"); // not indexed so no color table Assert.That (cs.GetColorTable ().Length, Is.EqualTo (0), "GetColorTable"); - Assert.Null (cs.GetIccProfile (), "GetIccProfile"); + Assert.That (cs.GetIccProfile (), Is.Null, "GetIccProfile"); if (TestRuntime.CheckXcodeVersion (8, 0)) { // kCGColorSpaceDeviceGray is not a public constant, e.g. from CGColorSpaceNames.* Assert.That (cs.Name, Is.EqualTo ("kCGColorSpaceDeviceGray"), "Name"); - Assert.False (cs.IsWideGamutRgb, "IsWideGamutRgb"); - Assert.True (cs.SupportsOutput, "SupportsOutput"); - Assert.Null (cs.GetIccData (), "GetIccData"); + Assert.That (cs.IsWideGamutRgb, Is.False, "IsWideGamutRgb"); + Assert.That (cs.SupportsOutput, Is.True, "SupportsOutput"); + Assert.That (cs.GetIccData (), Is.Null, "GetIccData"); } } } @@ -55,16 +55,16 @@ public void CreateDeviceRGB () using (var cs = CGColorSpace.CreateDeviceRGB ()) { Assert.That (cs.Components, Is.EqualTo ((nint) 3), "3"); Assert.That (cs.Model, Is.EqualTo (CGColorSpaceModel.RGB), "RGB"); - Assert.Null (cs.GetBaseColorSpace (), "GetBaseColorSpace"); + Assert.That (cs.GetBaseColorSpace (), Is.Null, "GetBaseColorSpace"); // not indexed so no color table Assert.That (cs.GetColorTable ().Length, Is.EqualTo (0), "GetColorTable"); - Assert.Null (cs.GetIccProfile (), "GetIccProfile"); + Assert.That (cs.GetIccProfile (), Is.Null, "GetIccProfile"); if (TestRuntime.CheckXcodeVersion (8, 0)) { // kCGColorSpaceDeviceRGB is not a public constant Assert.That (cs.Name, Is.EqualTo ("kCGColorSpaceDeviceRGB"), "Name"); - Assert.False (cs.IsWideGamutRgb, "IsWideGamutRgb"); - Assert.True (cs.SupportsOutput, "SupportsOutput"); - Assert.Null (cs.GetIccData (), "GetIccData"); + Assert.That (cs.IsWideGamutRgb, Is.False, "IsWideGamutRgb"); + Assert.That (cs.SupportsOutput, Is.True, "SupportsOutput"); + Assert.That (cs.GetIccData (), Is.Null, "GetIccData"); } } } @@ -75,16 +75,16 @@ public void CreateDeviceCMYK () using (var cs = CGColorSpace.CreateDeviceCmyk ()) { Assert.That (cs.Components, Is.EqualTo ((nint) 4), "4"); Assert.That (cs.Model, Is.EqualTo (CGColorSpaceModel.CMYK), "CMYK"); - Assert.Null (cs.GetBaseColorSpace (), "GetBaseColorSpace"); + Assert.That (cs.GetBaseColorSpace (), Is.Null, "GetBaseColorSpace"); // not indexed so no color table Assert.That (cs.GetColorTable ().Length, Is.EqualTo (0), "GetColorTable"); - Assert.Null (cs.GetIccProfile (), "GetIccProfile"); + Assert.That (cs.GetIccProfile (), Is.Null, "GetIccProfile"); if (TestRuntime.CheckXcodeVersion (8, 0)) { // kCGColorSpaceDeviceCMYK is not a public constant Assert.That (cs.Name, Is.EqualTo ("kCGColorSpaceDeviceCMYK"), "Name"); - Assert.False (cs.IsWideGamutRgb, "IsWideGamutRgb"); - Assert.True (cs.SupportsOutput, "SupportsOutput"); - Assert.Null (cs.GetIccData (), "GetIccData"); + Assert.That (cs.IsWideGamutRgb, Is.False, "IsWideGamutRgb"); + Assert.That (cs.SupportsOutput, Is.True, "SupportsOutput"); + Assert.That (cs.GetIccData (), Is.Null, "GetIccData"); } } } @@ -107,16 +107,16 @@ public void CreateIndexed () Assert.That (base_cs.Model, Is.EqualTo (bcs.Model), "GetBaseColorSpace"); var new_table = cs.GetColorTable (); Assert.That (table, Is.EqualTo (new_table), "GetColorTable"); - Assert.Null (cs.GetIccProfile (), "GetIccProfile"); + Assert.That (cs.GetIccProfile (), Is.Null, "GetIccProfile"); if (TestRuntime.CheckXcodeVersion (8, 0)) { - Assert.Null (cs.Name, "Name"); - Assert.False (cs.IsWideGamutRgb, "IsWideGamutRgb"); - Assert.False (cs.SupportsOutput, "SupportsOutput"); - Assert.Null (cs.GetIccData (), "GetIccData"); + Assert.That (cs.Name, Is.Null, "Name"); + Assert.That (cs.IsWideGamutRgb, Is.False, "IsWideGamutRgb"); + Assert.That (cs.SupportsOutput, Is.False, "SupportsOutput"); + Assert.That (cs.GetIccData (), Is.Null, "GetIccData"); } if (TestRuntime.CheckXcodeVersion (12, 0)) - Assert.False (cs.UsesExtendedRange, "UsesExtendedRange"); + Assert.That (cs.UsesExtendedRange, Is.False, "UsesExtendedRange"); } } @@ -129,7 +129,7 @@ public void CreateExtendedSrgb () using (var cs = CGColorSpace.CreateWithName (CGColorSpaceNames.ExtendedSrgb)) { Assert.That (cs.Components, Is.EqualTo ((nint) 3), "3"); Assert.That (cs.Model, Is.EqualTo (CGColorSpaceModel.RGB), "RGB"); - Assert.Null (cs.GetBaseColorSpace (), "GetBaseColorSpace"); + Assert.That (cs.GetBaseColorSpace (), Is.Null, "GetBaseColorSpace"); // not indexed so no color table Assert.That (cs.GetColorTable ().Length, Is.EqualTo (0), "GetColorTable"); @@ -137,14 +137,14 @@ public void CreateExtendedSrgb () Assert.That (icc_profile.Length, Is.EqualTo ((nuint) 3144), "GetIccProfile"); Assert.That (cs.Name, Is.EqualTo (CGColorSpaceNames.ExtendedSrgb.ToString ()), "Name"); - Assert.True (cs.IsWideGamutRgb, "IsWideGamutRgb"); - Assert.True (cs.SupportsOutput, "SupportsOutput"); + Assert.That (cs.IsWideGamutRgb, Is.True, "IsWideGamutRgb"); + Assert.That (cs.SupportsOutput, Is.True, "SupportsOutput"); using (var icc_data = cs.GetIccData ()) Assert.That (icc_data.Length, Is.EqualTo ((nuint) 3144), "GetIccData"); if (TestRuntime.CheckXcodeVersion (12, 0)) - Assert.True (cs.UsesExtendedRange, "UsesExtendedRange"); + Assert.That (cs.UsesExtendedRange, Is.True, "UsesExtendedRange"); } } @@ -159,13 +159,13 @@ public void Disposed () Assert.That (cs.Components, Is.EqualTo ((nint) 0), "0"); Assert.That (cs.Model, Is.EqualTo (CGColorSpaceModel.Unknown), "Unknown"); - Assert.Null (cs.GetBaseColorSpace (), "GetBaseColorSpace"); + Assert.That (cs.GetBaseColorSpace (), Is.Null, "GetBaseColorSpace"); Assert.That (cs.GetColorTable ().Length, Is.EqualTo (0), "GetColorTable"); - Assert.Null (cs.GetIccProfile (), "GetIccProfile"); - Assert.Null (cs.Name, "Name"); - Assert.False (cs.IsWideGamutRgb, "IsWideGamutRgb"); - Assert.False (cs.SupportsOutput, "SupportsOutput"); - Assert.Null (cs.GetIccData (), "GetIccData"); + Assert.That (cs.GetIccProfile (), Is.Null, "GetIccProfile"); + Assert.That (cs.Name, Is.Null, "Name"); + Assert.That (cs.IsWideGamutRgb, Is.False, "IsWideGamutRgb"); + Assert.That (cs.SupportsOutput, Is.False, "SupportsOutput"); + Assert.That (cs.GetIccData (), Is.Null, "GetIccData"); // IOW all safe to call with a `nil` handle } @@ -182,7 +182,7 @@ public void CreateICCProfile () } using (var space = CGColorSpace.CreateIccProfile ((NSData) null)) { - Assert.IsNull (space, "null data"); + Assert.That (space, Is.Null, "null data"); } } @@ -190,7 +190,7 @@ void TestICC (CGColorSpace cs) { Assert.That (cs.Components, Is.EqualTo ((nint) 3), "Components"); Assert.That (cs.Model, Is.EqualTo (CGColorSpaceModel.RGB), "Model"); - Assert.Null (cs.GetBaseColorSpace (), "GetBaseColorSpace"); + Assert.That (cs.GetBaseColorSpace (), Is.Null, "GetBaseColorSpace"); // not indexed so no color table Assert.That (cs.GetColorTable ().Length, Is.EqualTo (0), "GetColorTable"); @@ -198,9 +198,9 @@ void TestICC (CGColorSpace cs) Assert.That (icc_profile.Length, Is.EqualTo ((nuint) 3284), "GetIccProfile"); if (TestRuntime.CheckXcodeVersion (8, 0)) { - Assert.Null (cs.Name, "Name"); - Assert.False (cs.IsWideGamutRgb, "IsWideGamutRgb"); - Assert.True (cs.SupportsOutput, "SupportsOutput"); + Assert.That (cs.Name, Is.Null, "Name"); + Assert.That (cs.IsWideGamutRgb, Is.False, "IsWideGamutRgb"); + Assert.That (cs.SupportsOutput, Is.True, "SupportsOutput"); using (var icc_data = cs.GetIccData ()) Assert.That (icc_data.Length, Is.EqualTo ((nuint) 3284), "GetIccData"); } @@ -233,7 +233,7 @@ public void CreateIccData () public void CreateIccData_Null_NSData () { using (var space = CGColorSpace.CreateIccData ((NSData) null)) { - Assert.IsNull (space, "null data"); + Assert.That (space, Is.Null, "null data"); } } @@ -241,7 +241,7 @@ public void CreateIccData_Null_NSData () public void CreateIccData_Null_CGDataProvider () { using (var space = CGColorSpace.CreateIccData ((CGDataProvider) null)) { - Assert.IsNull (space, "null data provider"); + Assert.That (space, Is.Null, "null data provider"); } } @@ -296,11 +296,11 @@ public void CalibratedGray () Assert.Throws (() => CGColorSpace.CreateCalibratedGray (whitepoint, new nfloat [4], gamma), "invalid blackpoint4"); using (var space = CGColorSpace.CreateCalibratedGray (whitepoint, blackpoint, gamma)) { - Assert.IsNotNull (space, "all non-null"); + Assert.That (space, Is.Not.Null, "all non-null"); } using (var space = CGColorSpace.CreateCalibratedGray (whitepoint, null, gamma)) { - Assert.IsNotNull (space, "null blackpoint"); + Assert.That (space, Is.Not.Null, "null blackpoint"); } } @@ -325,23 +325,23 @@ public void CalibratedRGB () Assert.Throws (() => CGColorSpace.CreateCalibratedRGB (whitepoint, blackpoint, gamma, new nfloat [4]), "invalid matrix4"); using (var space = CGColorSpace.CreateCalibratedRGB (whitepoint, blackpoint, gamma, matrix)) { - Assert.IsNotNull (space, "all non-null"); + Assert.That (space, Is.Not.Null, "all non-null"); } using (var space = CGColorSpace.CreateCalibratedRGB (whitepoint, null, gamma, matrix)) { - Assert.IsNotNull (space, "null blackpoint"); + Assert.That (space, Is.Not.Null, "null blackpoint"); } using (var space = CGColorSpace.CreateCalibratedRGB (whitepoint, blackpoint, null, matrix)) { - Assert.IsNotNull (space, "null gamma"); + Assert.That (space, Is.Not.Null, "null gamma"); } using (var space = CGColorSpace.CreateCalibratedRGB (whitepoint, blackpoint, gamma, null)) { - Assert.IsNotNull (space, "all matrix-null"); + Assert.That (space, Is.Not.Null, "all matrix-null"); } using (var space = CGColorSpace.CreateCalibratedRGB (whitepoint, null, null, null)) { - Assert.IsNotNull (space, "all null"); + Assert.That (space, Is.Not.Null, "all null"); } } @@ -362,19 +362,19 @@ public void Lab () Assert.Throws (() => CGColorSpace.CreateLab (whitepoint, blackpoint, new nfloat [3]), "invalid range3"); using (var space = CGColorSpace.CreateLab (whitepoint, blackpoint, range)) { - Assert.IsNotNull (space, "all non-null"); + Assert.That (space, Is.Not.Null, "all non-null"); } using (var space = CGColorSpace.CreateLab (whitepoint, null, range)) { - Assert.IsNotNull (space, "null blackpoint"); + Assert.That (space, Is.Not.Null, "null blackpoint"); } using (var space = CGColorSpace.CreateLab (whitepoint, blackpoint, null)) { - Assert.IsNotNull (space, "null gamma"); + Assert.That (space, Is.Not.Null, "null gamma"); } using (var space = CGColorSpace.CreateLab (whitepoint, null, null)) { - Assert.IsNotNull (space, "all null"); + Assert.That (space, Is.Not.Null, "all null"); } } @@ -383,9 +383,9 @@ public void IsHdr () { TestRuntime.AssertXcodeVersion (11, 0); using (var cs = CGColorSpace.CreateWithName (CGColorSpaceNames.GenericRgb)) - Assert.False (cs.IsHdr, "GenericRgb"); + Assert.That (cs.IsHdr, Is.False, "GenericRgb"); using (var cs = CGColorSpace.CreateWithName (CGColorSpaceNames.DisplayP3_Hlg)) - Assert.True (cs.IsHdr, "DisplayP3_Hlg"); + Assert.That (cs.IsHdr, Is.True, "DisplayP3_Hlg"); } [Test] @@ -393,9 +393,9 @@ public void CGColorSpaceUsesITUR_2100TFTest () { TestRuntime.AssertXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch); using (var cs = CGColorSpace.CreateWithName (CGColorSpaceNames.DisplayP3_Hlg)) - Assert.True (cs.UsesItur2100TF, "DisplayP3_Hlg"); + Assert.That (cs.UsesItur2100TF, Is.True, "DisplayP3_Hlg"); using (var cs = CGColorSpace.CreateWithName (CGColorSpaceNames.GenericRgb)) - Assert.False (cs.UsesItur2100TF, "GenericRgb"); + Assert.That (cs.UsesItur2100TF, Is.False, "GenericRgb"); } [Test] @@ -404,7 +404,7 @@ public void CreateLinearizedTest () TestRuntime.AssertXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch); using (var cs = CGColorSpace.CreateWithName (CGColorSpaceNames.GenericRgb)) { var csl = cs.CreateLinearized (); - Assert.NotNull (csl, "not null"); + Assert.That (csl, Is.Not.Null, "not null"); Assert.That ((nint) TestRuntime.CFGetRetainCount (csl.Handle), Is.EqualTo ((nint) 1).Or.EqualTo ((nint) 2)); } } @@ -415,7 +415,7 @@ public void CreateExtendedTest () TestRuntime.AssertXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch); using (var cs = CGColorSpace.CreateWithName (CGColorSpaceNames.GenericRgb)) { var csl = cs.CreateExtended (); - Assert.NotNull (csl, "not null"); + Assert.That (csl, Is.Not.Null, "not null"); Assert.That ((nint) TestRuntime.CFGetRetainCount (csl.Handle), Is.EqualTo ((nint) 1).Or.EqualTo ((nint) 2)); } } @@ -426,7 +426,7 @@ public void CreateExtendedLinearizedTest () TestRuntime.AssertXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch); using (var cs = CGColorSpace.CreateWithName (CGColorSpaceNames.GenericRgb)) { var csl = cs.CreateExtendedLinearized (); - Assert.NotNull (csl, "not null"); + Assert.That (csl, Is.Not.Null, "not null"); Assert.That ((nint) TestRuntime.CFGetRetainCount (csl.Handle), Is.EqualTo ((nint) 1).Or.EqualTo ((nint) 2)); } } @@ -436,7 +436,7 @@ public void CreateCopyWithStandardRange () { TestRuntime.AssertXcodeVersion (14, 0); using var cs = CGColorSpace.CreateWithName (CGColorSpaceNames.GenericRgb); - Assert.NotNull (cs.CreateCopyWithStandardRange ()); + Assert.That (cs.CreateCopyWithStandardRange (), Is.Not.Null); } [Test] @@ -467,7 +467,7 @@ public void CopyBaseColorSpace () TestRuntime.AssertXcodeVersion (16, 0); using (var cs = CGColorSpace.CreateDeviceRGB ()) { using var cbcs = cs.CopyBaseColorSpace (); - Assert.IsNull (cbcs, "CopyBaseColorSpace"); + Assert.That (cbcs, Is.Null, "CopyBaseColorSpace"); } } } diff --git a/tests/monotouch-test/CoreGraphics/ColorTest.cs b/tests/monotouch-test/CoreGraphics/ColorTest.cs index 106b110f30a4..86387c6aed4f 100644 --- a/tests/monotouch-test/CoreGraphics/ColorTest.cs +++ b/tests/monotouch-test/CoreGraphics/ColorTest.cs @@ -56,7 +56,7 @@ public void ColorSpace () { using (var c = new CGColor (0.5f, 0.5f, 0.5f, 0.5f)) { using (var spc = c.ColorSpace) - Assert.IsNotNull (spc, "ColorSpace"); + Assert.That (spc, Is.Not.Null, "ColorSpace"); } } @@ -98,7 +98,7 @@ public void GetAXName () { TestRuntime.AssertXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch); using (var c = new CGColor (CGConstantColor.Black)) { - Assert.IsNotNull (c.AXName, "AXName"); + Assert.That (c.AXName, Is.Not.Null, "AXName"); } } @@ -107,14 +107,14 @@ public void CreateByMatchingToColorSpace () { TestRuntime.AssertXcodeVersion (11, 0); using (var c = CGColor.CreateByMatchingToColorSpace (null, CGColorRenderingIntent.Default, null, null)) { - Assert.IsNull (c, "0"); + Assert.That (c, Is.Null, "0"); } using (var cs = CGColorSpace.CreateGenericRgbLinear ()) using (var c1 = CGColor.CreateSrgb (1, 2, 3, 4)) using (var c2 = CGColor.CreateByMatchingToColorSpace (cs, CGColorRenderingIntent.Default, c1, null)) { - Assert.IsNotNull (c1, "1"); - Assert.IsNotNull (c2, "2"); + Assert.That (c1, Is.Not.Null, "1"); + Assert.That (c2, Is.Not.Null, "2"); } } @@ -124,12 +124,12 @@ public void ContentHeadroom () TestRuntime.AssertXcodeVersion (26, 0); using (var color = CGColor.CreateWithContentHeadroom (0.5f, null, 0.3f, 0.4f, 0.5f, 0.6f)) { - Assert.IsNull (color, "color #1"); + Assert.That (color, Is.Null, "color #1"); } using var headroomCapableColorspace = CGColorSpace.CreateWithName (CGColorSpaceNames.ExtendedSrgb); using (var color = CGColor.CreateWithContentHeadroom (0.0f, headroomCapableColorspace, 0.3f, 0.4f, 0.5f, 0.6f)) { - Assert.IsNotNull (color, "color #2"); + Assert.That (color, Is.Not.Null, "color #2"); Assert.That (color.ContentHeadroom, Is.EqualTo (0.0f), "ContentHeadroom #2"); Assert.That (color.NumberOfComponents, Is.EqualTo ((nint) 4), "NumberOfComponents #2"); Assert.That (color.Components, Is.EqualTo (new nfloat [] { 0.3f, 0.4f, 0.5f, 0.6f }), "Components #2"); diff --git a/tests/monotouch-test/CoreGraphics/ContextTest.cs b/tests/monotouch-test/CoreGraphics/ContextTest.cs index 1994a8ae2ef4..2a875a102881 100644 --- a/tests/monotouch-test/CoreGraphics/ContextTest.cs +++ b/tests/monotouch-test/CoreGraphics/ContextTest.cs @@ -61,17 +61,17 @@ public void EdrHeadroom () using var context = Create (); if (TestRuntime.CheckXcodeVersion (26, 0)) { - Assert.AreEqual (1.0f, context.GetEdrTargetHeadroom (), "a"); - Assert.IsFalse (context.SetEdrTargetHeadroom (2.0f), "b"); - Assert.AreEqual (1.0f, context.GetEdrTargetHeadroom (), "c"); - Assert.IsFalse (context.SetEdrTargetHeadroom (-2.0f), "d"); - Assert.AreEqual (1.0f, context.GetEdrTargetHeadroom (), "e"); + Assert.That (context.GetEdrTargetHeadroom (), Is.EqualTo (1.0f), "a"); + Assert.That (context.SetEdrTargetHeadroom (2.0f), Is.False, "b"); + Assert.That (context.GetEdrTargetHeadroom (), Is.EqualTo (1.0f), "c"); + Assert.That (context.SetEdrTargetHeadroom (-2.0f), Is.False, "d"); + Assert.That (context.GetEdrTargetHeadroom (), Is.EqualTo (1.0f), "e"); } else { - Assert.AreEqual (0.0f, context.GetEdrTargetHeadroom (), "a"); - Assert.IsTrue (context.SetEdrTargetHeadroom (2.0f), "b"); - Assert.AreEqual (2.0f, context.GetEdrTargetHeadroom (), "c"); - Assert.IsFalse (context.SetEdrTargetHeadroom (-2.0f), "d"); - Assert.AreEqual (2.0f, context.GetEdrTargetHeadroom (), "e"); + Assert.That (context.GetEdrTargetHeadroom (), Is.EqualTo (0.0f), "a"); + Assert.That (context.SetEdrTargetHeadroom (2.0f), Is.True, "b"); + Assert.That (context.GetEdrTargetHeadroom (), Is.EqualTo (2.0f), "c"); + Assert.That (context.SetEdrTargetHeadroom (-2.0f), Is.False, "d"); + Assert.That (context.GetEdrTargetHeadroom (), Is.EqualTo (2.0f), "e"); } } @@ -86,15 +86,15 @@ public void DrawImageApplyingToneMapping () var mapping = new CGToneMappingOptions () { Use100nitsHlgOotf = true, ExrToneMappingGammaExposure = 3.14f }; using (var context = Create ()) { - Assert.IsFalse (context.DrawImageApplyingToneMapping (new CGRect (0, 0, 10, 10), img, CGToneMapping.IturRecommended, (NSDictionary?) null), "DrawImageApplyingToneMapping A"); + Assert.That (context.DrawImageApplyingToneMapping (new CGRect (0, 0, 10, 10), img, CGToneMapping.IturRecommended, (NSDictionary?) null), Is.False, "DrawImageApplyingToneMapping A"); } using (var context = Create ()) { - Assert.IsFalse (context.DrawImageApplyingToneMapping (new CGRect (0, 0, 10, 10), img, CGToneMapping.IturRecommended, mapping), "DrawImageApplyingToneMapping B"); + Assert.That (context.DrawImageApplyingToneMapping (new CGRect (0, 0, 10, 10), img, CGToneMapping.IturRecommended, mapping), Is.False, "DrawImageApplyingToneMapping B"); } using (var context = Create ()) { - Assert.IsFalse (context.DrawImageApplyingToneMapping (new CGRect (0, 0, 10, 10), img, CGToneMapping.IturRecommended, mapping.Dictionary), "DrawImageApplyingToneMapping C"); + Assert.That (context.DrawImageApplyingToneMapping (new CGRect (0, 0, 10, 10), img, CGToneMapping.IturRecommended, mapping.Dictionary), Is.False, "DrawImageApplyingToneMapping C"); } } diff --git a/tests/monotouch-test/CoreGraphics/DataProviderTest.cs b/tests/monotouch-test/CoreGraphics/DataProviderTest.cs index 28bab218c9bc..fb8caa82e019 100644 --- a/tests/monotouch-test/CoreGraphics/DataProviderTest.cs +++ b/tests/monotouch-test/CoreGraphics/DataProviderTest.cs @@ -57,13 +57,13 @@ public void Create_ReleaseCallback () { IntPtr memory = Marshal.AllocHGlobal (20); using (var provider = new CGDataProvider (memory, 20, ((IntPtr mem) => { - Assert.AreEqual (memory, mem, "mem"); + Assert.That (mem, Is.EqualTo (memory), "mem"); Marshal.FreeHGlobal (mem); memory = IntPtr.Zero; }))) { } - Assert.AreEqual (IntPtr.Zero, memory, "mem freed"); + Assert.That (memory, Is.EqualTo (IntPtr.Zero), "mem freed"); } [Test] diff --git a/tests/monotouch-test/CoreGraphics/FontTest.cs b/tests/monotouch-test/CoreGraphics/FontTest.cs index 8073f7035bb8..ebdbaa2f1f4f 100644 --- a/tests/monotouch-test/CoreGraphics/FontTest.cs +++ b/tests/monotouch-test/CoreGraphics/FontTest.cs @@ -36,13 +36,13 @@ public void Nullable () [Test] public void CreateFromProvider () { - Assert.Null (CGFont.CreateFromProvider (null), "CreateFromProvider"); + Assert.That (CGFont.CreateFromProvider (null), Is.Null, "CreateFromProvider"); } [Test] public void CreateWithFontName () { - Assert.Null (CGFont.CreateWithFontName (null), "CreateWithFontName"); + Assert.That (CGFont.CreateWithFontName (null), Is.Null, "CreateWithFontName"); } [Test] diff --git a/tests/monotouch-test/CoreGraphics/FunctionTest.cs b/tests/monotouch-test/CoreGraphics/FunctionTest.cs index 5985a35a8539..21cad3fc4137 100644 --- a/tests/monotouch-test/CoreGraphics/FunctionTest.cs +++ b/tests/monotouch-test/CoreGraphics/FunctionTest.cs @@ -100,13 +100,13 @@ public void CoreGraphicsStrongDictionary () }; var retrievedRect = graphicsDict.Rect; - Assert.IsTrue (rect == retrievedRect, "CoreGraphicsStrongDictionary CGRect"); + Assert.That (rect == retrievedRect, Is.True, "CoreGraphicsStrongDictionary CGRect"); var retrievedSize = graphicsDict.Size; - Assert.IsTrue (size == retrievedSize, "CoreGraphicsStrongDictionary CGSize"); + Assert.That (size == retrievedSize, Is.True, "CoreGraphicsStrongDictionary CGSize"); var retrievedPoint = graphicsDict.Point; - Assert.IsTrue (point == retrievedPoint, "CoreGraphicsStrongDictionary CGPoint"); + Assert.That (point == retrievedPoint, Is.True, "CoreGraphicsStrongDictionary CGPoint"); } class GraphicsDict : DictionaryContainer { diff --git a/tests/monotouch-test/CoreGraphics/GeometryTest.cs b/tests/monotouch-test/CoreGraphics/GeometryTest.cs index f60ced6f596c..400bd1b08394 100644 --- a/tests/monotouch-test/CoreGraphics/GeometryTest.cs +++ b/tests/monotouch-test/CoreGraphics/GeometryTest.cs @@ -17,9 +17,8 @@ public class GeometryTest { static public readonly IntPtr Handle = Dlfcn.dlopen (Constants.CoreGraphicsLibrary, 0); - public static CGRect GetRect (string symbol) + public static CGRect GetRect (IntPtr indirect) { - var indirect = Dlfcn.dlsym (Handle, symbol); if (indirect == IntPtr.Zero) return CGRect.Empty; unsafe { @@ -31,28 +30,28 @@ public static CGRect GetRect (string symbol) [Test] public void Infinite () { - var r = GetRect ("CGRectInfinite"); - Assert.False (r.IsEmpty, "IsEmpty"); - Assert.False (r.IsNull (), "IsNull"); - Assert.True (r.IsInfinite (), "IsInfinite"); + var r = GetRect (Dlfcn.dlsym (Handle, "CGRectInfinite")); + Assert.That (r.IsEmpty, Is.False, "IsEmpty"); + Assert.That (r.IsNull (), Is.False, "IsNull"); + Assert.That (r.IsInfinite (), Is.True, "IsInfinite"); } [Test] public void Null () { - var r = GetRect ("CGRectNull"); - Assert.True (r.IsEmpty, "IsEmpty"); - Assert.True (r.IsNull (), "IsNull"); - Assert.False (r.IsInfinite (), "IsInfinite"); + var r = GetRect (Dlfcn.dlsym (Handle, "CGRectNull")); + Assert.That (r.IsEmpty, Is.True, "IsEmpty"); + Assert.That (r.IsNull (), Is.True, "IsNull"); + Assert.That (r.IsInfinite (), Is.False, "IsInfinite"); } [Test] public void Zero () { - var r = GetRect ("CGRectZero"); - Assert.True (r.IsEmpty, "IsEmpty"); - Assert.False (r.IsNull (), "IsNull"); - Assert.False (r.IsInfinite (), "IsInfinite"); + var r = GetRect (Dlfcn.dlsym (Handle, "CGRectZero")); + Assert.That (r.IsEmpty, Is.True, "IsEmpty"); + Assert.That (r.IsNull (), Is.False, "IsNull"); + Assert.That (r.IsInfinite (), Is.False, "IsInfinite"); } } } diff --git a/tests/monotouch-test/CoreGraphics/GradientTest.cs b/tests/monotouch-test/CoreGraphics/GradientTest.cs index ac6abb42f5cb..a563c5d2288a 100644 --- a/tests/monotouch-test/CoreGraphics/GradientTest.cs +++ b/tests/monotouch-test/CoreGraphics/GradientTest.cs @@ -105,14 +105,14 @@ public void CreateWithHeadroom () }; using var hdrCapableColorspace = CGColorSpace.CreateWithName (CGColorSpaceNames.DisplayP3_PQ); - Assert.IsTrue (hdrCapableColorspace.IsHdr, "IsHdr"); + Assert.That (hdrCapableColorspace.IsHdr, Is.True, "IsHdr"); using (var gradient = CGGradient.Create (0.5f, hdrCapableColorspace, colorComponents, locations)) { - Assert.IsNotNull (gradient, "Gradient #1"); + Assert.That (gradient, Is.Not.Null, "Gradient #1"); Assert.That (gradient.ContentHeadroom, Is.EqualTo (1.0f), "Gradient #1 - ContentHeadroom"); } using (var gradient = CGGradient.Create (0.5f, null, colorComponents, locations)) { - Assert.IsNull (gradient, "Gradient #2"); + Assert.That (gradient, Is.Null, "Gradient #2"); } } } diff --git a/tests/monotouch-test/CoreGraphics/PDFContentStreamTest.cs b/tests/monotouch-test/CoreGraphics/PDFContentStreamTest.cs index 4d51c1944ceb..8390a32c5a19 100644 --- a/tests/monotouch-test/CoreGraphics/PDFContentStreamTest.cs +++ b/tests/monotouch-test/CoreGraphics/PDFContentStreamTest.cs @@ -27,7 +27,7 @@ public void FromPage () Assert.That (streams.Length, Is.EqualTo (1), "GetStreams.Length"); Assert.That (streams [0].Handle, Is.Not.EqualTo (cs.Handle), "GetStreams"); - Assert.Null (cs.GetResource ("XObject", ""), "GetResource"); + Assert.That (cs.GetResource ("XObject", ""), Is.Null, "GetResource"); } } } diff --git a/tests/monotouch-test/CoreGraphics/PDFDocumentTest.cs b/tests/monotouch-test/CoreGraphics/PDFDocumentTest.cs index c0aab11187fb..fbeccad011cd 100644 --- a/tests/monotouch-test/CoreGraphics/PDFDocumentTest.cs +++ b/tests/monotouch-test/CoreGraphics/PDFDocumentTest.cs @@ -44,10 +44,10 @@ public void FromUrl () void CheckTamarin (CGPDFDocument pdf) { - Assert.True (pdf.AllowsCopying, "AllowsCopying"); - Assert.True (pdf.AllowsPrinting, "AllowsPrinting"); - Assert.False (pdf.IsEncrypted, "IsEncrypted"); - Assert.True (pdf.IsUnlocked, "IsUnlocked"); + Assert.That (pdf.AllowsCopying, Is.True, "AllowsCopying"); + Assert.That (pdf.AllowsPrinting, Is.True, "AllowsPrinting"); + Assert.That (pdf.IsEncrypted, Is.False, "IsEncrypted"); + Assert.That (pdf.IsUnlocked, Is.True, "IsUnlocked"); Assert.That (pdf.Pages, Is.EqualTo ((nint) 3), "Pages"); Assert.That (pdf.GetInfo ().Count, Is.EqualTo (7), "GetInfo"); diff --git a/tests/monotouch-test/CoreGraphics/PDFInfoTest.cs b/tests/monotouch-test/CoreGraphics/PDFInfoTest.cs index 9d0f3b704957..0541e3131a6c 100644 --- a/tests/monotouch-test/CoreGraphics/PDFInfoTest.cs +++ b/tests/monotouch-test/CoreGraphics/PDFInfoTest.cs @@ -62,11 +62,11 @@ public void ToDictionaryWithPermissions () using (var url = new NSUrl (filename)) { using (var ctx = new CGContextPDF (url, new CGRect (0, 0, 1000, 1000), info)) { - Assert.IsNotNull (ctx, "1"); + Assert.That (ctx, Is.Not.Null, "1"); } using (var consumer = new CGDataConsumer (url)) { using (var ctx = new CGContextPDF (consumer, new CGRect (0, 0, 1000, 1000), info)) { - Assert.IsNotNull (ctx, "2"); + Assert.That (ctx, Is.Not.Null, "2"); } } } diff --git a/tests/monotouch-test/CoreGraphics/PDFScannerTest.cs b/tests/monotouch-test/CoreGraphics/PDFScannerTest.cs index def94c38556b..fde7a324c497 100644 --- a/tests/monotouch-test/CoreGraphics/PDFScannerTest.cs +++ b/tests/monotouch-test/CoreGraphics/PDFScannerTest.cs @@ -111,7 +111,7 @@ public void Tamarin () bt_count = 0; do_checks = 7; - Assert.True (scanner.Scan (), "Scan"); + Assert.That (scanner.Scan (), Is.True, "Scan"); Assert.That (bt_count, Is.EqualTo (45), "new paragraph"); Assert.That (do_checks, Is.EqualTo (0), "found the image"); if (TestRuntime.CheckXcodeVersion (14, 0)) { diff --git a/tests/monotouch-test/CoreGraphics/PathTest.cs b/tests/monotouch-test/CoreGraphics/PathTest.cs index 6149a1d4dd18..2bb7be881fab 100644 --- a/tests/monotouch-test/CoreGraphics/PathTest.cs +++ b/tests/monotouch-test/CoreGraphics/PathTest.cs @@ -24,7 +24,7 @@ public void EllipseFromRect () var rect = new CGRect (0, 0, 15, 15); var matrix = CGAffineTransform.MakeIdentity (); using (CGPath p = CGPath.EllipseFromRect (rect, matrix)) { - Assert.IsNotNull (p, "non-null"); + Assert.That (p, Is.Not.Null, "non-null"); } } @@ -56,10 +56,10 @@ public void MoveToPoint () var matrix = CGAffineTransform.MakeIdentity (); using (CGPath p1 = new CGPath ()) using (CGPath p2 = new CGPath ()) { - Assert.IsTrue (p1.IsEmpty, "IsEmpty-1"); + Assert.That (p1.IsEmpty, Is.True, "IsEmpty-1"); p1.MoveToPoint (0, 0); p2.MoveToPoint (matrix, 0, 0); - Assert.IsFalse (p1.IsEmpty, "IsEmpty-2"); + Assert.That (p1.IsEmpty, Is.False, "IsEmpty-2"); Assert.That (p1, Is.EqualTo (p2), "CGPathEqualToPath"); } } @@ -70,12 +70,12 @@ public void AddLineToPoint () var matrix = CGAffineTransform.MakeIdentity (); using (CGPath p1 = new CGPath ()) using (CGPath p2 = new CGPath ()) { - Assert.IsTrue (p1.IsEmpty, "IsEmpty-1"); + Assert.That (p1.IsEmpty, Is.True, "IsEmpty-1"); p1.MoveToPoint (0, 0); p1.AddLineToPoint (1, 1); p2.MoveToPoint (matrix, 0, 0); p2.AddLineToPoint (matrix, 1, 1); - Assert.IsFalse (p1.IsEmpty, "IsEmpty-2"); + Assert.That (p1.IsEmpty, Is.False, "IsEmpty-2"); Assert.That (p1, Is.EqualTo (p2), "CGPathEqualToPath"); } } @@ -86,12 +86,12 @@ public void AddCurveToPoint () var matrix = CGAffineTransform.MakeIdentity (); using (CGPath p1 = new CGPath ()) using (CGPath p2 = new CGPath ()) { - Assert.IsTrue (p1.IsEmpty, "IsEmpty-1"); + Assert.That (p1.IsEmpty, Is.True, "IsEmpty-1"); p1.MoveToPoint (0, 0); p1.AddCurveToPoint (1, 2, 3, 4, 5, 6); p2.MoveToPoint (0, 0); p2.AddCurveToPoint (matrix, 1, 2, 3, 4, 5, 6); - Assert.IsFalse (p1.IsEmpty, "IsEmpty-2"); + Assert.That (p1.IsEmpty, Is.False, "IsEmpty-2"); Assert.That (p1, Is.EqualTo (p2), "CGPathEqualToPath"); } } @@ -102,13 +102,13 @@ public void AddQuadCurveToPoint () var matrix = CGAffineTransform.MakeIdentity (); using (CGPath p1 = new CGPath ()) using (CGPath p2 = new CGPath ()) { - Assert.IsTrue (p1.IsEmpty, "IsEmpty-1"); + Assert.That (p1.IsEmpty, Is.True, "IsEmpty-1"); p1.MoveToPoint (0, 0); p1.AddQuadCurveToPoint (1, 2, 3, 4); p1.CloseSubpath (); p2.MoveToPoint (0, 0); p2.AddQuadCurveToPoint (matrix, 1, 2, 3, 4); - Assert.IsFalse (p1.IsEmpty, "IsEmpty-2"); + Assert.That (p1.IsEmpty, Is.False, "IsEmpty-2"); Assert.That (p1, Is.Not.EqualTo (p2), "CGPathEqualToPath-2"); p2.CloseSubpath (); Assert.That (p1, Is.EqualTo (p2), "CGPathEqualToPath"); @@ -122,10 +122,10 @@ public void AddRect () var matrix = CGAffineTransform.MakeIdentity (); using (CGPath p1 = new CGPath ()) using (CGPath p2 = new CGPath ()) { - Assert.IsTrue (p1.IsEmpty, "IsEmpty-1"); + Assert.That (p1.IsEmpty, Is.True, "IsEmpty-1"); p1.AddRect (rect); p2.AddRect (matrix, rect); - Assert.IsFalse (p1.IsEmpty, "IsEmpty-2"); + Assert.That (p1.IsEmpty, Is.False, "IsEmpty-2"); Assert.That (p1, Is.EqualTo (p2), "CGPathEqualToPath"); } } @@ -137,10 +137,10 @@ public void AddRects () var matrix = CGAffineTransform.MakeIdentity (); using (CGPath p1 = new CGPath ()) using (CGPath p2 = new CGPath ()) { - Assert.IsTrue (p1.IsEmpty, "IsEmpty-1"); + Assert.That (p1.IsEmpty, Is.True, "IsEmpty-1"); p1.AddRects (new [] { rect, rect }, 1); p2.AddRects (matrix, new [] { rect }, 1); - Assert.IsFalse (p1.IsEmpty, "IsEmpty-2"); + Assert.That (p1.IsEmpty, Is.False, "IsEmpty-2"); Assert.That (p1, Is.EqualTo (p2), "CGPathEqualToPath"); } } @@ -151,10 +151,10 @@ public void AddLines () var matrix = CGAffineTransform.MakeIdentity (); using (CGPath p1 = new CGPath ()) using (CGPath p2 = new CGPath ()) { - Assert.IsTrue (p1.IsEmpty, "IsEmpty-1"); + Assert.That (p1.IsEmpty, Is.True, "IsEmpty-1"); p1.AddLines (new [] { CGPoint.Empty }); p2.AddLines (matrix, new [] { CGPoint.Empty }); - Assert.IsFalse (p1.IsEmpty, "IsEmpty-2"); + Assert.That (p1.IsEmpty, Is.False, "IsEmpty-2"); Assert.That (p1, Is.EqualTo (p2), "CGPathEqualToPath"); } } @@ -166,10 +166,10 @@ public void AddEllipseInRect () var matrix = CGAffineTransform.MakeIdentity (); using (CGPath p1 = new CGPath ()) using (CGPath p2 = new CGPath ()) { - Assert.IsTrue (p1.IsEmpty, "IsEmpty-1"); + Assert.That (p1.IsEmpty, Is.True, "IsEmpty-1"); p1.AddEllipseInRect (rect); p2.AddEllipseInRect (matrix, rect); - Assert.IsFalse (p1.IsEmpty, "IsEmpty-2"); + Assert.That (p1.IsEmpty, Is.False, "IsEmpty-2"); Assert.That (p1, Is.EqualTo (p2), "CGPathEqualToPath"); } } @@ -180,10 +180,10 @@ public void AddArc () var matrix = CGAffineTransform.MakeIdentity (); using (CGPath p1 = new CGPath ()) using (CGPath p2 = new CGPath ()) { - Assert.IsTrue (p1.IsEmpty, "IsEmpty-1"); + Assert.That (p1.IsEmpty, Is.True, "IsEmpty-1"); p1.AddArc (0, 0, 10, 0, 90, true); p2.AddArc (matrix, 0, 0, 10, 0, 90, true); - Assert.IsFalse (p1.IsEmpty, "IsEmpty-2"); + Assert.That (p1.IsEmpty, Is.False, "IsEmpty-2"); Assert.That (p1, Is.EqualTo (p2), "CGPathEqualToPath"); } } @@ -194,12 +194,12 @@ public void AddArcToPoint () var matrix = CGAffineTransform.MakeIdentity (); using (CGPath p1 = new CGPath ()) using (CGPath p2 = new CGPath ()) { - Assert.IsTrue (p1.IsEmpty, "IsEmpty-1"); + Assert.That (p1.IsEmpty, Is.True, "IsEmpty-1"); p1.MoveToPoint (0, 0); p1.AddArcToPoint (0, 0, 10, 0, 90); p2.MoveToPoint (0, 0); p2.AddArcToPoint (matrix, 0, 0, 10, 0, 90); - Assert.IsFalse (p1.IsEmpty, "IsEmpty-2"); + Assert.That (p1.IsEmpty, Is.False, "IsEmpty-2"); Assert.That (p1, Is.EqualTo (p2), "CGPathEqualToPath"); } } @@ -210,12 +210,12 @@ public void AddRelativeArc () var matrix = CGAffineTransform.MakeIdentity (); using (CGPath p1 = new CGPath ()) using (CGPath p2 = new CGPath ()) { - Assert.IsTrue (p1.IsEmpty, "IsEmpty-1"); + Assert.That (p1.IsEmpty, Is.True, "IsEmpty-1"); p1.MoveToPoint (0, 0); p1.AddRelativeArc (0, 0, 10, 0, 90); p2.MoveToPoint (0, 0); p2.AddRelativeArc (matrix, 0, 0, 10, 0, 90); - Assert.IsFalse (p1.IsEmpty, "IsEmpty-2"); + Assert.That (p1.IsEmpty, Is.False, "IsEmpty-2"); Assert.That (p1, Is.EqualTo (p2), "CGPathEqualToPath"); } } @@ -227,7 +227,7 @@ public void AddPath () using (CGPath p2 = new CGPath ()) { p1.MoveToPoint (0, 0); p2.AddPath (p1); - Assert.IsFalse (p2.IsEmpty, "IsEmpty"); + Assert.That (p2.IsEmpty, Is.False, "IsEmpty"); } } @@ -238,8 +238,8 @@ public void Normalizing () using (CGPath p1 = new CGPath ()) { p1.MoveToPoint (0, 0); p1.AddLineToPoint (1, 1); - Assert.IsNotNull (p1.CreateByNormalizing (false)); - Assert.IsNotNull (p1.CreateByNormalizing (true)); + Assert.That (p1.CreateByNormalizing (false), Is.Not.Null); + Assert.That (p1.CreateByNormalizing (true), Is.Not.Null); } } @@ -253,8 +253,8 @@ public void Union () using (CGPath p2 = new CGPath ()) { p2.MoveToPoint (2, 2); p2.AddLineToPoint (0, 0); - Assert.IsNotNull (p1.CreateByUnioningPath (p2, false)); - Assert.IsNotNull (p1.CreateByUnioningPath (p2, true)); + Assert.That (p1.CreateByUnioningPath (p2, false), Is.Not.Null); + Assert.That (p1.CreateByUnioningPath (p2, true), Is.Not.Null); } } } @@ -269,8 +269,8 @@ public void Intersecting () using (CGPath p2 = new CGPath ()) { p2.MoveToPoint (2, 2); p2.AddLineToPoint (0, 0); - Assert.IsNotNull (p1.CreateByIntersectingPath (p2, false)); - Assert.IsNotNull (p1.CreateByIntersectingPath (p2, true)); + Assert.That (p1.CreateByIntersectingPath (p2, false), Is.Not.Null); + Assert.That (p1.CreateByIntersectingPath (p2, true), Is.Not.Null); } } } @@ -285,8 +285,8 @@ public void Subtracting () using (CGPath p2 = new CGPath ()) { p2.MoveToPoint (2, 2); p2.AddLineToPoint (0, 0); - Assert.IsNotNull (p1.CreateBySubtractingPath (p2, false)); - Assert.IsNotNull (p1.CreateBySubtractingPath (p2, true)); + Assert.That (p1.CreateBySubtractingPath (p2, false), Is.Not.Null); + Assert.That (p1.CreateBySubtractingPath (p2, true), Is.Not.Null); } } } @@ -301,8 +301,8 @@ public void SymmetricDifference () using (CGPath p2 = new CGPath ()) { p2.MoveToPoint (2, 2); p2.AddLineToPoint (0, 0); - Assert.IsNotNull (p1.CreateBySymmetricDifferenceOfPath (p2, false)); - Assert.IsNotNull (p1.CreateBySymmetricDifferenceOfPath (p2, true)); + Assert.That (p1.CreateBySymmetricDifferenceOfPath (p2, false), Is.Not.Null); + Assert.That (p1.CreateBySymmetricDifferenceOfPath (p2, true), Is.Not.Null); } } } @@ -317,8 +317,8 @@ public void LineBySubtracting () using (CGPath p2 = new CGPath ()) { p2.MoveToPoint (2, 2); p2.AddLineToPoint (0, 0); - Assert.IsNotNull (p1.CreateLineBySubtractingPath (p2, false)); - Assert.IsNotNull (p1.CreateLineBySubtractingPath (p2, true)); + Assert.That (p1.CreateLineBySubtractingPath (p2, false), Is.Not.Null); + Assert.That (p1.CreateLineBySubtractingPath (p2, true), Is.Not.Null); } } } @@ -333,8 +333,8 @@ public void LineByIntersecting () using (CGPath p2 = new CGPath ()) { p2.MoveToPoint (2, 2); p2.AddLineToPoint (0, 0); - Assert.IsNotNull (p1.CreateLineByIntersectingPath (p2, false)); - Assert.IsNotNull (p1.CreateLineByIntersectingPath (p2, true)); + Assert.That (p1.CreateLineByIntersectingPath (p2, false), Is.Not.Null); + Assert.That (p1.CreateLineByIntersectingPath (p2, true), Is.Not.Null); } } } @@ -346,8 +346,8 @@ public void GetSeparateComponents () using (CGPath p1 = new CGPath ()) { p1.MoveToPoint (0, 0); p1.AddLineToPoint (1, 1); - Assert.AreEqual (0, p1.GetSeparateComponents (true).Length); - Assert.AreEqual (0, p1.GetSeparateComponents (false).Length); + Assert.That (p1.GetSeparateComponents (true).Length, Is.EqualTo (0)); + Assert.That (p1.GetSeparateComponents (false).Length, Is.EqualTo (0)); } } @@ -358,7 +358,7 @@ public void CreateByFlattening () using (CGPath p1 = new CGPath ()) { p1.MoveToPoint (0, 0); p1.AddLineToPoint (1, 1); - Assert.IsNotNull (p1.CreateByFlattening (new nfloat (0.5))); + Assert.That (p1.CreateByFlattening (new nfloat (0.5)), Is.Not.Null); } } @@ -372,8 +372,8 @@ public void DoesIntersect () using (CGPath p2 = new CGPath ()) { p2.MoveToPoint (0, 2); p2.AddLineToPoint (2, 0); - Assert.IsFalse (p1.DoesIntersect (p2, false)); - Assert.IsFalse (p1.DoesIntersect (p2, false)); + Assert.That (p1.DoesIntersect (p2, false), Is.False); + Assert.That (p1.DoesIntersect (p2, false), Is.False); } } } @@ -387,7 +387,7 @@ public void Bug40230 () // Assertion failed: (corner_height >= 0 && 2 * corner_height <= CGRectGetHeight(rect)), function CGPathRef CGPathCreateWithRoundedRect Assert.Throws (() => CGPath.FromRoundedRect (rect, 1, 13.5f), "height"); using (var path = CGPath.FromRoundedRect (rect, 1, 1)) { - Assert.IsNotNull (path, "path"); + Assert.That (path, Is.Not.Null, "path"); } } @@ -399,9 +399,9 @@ public void IncreaseRetainCountMakeMutable () var count = CFGetRetainCount (p1.Handle); using (var copy = p1.Copy ()) { var newRetainCount = CFGetRetainCount (copy.Handle); - Assert.AreEqual (count, newRetainCount, "Ref count should not have changed."); - Assert.AreEqual ((nint) 1, count, "Original count."); - Assert.AreEqual ((nint) 1, newRetainCount, "New count"); + Assert.That (newRetainCount, Is.EqualTo (count), "Ref count should not have changed."); + Assert.That (count, Is.EqualTo ((nint) 1), "Original count."); + Assert.That (newRetainCount, Is.EqualTo ((nint) 1), "New count"); } } } diff --git a/tests/monotouch-test/CoreGraphics/PointTest.cs b/tests/monotouch-test/CoreGraphics/PointTest.cs index c7bb4948cad5..0fb9f695bf14 100644 --- a/tests/monotouch-test/CoreGraphics/PointTest.cs +++ b/tests/monotouch-test/CoreGraphics/PointTest.cs @@ -17,7 +17,7 @@ public class PointTest { public void ToStringTest () { var point = new CGPoint ((nfloat) 1, (nfloat) 2); - Assert.AreEqual ("{1, 2}", point.ToString (), "ToString"); + Assert.That (point.ToString (), Is.EqualTo ("{1, 2}"), "ToString"); } } } diff --git a/tests/monotouch-test/CoreGraphics/RectTest.cs b/tests/monotouch-test/CoreGraphics/RectTest.cs index ced9f14f8e65..79cc65edeb6d 100644 --- a/tests/monotouch-test/CoreGraphics/RectTest.cs +++ b/tests/monotouch-test/CoreGraphics/RectTest.cs @@ -18,52 +18,52 @@ public void Inflate () { var rect = new CGRect (1, 2, 3, 4); rect.Inflate (5, 6); - Assert.AreEqual (-4, (int) rect.X, "x 1"); - Assert.AreEqual (-4, (int) rect.Y, "y 1"); - Assert.AreEqual (13, (int) rect.Width, "w 1"); - Assert.AreEqual (16, (int) rect.Height, "h 1"); + Assert.That ((int) rect.X, Is.EqualTo (-4), "x 1"); + Assert.That ((int) rect.Y, Is.EqualTo (-4), "y 1"); + Assert.That ((int) rect.Width, Is.EqualTo (13), "w 1"); + Assert.That ((int) rect.Height, Is.EqualTo (16), "h 1"); rect.Inflate (new CGSize (10, 20)); - Assert.AreEqual (-14, (int) rect.X, "x 2"); - Assert.AreEqual (-24, (int) rect.Y, "y 2"); - Assert.AreEqual (33, (int) rect.Width, "w 2"); - Assert.AreEqual (56, (int) rect.Height, "h 2"); + Assert.That ((int) rect.X, Is.EqualTo (-14), "x 2"); + Assert.That ((int) rect.Y, Is.EqualTo (-24), "y 2"); + Assert.That ((int) rect.Width, Is.EqualTo (33), "w 2"); + Assert.That ((int) rect.Height, Is.EqualTo (56), "h 2"); rect = CGRect.Inflate (rect, 5, 4); - Assert.AreEqual (-19, (int) rect.X, "x 3"); - Assert.AreEqual (-28, (int) rect.Y, "y 3"); - Assert.AreEqual (43, (int) rect.Width, "w 3"); - Assert.AreEqual (64, (int) rect.Height, "h 3"); + Assert.That ((int) rect.X, Is.EqualTo (-19), "x 3"); + Assert.That ((int) rect.Y, Is.EqualTo (-28), "y 3"); + Assert.That ((int) rect.Width, Is.EqualTo (43), "w 3"); + Assert.That ((int) rect.Height, Is.EqualTo (64), "h 3"); } [Test] public void Null () { - Assert.True (CGRect.Null.IsNull (), "Null.IsNull"); - Assert.True (CGRect.Null.IsEmpty, "Null.IsEmpty"); - Assert.False (CGRect.Null.IsInfinite (), "Null.IsInfinite"); + Assert.That (CGRect.Null.IsNull (), Is.True, "Null.IsNull"); + Assert.That (CGRect.Null.IsEmpty, Is.True, "Null.IsEmpty"); + Assert.That (CGRect.Null.IsInfinite (), Is.False, "Null.IsInfinite"); } [Test] public void Infinite () { - Assert.True (CGRect.Infinite.IsInfinite (), "Infinite.IsInfinite"); - Assert.False (CGRect.Infinite.IsEmpty, "Infinite.IsEmpty"); - Assert.False (CGRect.Infinite.IsNull (), "Infinite.IsNull"); + Assert.That (CGRect.Infinite.IsInfinite (), Is.True, "Infinite.IsInfinite"); + Assert.That (CGRect.Infinite.IsEmpty, Is.False, "Infinite.IsEmpty"); + Assert.That (CGRect.Infinite.IsNull (), Is.False, "Infinite.IsNull"); } [Test] public void Empty () { - Assert.True (CGRect.Empty.IsEmpty, "Empty.IsEmpty"); - Assert.False (CGRect.Empty.IsNull (), "Empty.IsNull"); - Assert.False (CGRect.Empty.IsInfinite (), "Empty.IsInfinite"); + Assert.That (CGRect.Empty.IsEmpty, Is.True, "Empty.IsEmpty"); + Assert.That (CGRect.Empty.IsNull (), Is.False, "Empty.IsNull"); + Assert.That (CGRect.Empty.IsInfinite (), Is.False, "Empty.IsInfinite"); // for System.Drawing compatibility this was named Empty - test confirms it's identical to CGRectZero var handle = Dlfcn.dlopen (Constants.CoreGraphicsLibrary, 0); try { var zero = Dlfcn.GetCGRect (handle, "CGRectZero"); - Assert.AreEqual (CGRect.Empty, zero, "CGRectZero"); + Assert.That (zero, Is.EqualTo (CGRect.Empty), "CGRectZero"); } finally { Dlfcn.dlclose (handle); } @@ -73,7 +73,7 @@ public void Empty () public void ToStringTest () { var rect = new CGRect ((nfloat) 1, (nfloat) 2, (nfloat) 3, (nfloat) 4); - Assert.AreEqual ("{{1, 2}, {3, 4}}", rect.ToString (), "ToString"); + Assert.That (rect.ToString (), Is.EqualTo ("{{1, 2}, {3, 4}}"), "ToString"); } } } diff --git a/tests/monotouch-test/CoreGraphics/ShadingTest.cs b/tests/monotouch-test/CoreGraphics/ShadingTest.cs index 44220f4819c5..17c104a1f98b 100644 --- a/tests/monotouch-test/CoreGraphics/ShadingTest.cs +++ b/tests/monotouch-test/CoreGraphics/ShadingTest.cs @@ -55,7 +55,7 @@ void CreateShadingWithContentHeadroomTest (Func { try { using var hdrCapableColorspace = CGColorSpace.CreateWithName (CGColorSpaceNames.DisplayP3_PQ); - Assert.IsTrue (hdrCapableColorspace.IsHdr, "IsHdr"); + Assert.That (hdrCapableColorspace.IsHdr, Is.True, "IsHdr"); using var slopedFunction = FunctionTest.CreateSlopedFunction (() => functionCalled = true, 1, hdrCapableColorspace.Components + 1); @@ -66,8 +66,8 @@ void CreateShadingWithContentHeadroomTest (Func Marshal.FreeHGlobal (v), out err)) { - Assert.AreEqual (shape, arr.Shape, "2 Shape"); - Assert.AreEqual (MLMultiArrayDataType.Float32, arr.DataType, "2 DataType"); - Assert.AreEqual (strides, arr.Strides, "2 Strides"); - Assert.IsNull (err, "2 err"); + Assert.That (arr.Shape, Is.EqualTo (shape), "2 Shape"); + Assert.That (arr.DataType, Is.EqualTo (MLMultiArrayDataType.Float32), "2 DataType"); + Assert.That (arr.Strides, Is.EqualTo (strides), "2 Strides"); + Assert.That (err, Is.Null, "2 err"); } using (var arr = new MLMultiArray (IntPtr.Zero, nsshape, MLMultiArrayDataType.Double, nsstrides, (v) => Marshal.FreeHGlobal (v), out err)) { - Assert.AreEqual (shape, arr.Shape, "3 Shape"); - Assert.AreEqual (MLMultiArrayDataType.Double, arr.DataType, "3 DataType"); - Assert.AreEqual (strides, arr.Strides, "3 Strides"); - Assert.AreEqual (IntPtr.Zero, arr.DataPointer, "3 DataPointer"); - Assert.IsNull (err, "3 err"); + Assert.That (arr.Shape, Is.EqualTo (shape), "3 Shape"); + Assert.That (arr.DataType, Is.EqualTo (MLMultiArrayDataType.Double), "3 DataType"); + Assert.That (arr.Strides, Is.EqualTo (strides), "3 Strides"); + Assert.That (arr.DataPointer, Is.EqualTo (IntPtr.Zero), "3 DataPointer"); + Assert.That (err, Is.Null, "3 err"); } using (var arr = new MLMultiArray (nsshape, MLMultiArrayDataType.Int32, out err)) { - Assert.AreEqual (shape, arr.Shape, "4 Shape"); - Assert.AreEqual (MLMultiArrayDataType.Int32, arr.DataType, "4 DataType"); - Assert.IsNull (err, "4 err"); + Assert.That (arr.Shape, Is.EqualTo (shape), "4 Shape"); + Assert.That (arr.DataType, Is.EqualTo (MLMultiArrayDataType.Int32), "4 DataType"); + Assert.That (err, Is.Null, "4 err"); } } @@ -61,25 +61,25 @@ public void Indexers () NSError err; var shape = new nint [] { 10 }; using (var arr = new MLMultiArray (shape, MLMultiArrayDataType.Int32, out err)) { - Assert.IsNull (err, "err"); - Assert.AreEqual ((nint) 10, arr.Count, "Count"); - Assert.AreEqual (new nint [] { 10 }, arr.Shape, "Shape"); - Assert.AreEqual (new nint [] { 1 }, arr.Strides, "Strides"); + Assert.That (err, Is.Null, "err"); + Assert.That (arr.Count, Is.EqualTo ((nint) 10), "Count"); + Assert.That (arr.Shape, Is.EqualTo (new nint [] { 10 }), "Shape"); + Assert.That (arr.Strides, Is.EqualTo (new nint [] { 1 }), "Strides"); arr [0] = 0; // MLMultiArray's elements aren't zero-initialized - Assert.AreEqual (0, arr [0].Int32Value, "a"); - Assert.AreEqual (0, arr [new nint [] { 0 }].Int32Value, "b"); - Assert.AreEqual (0, arr [new NSNumber [] { NSNumber.FromNInt (0) }].Int32Value, "c nint"); - Assert.AreEqual (0, arr [new NSNumber [] { NSNumber.FromInt32 (0) }].Int32Value, "c int32"); - Assert.AreEqual (0, arr [new NSNumber [] { NSNumber.FromByte (0) }].Int32Value, "c byte"); - Assert.AreEqual (0, arr [new NSNumber [] { NSNumber.FromFloat (0) }].Int32Value, "c float"); - - Assert.AreEqual (0, arr.GetObject (0).Int32Value, "GetObject a"); - Assert.AreEqual (0, arr.GetObject (new nint [] { 0 }).Int32Value, "GetObject b"); - Assert.AreEqual (0, arr.GetObject (new NSNumber [] { NSNumber.FromNInt (0) }).Int32Value, "GetObject c nint"); - Assert.AreEqual (0, arr.GetObject (new NSNumber [] { NSNumber.FromInt32 (0) }).Int32Value, "GetObject c int32"); - Assert.AreEqual (0, arr.GetObject (new NSNumber [] { NSNumber.FromByte (0) }).Int32Value, "GetObject c byte"); - Assert.AreEqual (0, arr.GetObject (new NSNumber [] { NSNumber.FromFloat (0) }).Int32Value, "GetObject c float"); + Assert.That (arr [0].Int32Value, Is.EqualTo (0), "a"); + Assert.That (arr [new nint [] { 0 }].Int32Value, Is.EqualTo (0), "b"); + Assert.That (arr [new NSNumber [] { NSNumber.FromNInt (0) }].Int32Value, Is.EqualTo (0), "c nint"); + Assert.That (arr [new NSNumber [] { NSNumber.FromInt32 (0) }].Int32Value, Is.EqualTo (0), "c int32"); + Assert.That (arr [new NSNumber [] { NSNumber.FromByte (0) }].Int32Value, Is.EqualTo (0), "c byte"); + Assert.That (arr [new NSNumber [] { NSNumber.FromFloat (0) }].Int32Value, Is.EqualTo (0), "c float"); + + Assert.That (arr.GetObject (0).Int32Value, Is.EqualTo (0), "GetObject a"); + Assert.That (arr.GetObject (new nint [] { 0 }).Int32Value, Is.EqualTo (0), "GetObject b"); + Assert.That (arr.GetObject (new NSNumber [] { NSNumber.FromNInt (0) }).Int32Value, Is.EqualTo (0), "GetObject c nint"); + Assert.That (arr.GetObject (new NSNumber [] { NSNumber.FromInt32 (0) }).Int32Value, Is.EqualTo (0), "GetObject c int32"); + Assert.That (arr.GetObject (new NSNumber [] { NSNumber.FromByte (0) }).Int32Value, Is.EqualTo (0), "GetObject c byte"); + Assert.That (arr.GetObject (new NSNumber [] { NSNumber.FromFloat (0) }).Int32Value, Is.EqualTo (0), "GetObject c float"); arr [1] = NSNumber.FromInt32 (1); arr [new nint [] { 2 }] = NSNumber.FromInt32 (2); @@ -88,28 +88,28 @@ public void Indexers () arr.SetObject (NSNumber.FromInt32 (5), new nint [] { 5 }); arr.SetObject (NSNumber.FromInt32 (6), new NSNumber [] { NSNumber.FromSByte (6) }); - Assert.AreEqual (1, arr [1].Int32Value, "1"); - Assert.AreEqual (2, arr [2].Int32Value, "2"); - Assert.AreEqual (3, arr [3].Int32Value, "3"); - Assert.AreEqual (4, arr [4].Int32Value, "4"); - Assert.AreEqual (5, arr [5].Int32Value, "5"); - Assert.AreEqual (6, arr [6].Int32Value, "6"); + Assert.That (arr [1].Int32Value, Is.EqualTo (1), "1"); + Assert.That (arr [2].Int32Value, Is.EqualTo (2), "2"); + Assert.That (arr [3].Int32Value, Is.EqualTo (3), "3"); + Assert.That (arr [4].Int32Value, Is.EqualTo (4), "4"); + Assert.That (arr [5].Int32Value, Is.EqualTo (5), "5"); + Assert.That (arr [6].Int32Value, Is.EqualTo (6), "6"); } // multi-dimensional shape = new nint [] { 7, 7, 7 }; using (var arr = new MLMultiArray (shape, MLMultiArrayDataType.Int32, out err)) { - Assert.IsNull (err, "err"); - Assert.AreEqual (shape [0] * shape [1] * shape [2], arr.Count, "Count"); + Assert.That (err, Is.Null, "err"); + Assert.That (arr.Count, Is.EqualTo (shape [0] * shape [1] * shape [2]), "Count"); arr [0, 0, 0] = 0; // MLMultiArray's elements aren't zero-initialized - Assert.AreEqual (0, arr [0, 0, 0].Int32Value, "a"); - Assert.AreEqual (0, arr [new nint [] { 0, 0, 0 }].Int32Value, "b"); - Assert.AreEqual (0, arr [new NSNumber [] { NSNumber.FromNInt (0), NSNumber.FromNInt (0), NSNumber.FromNInt (0) }].Int32Value, "c nint"); + Assert.That (arr [0, 0, 0].Int32Value, Is.EqualTo (0), "a"); + Assert.That (arr [new nint [] { 0, 0, 0 }].Int32Value, Is.EqualTo (0), "b"); + Assert.That (arr [new NSNumber [] { NSNumber.FromNInt (0), NSNumber.FromNInt (0), NSNumber.FromNInt (0) }].Int32Value, Is.EqualTo (0), "c nint"); - Assert.AreEqual (0, arr.GetObject (0, 0, 0).Int32Value, "GetObject a"); - Assert.AreEqual (0, arr.GetObject (new nint [] { 0, 0, 0 }).Int32Value, "GetObject b"); - Assert.AreEqual (0, arr.GetObject (new NSNumber [] { NSNumber.FromNInt (0), NSNumber.FromNInt (0), NSNumber.FromNInt (0) }).Int32Value, "GetObject c nint"); + Assert.That (arr.GetObject (0, 0, 0).Int32Value, Is.EqualTo (0), "GetObject a"); + Assert.That (arr.GetObject (new nint [] { 0, 0, 0 }).Int32Value, Is.EqualTo (0), "GetObject b"); + Assert.That (arr.GetObject (new NSNumber [] { NSNumber.FromNInt (0), NSNumber.FromNInt (0), NSNumber.FromNInt (0) }).Int32Value, Is.EqualTo (0), "GetObject c nint"); arr [1, 1, 1] = NSNumber.FromInt32 (1); arr [new nint [] { 2, 2, 2 }] = NSNumber.FromInt32 (2); @@ -118,12 +118,12 @@ public void Indexers () arr.SetObject (NSNumber.FromInt32 (5), new nint [] { 5, 5, 5 }); arr.SetObject (NSNumber.FromInt32 (6), new NSNumber [] { NSNumber.FromSByte (6), NSNumber.FromSByte (6), NSNumber.FromSByte (6) }); - Assert.AreEqual (1, arr [1, 1, 1].Int32Value, "1"); - Assert.AreEqual (2, arr [2, 2, 2].Int32Value, "2"); - Assert.AreEqual (3, arr [3, 3, 3].Int32Value, "3"); - Assert.AreEqual (4, arr [4, 4, 4].Int32Value, "4"); - Assert.AreEqual (5, arr [5, 5, 5].Int32Value, "5"); - Assert.AreEqual (6, arr [6, 6, 6].Int32Value, "6"); + Assert.That (arr [1, 1, 1].Int32Value, Is.EqualTo (1), "1"); + Assert.That (arr [2, 2, 2].Int32Value, Is.EqualTo (2), "2"); + Assert.That (arr [3, 3, 3].Int32Value, Is.EqualTo (3), "3"); + Assert.That (arr [4, 4, 4].Int32Value, Is.EqualTo (4), "4"); + Assert.That (arr [5, 5, 5].Int32Value, Is.EqualTo (5), "5"); + Assert.That (arr [6, 6, 6].Int32Value, Is.EqualTo (6), "6"); } } } diff --git a/tests/monotouch-test/CoreMedia/BlockBufferTest.cs b/tests/monotouch-test/CoreMedia/BlockBufferTest.cs index 484fcf00989c..63bf6a07703c 100644 --- a/tests/monotouch-test/CoreMedia/BlockBufferTest.cs +++ b/tests/monotouch-test/CoreMedia/BlockBufferTest.cs @@ -31,7 +31,7 @@ public void CreateEmpty () public void CMBlockBufferCustomBlockSource () { var type = typeof (CMCustomBlockAllocator).GetNestedType ("CMBlockBufferCustomBlockSource", BindingFlags.NonPublic); - Assert.NotNull (type, "CMBlockBufferCustomBlockSource"); + Assert.That (type, Is.Not.Null, "CMBlockBufferCustomBlockSource"); // it's 28 (not 32) bytes when executed on 64bits iOS, which implies it's packed to 4 bytes #pragma warning disable IL3050 // Using member 'System.Runtime.InteropServices.Marshal.SizeOf(Type)' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. Marshalling code for the object might not be available. Use the SizeOf overload instead. Assert.That (Marshal.SizeOf (type), Is.EqualTo (4 + 3 * IntPtr.Size), "Size"); @@ -75,7 +75,7 @@ public void AppendMemoryBlockTest () Assert.That (err2, Is.EqualTo (CMBlockBufferError.None), "AppendMemoryBlock error"); Assert.That (bb.DataLength, Is.EqualTo ((nuint) 10), "FromMemoryBlock DataLength"); } - Assert.IsTrue (freeCalled, "FromMemoryBlock FreeCalled"); + Assert.That (freeCalled, Is.True, "FromMemoryBlock FreeCalled"); } public bool allocateCalled; @@ -107,9 +107,9 @@ public void FromMemoryBlockAndContiguousTest () using (var bb = CMBlockBuffer.FromMemoryBlock (IntPtr.Zero, 16, allocator, 0, 5, CMBlockBufferFlags.AssureMemoryNow, out err1)) { Assert.That (err1, Is.EqualTo (CMBlockBufferError.None), "FromMemoryBlock error"); Assert.That (bb.DataLength, Is.EqualTo ((nuint) 5), "FromMemoryBlock DataLength"); - Assert.IsTrue (allocateCalled, "FromMemoryBlock AllocateCalled"); + Assert.That (allocateCalled, Is.True, "FromMemoryBlock AllocateCalled"); } - Assert.IsTrue (freeCalled, "FromMemoryBlock FreeCalled"); + Assert.That (freeCalled, Is.True, "FromMemoryBlock FreeCalled"); } class CustomAllocator : CMCustomBlockAllocator { @@ -209,7 +209,7 @@ public void CopyDataBytesTest () err = buf.CopyDataBytes (0, (uint) data.Length, destPointer); Assert.That (err, Is.EqualTo (CMBlockBufferError.None), $"CMBlockBufferError 2: {err}"); for (int i = 0; i < data.Length; i++) - Assert.AreEqual (data [0], destData [0], $"CMBlockBuffer CopyDataBytesTest iteration: {i}"); + Assert.That (destData [0], Is.EqualTo (data [0]), $"CMBlockBuffer CopyDataBytesTest iteration: {i}"); } pinned.Free (); destPinned.Free (); @@ -227,7 +227,7 @@ public void CopyDataBytesUsingManagedArrayTest () err = buf.CopyDataBytes (0, (uint) data.Length, out destData); Assert.That (err, Is.EqualTo (CMBlockBufferError.None), $"CMBlockBufferError 2: {err}"); for (int i = 0; i < data.Length; i++) - Assert.AreEqual (data [0], destData [0], $"CMBlockBuffer CopyDataBytesUsingManagedArrayTest iteration: {i}"); + Assert.That (destData [0], Is.EqualTo (data [0]), $"CMBlockBuffer CopyDataBytesUsingManagedArrayTest iteration: {i}"); } } @@ -248,7 +248,7 @@ public void ReplaceDataBytesTest () err = buf.ReplaceDataBytes (replacePointer, 0, (uint) replaceData.Length); Assert.That (err, Is.EqualTo (CMBlockBufferError.None), $"CMBlockBufferError 2: {err}"); for (int i = 0; i < data.Length; i++) - Assert.AreEqual (0x5, data [0], $"CMBlockBuffer ReplaceDataBytesTest iteration: {i}"); + Assert.That (data [0], Is.EqualTo (0x5), $"CMBlockBuffer ReplaceDataBytesTest iteration: {i}"); } pinned.Free (); replacePinned.Free (); @@ -267,7 +267,7 @@ public void ReplaceDataBytesManagedTest () err = buf.ReplaceDataBytes (replaceData, 0); Assert.That (err, Is.EqualTo (CMBlockBufferError.None), $"CMBlockBufferError 2: {err}"); for (int i = 0; i < data.Length; i++) - Assert.AreEqual (0x5, data [0], $"CMBlockBuffer ReplaceDataBytesManagedTest iteration: {i}"); + Assert.That (data [0], Is.EqualTo (0x5), $"CMBlockBuffer ReplaceDataBytesManagedTest iteration: {i}"); } } @@ -290,7 +290,7 @@ public void AccessDataBytesTest () Marshal.Copy (outPtr, tempBuffer, 0, 5); for (int i = 0; i < tempBuffer.Length; i++) - Assert.AreEqual ((byte) (i + 5), tempBuffer [i], $"CMBlockBuffer AccessDataBytesTest iteration: {i}"); + Assert.That (tempBuffer [i], Is.EqualTo ((byte) (i + 5)), $"CMBlockBuffer AccessDataBytesTest iteration: {i}"); } pinned.Free (); tempBufferPinned.Free (); @@ -315,7 +315,7 @@ public void GetDataPointerTest () Marshal.Copy (outPtr, tempBuffer, 0, (int) lengthAtOffset); for (int i = 0; i < tempBuffer.Length; i++) - Assert.AreEqual ((byte) (i + 5), tempBuffer [i], $"CMBlockBuffer GetDataPointerTest iteration: {i}"); + Assert.That (tempBuffer [i], Is.EqualTo ((byte) (i + 5)), $"CMBlockBuffer GetDataPointerTest iteration: {i}"); } pinned.Free (); } diff --git a/tests/monotouch-test/CoreMedia/CMClockOrTimebaseTest.cs b/tests/monotouch-test/CoreMedia/CMClockOrTimebaseTest.cs index 48a7673b80d1..4498f90a386f 100644 --- a/tests/monotouch-test/CoreMedia/CMClockOrTimebaseTest.cs +++ b/tests/monotouch-test/CoreMedia/CMClockOrTimebaseTest.cs @@ -15,7 +15,7 @@ public void RetainReleaseTest () var clock = CMClock.HostTimeClock; var timebase = Runtime.GetINativeObject (clock.Handle, false); // we should be able to dispose the clock and the timebase with no crashes. - Assert.AreEqual (clock.Handle, timebase.Handle); + Assert.That (timebase.Handle, Is.EqualTo (clock.Handle)); clock.Dispose (); timebase.Dispose (); } diff --git a/tests/monotouch-test/CoreMedia/CMClockTest.cs b/tests/monotouch-test/CoreMedia/CMClockTest.cs index 24b4e11c93ab..1e5741e9c771 100644 --- a/tests/monotouch-test/CoreMedia/CMClockTest.cs +++ b/tests/monotouch-test/CoreMedia/CMClockTest.cs @@ -28,7 +28,7 @@ public void CreateAudioClock () using (var clock = CMClock.CreateAudioClock (out ce)) { if (ce == (CMClockError) (-101)) TestRuntime.IgnoreInCI ("For unknown reasons, we might get -101 as an error code on the bots sometimes."); - Assert.AreEqual (CMClockError.None, ce); + Assert.That (ce, Is.EqualTo (CMClockError.None)); } } #endif diff --git a/tests/monotouch-test/CoreMedia/CMFormatDescriptionTest.cs b/tests/monotouch-test/CoreMedia/CMFormatDescriptionTest.cs index b9fb6269ee4f..c2526b13c0e2 100644 --- a/tests/monotouch-test/CoreMedia/CMFormatDescriptionTest.cs +++ b/tests/monotouch-test/CoreMedia/CMFormatDescriptionTest.cs @@ -25,10 +25,10 @@ public void ClosedCaption () { CMFormatDescriptionError fde; using (var fd = CMFormatDescription.Create (CMMediaType.ClosedCaption, (uint) CMClosedCaptionFormatType.CEA608, out fde)) { - Assert.AreEqual (CMFormatDescriptionError.None, fde, "#1"); - Assert.AreEqual ((CMMuxedStreamType) 0, fd.MuxedStreamType, "#2"); - Assert.AreEqual (CMMediaType.ClosedCaption, fd.MediaType, "#3"); - Assert.AreEqual (CMClosedCaptionFormatType.CEA608, fd.ClosedCaptionFormatType, "#4"); + Assert.That (fde, Is.EqualTo (CMFormatDescriptionError.None), "#1"); + Assert.That (fd.MuxedStreamType, Is.EqualTo ((CMMuxedStreamType) 0), "#2"); + Assert.That (fd.MediaType, Is.EqualTo (CMMediaType.ClosedCaption), "#3"); + Assert.That (fd.ClosedCaptionFormatType, Is.EqualTo (CMClosedCaptionFormatType.CEA608), "#4"); } } @@ -47,12 +47,12 @@ public void Video () case AVAuthorizationStatus.Denied: case AVAuthorizationStatus.NotDetermined: // We can't test the below, since the some other tests may have initialized whatever we need for the API to work correctly. - // Assert.Null (CMFormatDescription.Create (CMMediaType.Video, (uint) CMVideoCodecType.H264, out fde), "null ({0})", auth); + // Assert.That (CMFormatDescription.Create (CMMediaType.Video, (uint) CMVideoCodecType.H264, out fde), Is.Null, "null ({0})", auth); // Assert.That (fde, Is.EqualTo (CMFormatDescriptionError.InvalidParameter), "CMFormatDescriptionError"); break; case AVAuthorizationStatus.Authorized: // We can't test the below, since the some other tests may have initialized whatever we need for the API to work correctly. - // Assert.Null (CMFormatDescription.Create (CMMediaType.Video, (uint) CMVideoCodecType.H264, out fde), "null (authorized)"); + // Assert.That (CMFormatDescription.Create (CMMediaType.Video, (uint) CMVideoCodecType.H264, out fde), Is.Null, "null (authorized)"); // Assert.That (fde, Is.EqualTo (CMFormatDescriptionError.InvalidParameter), "CMFormatDescriptionError (authorized)"); using (var captureSession = new AVCaptureSession ()) { @@ -66,7 +66,7 @@ public void Video () } } - Assert.IsNotNull (CMFormatDescription.Create (CMMediaType.Video, (uint) CMVideoCodecType.H264, out fde), "not null (authorized)"); + Assert.That (CMFormatDescription.Create (CMMediaType.Video, (uint) CMVideoCodecType.H264, out fde), Is.Not.Null, "not null (authorized)"); Assert.That (fde, Is.EqualTo (CMFormatDescriptionError.None), "CMFormatDescriptionError #2 (authorized)"); break; } @@ -117,22 +117,25 @@ public void H264ParameterSetsTest () var desc = CMVideoFormatDescription.FromH264ParameterSets (props, 4, out error); props = null; Assert.That (error == CMFormatDescriptionError.None, "H264ParameterSetsTest"); - Assert.NotNull (desc, "H264ParameterSetsTest"); - Assert.That (desc.Dimensions.Height == 1080 && desc.Dimensions.Width == 1920, "H264ParameterSetsTest"); + Assert.That (desc, Is.Not.Null, "H264ParameterSetsTest"); + Assert.That (desc.Dimensions.Height, Is.EqualTo (1080), "H264ParameterSetsTest Height"); + Assert.That (desc.Dimensions.Width, Is.EqualTo (1920), "H264ParameterSetsTest Width"); CMFormatDescriptionError err; nuint paramCount; int nalCount; var bytes = desc.GetH264ParameterSet (0, out paramCount, out nalCount, out err); Assert.That (err == CMFormatDescriptionError.None, "H264ParameterSetsTest"); - Assert.NotNull (bytes, "H264ParameterSetsTest"); - Assert.True (nalCount == 4 && paramCount == 2); + Assert.That (bytes, Is.Not.Null, "H264ParameterSetsTest"); + Assert.That (nalCount, Is.EqualTo (4), "H264 nalCount 0"); + Assert.That (paramCount, Is.EqualTo ((nuint) 2), "H264 paramCount 0"); Assert.That (arr0, Is.EqualTo (bytes), "H264ParameterSetsTest roundtrip"); bytes = desc.GetH264ParameterSet (1, out paramCount, out nalCount, out err); Assert.That (err == CMFormatDescriptionError.None, "H264ParameterSetsTest"); - Assert.NotNull (bytes, "H264ParameterSetsTest"); - Assert.True (nalCount == 4 && paramCount == 2); + Assert.That (bytes, Is.Not.Null, "H264ParameterSetsTest"); + Assert.That (nalCount, Is.EqualTo (4), "H264 nalCount 1"); + Assert.That (paramCount, Is.EqualTo ((nuint) 2), "H264 paramCount 1"); Assert.That (arr1, Is.EqualTo (bytes), "H264ParameterSetsTest roundtrip"); } @@ -151,28 +154,32 @@ public void HevcParameterSetsTest () props = null; Assert.That (error == CMFormatDescriptionError.None, "HevcParameterSetsTest 1"); - Assert.NotNull (desc, "HevcParameterSetsTest 2"); - Assert.That (desc.Dimensions.Height == 720 && desc.Dimensions.Width == 1280, "HevcParameterSetsTest 3"); + Assert.That (desc, Is.Not.Null, "HevcParameterSetsTest 2"); + Assert.That (desc.Dimensions.Height, Is.EqualTo (720), "HevcParameterSetsTest Height"); + Assert.That (desc.Dimensions.Width, Is.EqualTo (1280), "HevcParameterSetsTest Width"); CMFormatDescriptionError err; nuint paramCount; int nalCount; var bytes = desc.GetHevcParameterSet (0, out paramCount, out nalCount, out err); Assert.That (err == CMFormatDescriptionError.None, "HevcParameterSetsTest arr0 1"); - Assert.NotNull (bytes, "HevcParameterSetsTest arr0 2"); - Assert.True (nalCount == 4 && paramCount == 3); + Assert.That (bytes, Is.Not.Null, "HevcParameterSetsTest arr0 2"); + Assert.That (nalCount, Is.EqualTo (4), "Hevc nalCount arr0"); + Assert.That (paramCount, Is.EqualTo ((nuint) 3), "Hevc paramCount arr0"); Assert.That (arr0, Is.EqualTo (bytes), "HevcParameterSetsTest arr0 roundtrip"); bytes = desc.GetHevcParameterSet (1, out paramCount, out nalCount, out err); Assert.That (err == CMFormatDescriptionError.None, "HevcParameterSetsTest arr1 1"); - Assert.NotNull (bytes, "HevcParameterSetsTest arr1 2"); - Assert.True (nalCount == 4 && paramCount == 3); + Assert.That (bytes, Is.Not.Null, "HevcParameterSetsTest arr1 2"); + Assert.That (nalCount, Is.EqualTo (4), "Hevc nalCount arr1"); + Assert.That (paramCount, Is.EqualTo ((nuint) 3), "Hevc paramCount arr1"); Assert.That (arr1, Is.EqualTo (bytes), "HevcParameterSetsTest arr1 roundtrip"); bytes = desc.GetHevcParameterSet (2, out paramCount, out nalCount, out err); Assert.That (err == CMFormatDescriptionError.None, "HevcParameterSetsTest arr2 1"); - Assert.NotNull (bytes, "HevcParameterSetsTest arr2 2"); - Assert.True (nalCount == 4 && paramCount == 3); + Assert.That (bytes, Is.Not.Null, "HevcParameterSetsTest arr2 2"); + Assert.That (nalCount, Is.EqualTo (4), "Hevc nalCount arr2"); + Assert.That (paramCount, Is.EqualTo ((nuint) 3), "Hevc paramCount arr2"); Assert.That (arr2, Is.EqualTo (bytes), "HevcParameterSetsTest arr2 roundtrip"); } @@ -180,30 +187,30 @@ public void HevcParameterSetsTest () public void VideoFormatDescriptionConstructors () { using (var obj = new CMVideoFormatDescription (CMVideoCodecType.H264, new CMVideoDimensions (960, 540))) { - Assert.AreEqual (960, obj.Dimensions.Width, "Width #1"); - Assert.AreEqual (540, obj.Dimensions.Height, "Height #1"); - Assert.AreEqual (CMVideoCodecType.H264, obj.VideoCodecType, "VideoCodecType #1"); - Assert.IsNull (obj.GetExtensions (), "Extensions #1"); + Assert.That (obj.Dimensions.Width, Is.EqualTo (960), "Width #1"); + Assert.That (obj.Dimensions.Height, Is.EqualTo (540), "Height #1"); + Assert.That (obj.VideoCodecType, Is.EqualTo (CMVideoCodecType.H264), "VideoCodecType #1"); + Assert.That (obj.GetExtensions (), Is.Null, "Extensions #1"); } using (var obj = new CMVideoFormatDescription (CMVideoCodecType.H263, new CMVideoDimensions (480, 270), (NSDictionary?) null)) { - Assert.AreEqual (480, obj.Dimensions.Width, "Width #2"); - Assert.AreEqual (270, obj.Dimensions.Height, "Height #2"); - Assert.AreEqual (CMVideoCodecType.H263, obj.VideoCodecType, "VideoCodecType #2"); - Assert.IsNull (obj.GetExtensions (), "Extensions #2"); + Assert.That (obj.Dimensions.Width, Is.EqualTo (480), "Width #2"); + Assert.That (obj.Dimensions.Height, Is.EqualTo (270), "Height #2"); + Assert.That (obj.VideoCodecType, Is.EqualTo (CMVideoCodecType.H263), "VideoCodecType #2"); + Assert.That (obj.GetExtensions (), Is.Null, "Extensions #2"); } var extensions = new CMFormatDescriptionExtensions () { BytesPerRow = 24, }; using (var obj = new CMVideoFormatDescription (CMVideoCodecType.H263, new CMVideoDimensions (480, 270), extensions)) { - Assert.AreEqual (480, obj.Dimensions.Width, "Width #3"); - Assert.AreEqual (270, obj.Dimensions.Height, "Height #3"); - Assert.AreEqual (CMVideoCodecType.H263, obj.VideoCodecType, "VideoCodecType #3"); + Assert.That (obj.Dimensions.Width, Is.EqualTo (480), "Width #3"); + Assert.That (obj.Dimensions.Height, Is.EqualTo (270), "Height #3"); + Assert.That (obj.VideoCodecType, Is.EqualTo (CMVideoCodecType.H263), "VideoCodecType #3"); var dict = obj.GetExtensions (); var ext = new CMFormatDescriptionExtensions (dict); - Assert.IsNotNull (ext, "Extensions #3"); - Assert.AreEqual (24, ext.BytesPerRow, "Extensions.BytesPerRow #3"); + Assert.That (ext, Is.Not.Null, "Extensions #3"); + Assert.That (ext.BytesPerRow, Is.EqualTo (24), "Extensions.BytesPerRow #3"); } } diff --git a/tests/monotouch-test/CoreMedia/CMMemoryPoolTest.cs b/tests/monotouch-test/CoreMedia/CMMemoryPoolTest.cs index e481c8a91ade..701116454ca3 100644 --- a/tests/monotouch-test/CoreMedia/CMMemoryPoolTest.cs +++ b/tests/monotouch-test/CoreMedia/CMMemoryPoolTest.cs @@ -22,7 +22,7 @@ public void Ctor () using (var mp = new CMMemoryPool ()) { var allocator = mp.GetAllocator (); var ptr = allocator.Allocate (55); - Assert.AreNotEqual (IntPtr.Zero, ptr); + Assert.That (ptr, Is.Not.EqualTo (IntPtr.Zero)); allocator.Deallocate (ptr); } } @@ -35,7 +35,7 @@ public void CtorAgeOutPeriod () using (var mp = new CMMemoryPool (TimeSpan.FromSeconds (40))) { var allocator = mp.GetAllocator (); var ptr = allocator.Allocate (2); - Assert.AreNotEqual (IntPtr.Zero, ptr); + Assert.That (ptr, Is.Not.EqualTo (IntPtr.Zero)); allocator.Deallocate (ptr); } } diff --git a/tests/monotouch-test/CoreMedia/CMTagCollectionTests.cs b/tests/monotouch-test/CoreMedia/CMTagCollectionTests.cs index 57db0e5a1a6c..36c99149b63e 100644 --- a/tests/monotouch-test/CoreMedia/CMTagCollectionTests.cs +++ b/tests/monotouch-test/CoreMedia/CMTagCollectionTests.cs @@ -23,7 +23,7 @@ public void GetTypeIdTest () { TestRuntime.AssertXcodeVersion (15, 0); - Assert.AreNotEqual (0, CMTagCollection.GetTypeId (), "GetTypeId"); + Assert.That (CMTagCollection.GetTypeId (), Is.Not.EqualTo (0), "GetTypeId"); } [Test] @@ -33,26 +33,26 @@ public void CreateTest () { using var tagCollection = CMTagCollection.Create (); - Assert.AreEqual (0, (int) tagCollection.Count, "Count A"); - Assert.IsTrue (tagCollection.IsEmpty, "IsEmpty A"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (0), "Count A"); + Assert.That (tagCollection.IsEmpty, Is.True, "IsEmpty A"); } { using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo); - Assert.AreEqual (1, (int) tagCollection.Count, "Count B"); - Assert.IsFalse (tagCollection.IsEmpty, "IsEmpty B"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (1), "Count B"); + Assert.That (tagCollection.IsEmpty, Is.False, "IsEmpty B"); } { using var tagCollection = CMTagCollection.Create (new CMTag [] { CMTag.MediaTypeVideo }); - Assert.AreEqual (1, (int) tagCollection.Count, "Count C"); - Assert.IsFalse (tagCollection.IsEmpty, "IsEmpty C"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (1), "Count C"); + Assert.That (tagCollection.IsEmpty, Is.False, "IsEmpty C"); } { using var tagCollection = CMTagCollection.Create ((CMTag []) null); - Assert.AreEqual (0, (int) tagCollection.Count, "Count D"); - Assert.IsTrue (tagCollection.IsEmpty, "IsEmpty D"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (0), "Count D"); + Assert.That (tagCollection.IsEmpty, Is.True, "IsEmpty D"); } } @@ -63,30 +63,30 @@ public void CreateTest_OSStatus () { using var tagCollection = CMTagCollection.Create (out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status A"); - Assert.AreEqual (0, (int) tagCollection.Count, "Count A"); - Assert.IsTrue (tagCollection.IsEmpty, "IsEmpty A"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status A"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (0), "Count A"); + Assert.That (tagCollection.IsEmpty, Is.True, "IsEmpty A"); } { using var tagCollection = CMTagCollection.Create (out var status, CMTag.MediaTypeVideo); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status B"); - Assert.AreEqual (1, (int) tagCollection.Count, "Count B"); - Assert.IsFalse (tagCollection.IsEmpty, "IsEmpty B"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status B"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (1), "Count B"); + Assert.That (tagCollection.IsEmpty, Is.False, "IsEmpty B"); } { using var tagCollection = CMTagCollection.Create (out var status, new CMTag [] { CMTag.MediaTypeVideo }); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status C"); - Assert.AreEqual (1, (int) tagCollection.Count, "Count C"); - Assert.IsFalse (tagCollection.IsEmpty, "IsEmpty C"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status C"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (1), "Count C"); + Assert.That (tagCollection.IsEmpty, Is.False, "IsEmpty C"); } { using var tagCollection = CMTagCollection.Create (out var status, (CMTag []) null); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status D"); - Assert.AreEqual (0, (int) tagCollection.Count, "Count D"); - Assert.IsTrue (tagCollection.IsEmpty, "IsEmpty D"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status D"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (0), "Count D"); + Assert.That (tagCollection.IsEmpty, Is.True, "IsEmpty D"); } } @@ -97,28 +97,28 @@ public void CreateMutableTest () { using var tagCollection = CMTagCollection.CreateMutable (out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status A"); - Assert.AreEqual (0, (int) tagCollection.Count, "Count A"); - Assert.IsTrue (tagCollection.IsEmpty, "IsEmpty A"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status A"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (0), "Count A"); + Assert.That (tagCollection.IsEmpty, Is.True, "IsEmpty A"); } { using var tagCollection = CMTagCollection.CreateMutable (1, out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status B"); - Assert.AreEqual (0, (int) tagCollection.Count, "Count B"); - Assert.IsTrue (tagCollection.IsEmpty, "IsEmpty B"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status B"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (0), "Count B"); + Assert.That (tagCollection.IsEmpty, Is.True, "IsEmpty B"); } { using var tagCollection = CMTagCollection.CreateMutable (-1, out var status); - Assert.AreEqual (CMTagCollectionError.ParamErr, status, "Status C"); - Assert.IsNull (tagCollection, "Null C"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.ParamErr), "Status C"); + Assert.That (tagCollection, Is.Null, "Null C"); } { using var tagCollection = CMTagCollection.CreateMutable (); - Assert.AreEqual (0, (int) tagCollection.Count, "Count D"); - Assert.IsTrue (tagCollection.IsEmpty, "IsEmpty D"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (0), "Count D"); + Assert.That (tagCollection.IsEmpty, Is.True, "IsEmpty D"); } } @@ -128,13 +128,13 @@ public void CopyTest () TestRuntime.AssertXcodeVersion (15, 0); using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo); - Assert.AreEqual (1, (int) tagCollection.Count, "Count A"); - Assert.IsFalse (tagCollection.IsEmpty, "IsEmpty A"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (1), "Count A"); + Assert.That (tagCollection.IsEmpty, Is.False, "IsEmpty A"); using var copy = tagCollection.Copy (out var status); - Assert.AreEqual (1, (int) copy.Count, "Count B"); - Assert.IsFalse (copy.IsEmpty, "IsEmpty B"); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status B"); + Assert.That ((int) copy.Count, Is.EqualTo (1), "Count B"); + Assert.That (copy.IsEmpty, Is.False, "IsEmpty B"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status B"); } [Test] @@ -143,13 +143,13 @@ public void CreateMutableCopyTest () TestRuntime.AssertXcodeVersion (15, 0); using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo); - Assert.AreEqual (1, (int) tagCollection.Count, "Count A"); - Assert.IsFalse (tagCollection.IsEmpty, "IsEmpty A"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (1), "Count A"); + Assert.That (tagCollection.IsEmpty, Is.False, "IsEmpty A"); using var copy = tagCollection.CreateMutableCopy (out var status); - Assert.AreEqual (1, (int) copy.Count, "Count B"); - Assert.IsFalse (copy.IsEmpty, "IsEmpty B"); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status B"); + Assert.That ((int) copy.Count, Is.EqualTo (1), "Count B"); + Assert.That (copy.IsEmpty, Is.False, "IsEmpty B"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status B"); } [Test] @@ -158,7 +158,7 @@ public void ToStringTest () TestRuntime.AssertXcodeVersion (15, 0); using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo); - Assert.AreEqual ("CMTagCollection{\n{category:'mdia' value:'vide' }\n}", tagCollection.ToString (), "ToString"); + Assert.That (tagCollection.ToString (), Is.EqualTo ("CMTagCollection{\n{category:'mdia' value:'vide' }\n}"), "ToString"); } [Test] @@ -167,8 +167,8 @@ public void ContainsTagTest () TestRuntime.AssertXcodeVersion (15, 0); using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo); - Assert.AreEqual (true, tagCollection.ContainsTag (CMTag.MediaTypeVideo), "MediaTypeVideo"); - Assert.AreEqual (false, tagCollection.ContainsTag (CMTag.MediaTypeAudio), "MediaTypeAudio"); + Assert.That (tagCollection.ContainsTag (CMTag.MediaTypeVideo), Is.EqualTo (true), "MediaTypeVideo"); + Assert.That (tagCollection.ContainsTag (CMTag.MediaTypeAudio), Is.EqualTo (false), "MediaTypeAudio"); } [Test] @@ -178,8 +178,8 @@ public void ContainsTagCollectionTest () using var tagCollection1 = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); using var tagCollection2 = CMTagCollection.Create (CMTag.MediaTypeAudio); - Assert.AreEqual (true, tagCollection1.ContainsTagCollection (tagCollection2), "1"); - Assert.AreEqual (false, tagCollection2.ContainsTagCollection (tagCollection1), "2"); + Assert.That (tagCollection1.ContainsTagCollection (tagCollection2), Is.EqualTo (true), "1"); + Assert.That (tagCollection2.ContainsTagCollection (tagCollection1), Is.EqualTo (false), "2"); Assert.Throws (() => tagCollection1.ContainsTagCollection (null), "Null"); } @@ -190,10 +190,10 @@ public void ContainsTagsTest () TestRuntime.AssertXcodeVersion (15, 0); using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); - Assert.AreEqual (true, tagCollection.ContainsTags (CMTag.MediaTypeVideo), "MediaTypeVideo"); - Assert.AreEqual (true, tagCollection.ContainsTags (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio), "MediaTypeVideo+MediaTypeAudio"); - Assert.AreEqual (false, tagCollection.ContainsTags (CMTag.MediaTypeVideo, CMTag.PackingTypeNone), "MediaTypeVideo+PackingTypeNone"); - Assert.AreEqual (false, tagCollection.ContainsTags (CMTag.PackingTypeNone), "PackingTypeNone"); + Assert.That (tagCollection.ContainsTags (CMTag.MediaTypeVideo), Is.EqualTo (true), "MediaTypeVideo"); + Assert.That (tagCollection.ContainsTags (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio), Is.EqualTo (true), "MediaTypeVideo+MediaTypeAudio"); + Assert.That (tagCollection.ContainsTags (CMTag.MediaTypeVideo, CMTag.PackingTypeNone), Is.EqualTo (false), "MediaTypeVideo+PackingTypeNone"); + Assert.That (tagCollection.ContainsTags (CMTag.PackingTypeNone), Is.EqualTo (false), "PackingTypeNone"); } [Test] @@ -202,8 +202,8 @@ public void ContainsCategoryTest () TestRuntime.AssertXcodeVersion (15, 0); using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); - Assert.AreEqual (false, tagCollection.ContainsCategory (CMTagCategory.ProjectionType), "ProjectionType"); - Assert.AreEqual (true, tagCollection.ContainsCategory (CMTagCategory.MediaType), "MediaType"); + Assert.That (tagCollection.ContainsCategory (CMTagCategory.ProjectionType), Is.EqualTo (false), "ProjectionType"); + Assert.That (tagCollection.ContainsCategory (CMTagCategory.MediaType), Is.EqualTo (true), "MediaType"); } [Test] @@ -212,8 +212,8 @@ public void GetCountTest () TestRuntime.AssertXcodeVersion (15, 0); using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); - Assert.AreEqual (0, (int) tagCollection.GetCount (CMTagCategory.ProjectionType), "ProjectionType"); - Assert.AreEqual (2, (int) tagCollection.GetCount (CMTagCategory.MediaType), "MediaType"); + Assert.That ((int) tagCollection.GetCount (CMTagCategory.ProjectionType), Is.EqualTo (0), "ProjectionType"); + Assert.That ((int) tagCollection.GetCount (CMTagCategory.MediaType), Is.EqualTo (2), "MediaType"); } [Test] @@ -223,7 +223,7 @@ public void TagsTest () using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); var tags = tagCollection.Tags; - Assert.AreEqual (2, tags.Length, "Length"); + Assert.That (tags.Length, Is.EqualTo (2), "Length"); } [Test] @@ -233,8 +233,8 @@ public void GetTagsTest () using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); var tags = tagCollection.GetTags (out var status); - Assert.AreEqual (2, tags.Length, "Length"); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status"); + Assert.That (tags.Length, Is.EqualTo (2), "Length"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status"); } [Test] @@ -245,10 +245,10 @@ public void GetTags2Test () using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); var tags = new CMTag [1]; var status = tagCollection.GetTags (tags, tags.Length, out var tagsCopied); - Assert.AreEqual (1, tags.Length, "Length"); - Assert.AreEqual (1, (int) tagsCopied, "Tags Copied"); - Assert.AreEqual (CMTagCollectionError.ExhaustedBufferSize, status, "Status"); - Assert.IsTrue (tags [0].IsValid, "Tags[0].IsValid"); + Assert.That (tags.Length, Is.EqualTo (1), "Length"); + Assert.That ((int) tagsCopied, Is.EqualTo (1), "Tags Copied"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.ExhaustedBufferSize), "Status"); + Assert.That (tags [0].IsValid, Is.True, "Tags[0].IsValid"); Assert.Throws (() => tagCollection.GetTags (tags, tags.Length + 1, out tagsCopied), "AOORE"); Assert.Throws (() => tagCollection.GetTags (tags, -1, out tagsCopied), "AOORE 2"); @@ -261,8 +261,8 @@ public void GetTagsForCategoryTest () using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio, CMTag.PackingTypeNone); var tags = tagCollection.GetTags (CMTagCategory.MediaType, out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status"); - Assert.AreEqual (2, tags.Length, "Length"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status"); + Assert.That (tags.Length, Is.EqualTo (2), "Length"); } [Test] @@ -273,10 +273,10 @@ public void GetTagsForCategory2Test () using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio, CMTag.PackingTypeNone); var tags = new CMTag [1]; var status = tagCollection.GetTags (CMTagCategory.MediaType, tags, tags.Length, out var tagsCopied); - Assert.AreEqual (1, tags.Length, "Length"); - Assert.AreEqual (1, (int) tagsCopied, "Tags Copied"); - Assert.AreEqual (CMTagCollectionError.ExhaustedBufferSize, status, "Status"); - Assert.IsTrue (tags [0].IsValid, "Tags[0].IsValid"); + Assert.That (tags.Length, Is.EqualTo (1), "Length"); + Assert.That ((int) tagsCopied, Is.EqualTo (1), "Tags Copied"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.ExhaustedBufferSize), "Status"); + Assert.That (tags [0].IsValid, Is.True, "Tags[0].IsValid"); Assert.Throws (() => tagCollection.GetTags (CMTagCategory.MediaType, tags, tags.Length + 1, out var tagsCopied), "AOORE"); Assert.Throws (() => tagCollection.GetTags (CMTagCategory.MediaType, tags, -1, out var tagsCopied), "AOORE 2"); @@ -288,7 +288,7 @@ public void GetCount_Filter () TestRuntime.AssertXcodeVersion (15, 0); using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio, CMTag.PackingTypeNone); - Assert.AreEqual (2, (int) tagCollection.GetCount ((v) => v.Category == CMTagCategory.MediaType), "Count"); + Assert.That ((int) tagCollection.GetCount ((v) => v.Category == CMTagCategory.MediaType), Is.EqualTo (2), "Count"); } [Test] @@ -298,7 +298,7 @@ public void GetTags_Filter () using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio, CMTag.PackingTypeNone); var count = tagCollection.GetCount ((v) => v.Category == CMTagCategory.MediaType); - Assert.AreEqual (2, (int) count, "Count"); + Assert.That ((int) count, Is.EqualTo (2), "Count"); } [Test] @@ -309,10 +309,10 @@ public void GetTags2_Filter () using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio, CMTag.PackingTypeNone); var tags = new CMTag [1]; var status = tagCollection.GetTags ((v) => v.Category == CMTagCategory.MediaType, tags, tags.Length, out var tagsCopied); - Assert.AreEqual (1, tags.Length, "Length"); - Assert.AreEqual (1, (int) tagsCopied, "Tags Copied"); - Assert.AreEqual (CMTagCollectionError.ExhaustedBufferSize, status, "Status"); - Assert.IsTrue (tags [0].IsValid, "Tags[0].IsValid"); + Assert.That (tags.Length, Is.EqualTo (1), "Length"); + Assert.That ((int) tagsCopied, Is.EqualTo (1), "Tags Copied"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.ExhaustedBufferSize), "Status"); + Assert.That (tags [0].IsValid, Is.True, "Tags[0].IsValid"); Assert.Throws (() => tagCollection.GetTags ((v) => v.Category == CMTagCategory.MediaType, tags, tags.Length + 1, out tagsCopied), "AOORE"); Assert.Throws (() => tagCollection.GetTags ((v) => v.Category == CMTagCategory.MediaType, tags, -1, out tagsCopied), "AOORE 2"); @@ -325,8 +325,8 @@ public void CreateWithCopyOfTags_Filter () using var tagCollection1 = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio, CMTag.PackingTypeNone); using var tagCollection2 = tagCollection1.CreateWithCopyOfTags (out var status, CMTagCategory.MediaType); - Assert.AreEqual (2, (int) tagCollection2.Count, "Count"); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status"); + Assert.That ((int) tagCollection2.Count, Is.EqualTo (2), "Count"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status"); } [Test] @@ -339,7 +339,7 @@ public void ApplyTest () tagCollection.Apply ((v) => { counter++; }); - Assert.AreEqual ((int) tagCollection.Count, counter, "Counter"); + Assert.That (counter, Is.EqualTo ((int) tagCollection.Count), "Counter"); } [Test] @@ -353,8 +353,8 @@ public void ApplyUntilTest () counter++; return false; }); - Assert.AreEqual ((int) tagCollection.Count, counter, "Counter A"); - Assert.IsFalse (tag.IsValid, "IsValid A"); + Assert.That (counter, Is.EqualTo ((int) tagCollection.Count), "Counter A"); + Assert.That (tag.IsValid, Is.False, "IsValid A"); counter = 0; tag = tagCollection.ApplyUntil ((v) => { @@ -365,8 +365,8 @@ public void ApplyUntilTest () }); Assert.That (counter, Is.GreaterThan (0), "Counter B1"); Assert.That (counter, Is.LessThanOrEqualTo ((int) tagCollection.Count), "Counter B2"); - Assert.IsTrue (tag.IsValid, "IsValid B"); - Assert.IsTrue (CMTag.Equals (tag, CMTag.PackingTypeNone), "Equals B"); + Assert.That (tag.IsValid, Is.True, "IsValid B"); + Assert.That (CMTag.Equals (tag, CMTag.PackingTypeNone), Is.True, "Equals B"); } [Test] @@ -377,9 +377,9 @@ public void Intersect () using var tagCollection1 = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); using var tagCollection2 = CMTagCollection.Create (CMTag.MediaTypeAudio, CMTag.PackingTypeNone); using var tagCollection = CMTagCollection.Intersect (tagCollection1, tagCollection2, out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status"); - Assert.AreEqual (1, (int) tagCollection.Count, "Count"); - Assert.IsTrue (CMTag.Equals (CMTag.MediaTypeAudio, tagCollection.Tags [0]), "Tag #0"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (1), "Count"); + Assert.That (CMTag.Equals (CMTag.MediaTypeAudio, tagCollection.Tags [0]), Is.True, "Tag #0"); } @@ -391,9 +391,9 @@ public void Intersect_Instance () using var tagCollection1 = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); using var tagCollection2 = CMTagCollection.Create (CMTag.MediaTypeAudio, CMTag.PackingTypeNone); using var tagCollection = tagCollection1.Intersect (tagCollection2, out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status"); - Assert.AreEqual (1, (int) tagCollection.Count, "Count"); - Assert.IsTrue (CMTag.Equals (CMTag.MediaTypeAudio, tagCollection.Tags [0]), "Tag #0"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (1), "Count"); + Assert.That (CMTag.Equals (CMTag.MediaTypeAudio, tagCollection.Tags [0]), Is.True, "Tag #0"); } [Test] @@ -404,8 +404,8 @@ public void Union () using var tagCollection1 = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); using var tagCollection2 = CMTagCollection.Create (CMTag.MediaTypeAudio, CMTag.PackingTypeNone); using var tagCollection = CMTagCollection.Union (tagCollection1, tagCollection2, out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status"); - Assert.AreEqual (3, (int) tagCollection.Count, "Count"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (3), "Count"); } @@ -417,8 +417,8 @@ public void Union_Instance () using var tagCollection1 = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); using var tagCollection2 = CMTagCollection.Create (CMTag.MediaTypeAudio, CMTag.PackingTypeNone); using var tagCollection = tagCollection1.Union (tagCollection2, out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status"); - Assert.AreEqual (3, (int) tagCollection.Count, "Count"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (3), "Count"); } [Test] @@ -429,9 +429,9 @@ public void Subtract () using var tagCollection1 = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); using var tagCollection2 = CMTagCollection.Create (CMTag.MediaTypeAudio, CMTag.PackingTypeNone); using var tagCollection = CMTagCollection.Subtract (tagCollection1, tagCollection2, out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status"); - Assert.AreEqual (1, (int) tagCollection.Count, "Count"); - Assert.IsTrue (CMTag.Equals (CMTag.MediaTypeVideo, tagCollection.Tags [0]), "Tag #0"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (1), "Count"); + Assert.That (CMTag.Equals (CMTag.MediaTypeVideo, tagCollection.Tags [0]), Is.True, "Tag #0"); } [Test] @@ -442,9 +442,9 @@ public void Subtract_Instance () using var tagCollection1 = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); using var tagCollection2 = CMTagCollection.Create (CMTag.MediaTypeAudio, CMTag.PackingTypeNone); using var tagCollection = tagCollection1.Subtract (tagCollection2, out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status"); - Assert.AreEqual (1, (int) tagCollection.Count, "Count"); - Assert.IsTrue (CMTag.Equals (CMTag.MediaTypeVideo, tagCollection.Tags [0]), "Tag #0"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (1), "Count"); + Assert.That (CMTag.Equals (CMTag.MediaTypeVideo, tagCollection.Tags [0]), Is.True, "Tag #0"); } [Test] @@ -455,8 +455,8 @@ public void ExclusiveOr () using var tagCollection1 = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); using var tagCollection2 = CMTagCollection.Create (CMTag.MediaTypeAudio, CMTag.PackingTypeNone); using var tagCollection = CMTagCollection.ExclusiveOr (tagCollection1, tagCollection2, out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status"); - Assert.AreEqual (2, (int) tagCollection.Count, "Count"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (2), "Count"); } [Test] @@ -467,8 +467,8 @@ public void ExclusiveOr_Instance () using var tagCollection1 = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); using var tagCollection2 = CMTagCollection.Create (CMTag.MediaTypeAudio, CMTag.PackingTypeNone); using var tagCollection = tagCollection1.ExclusiveOr (tagCollection2, out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, "Status"); - Assert.AreEqual (2, (int) tagCollection.Count, "Count"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), "Status"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (2), "Count"); } [Test] @@ -478,7 +478,7 @@ public void AddTest () // Trying to modify a non-mutable collection using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo); - Assert.AreEqual (CMTagCollectionError.ParamErr, tagCollection.Add (CMTag.MediaTypeAudio), "Add"); + Assert.That (tagCollection.Add (CMTag.MediaTypeAudio), Is.EqualTo (CMTagCollectionError.ParamErr), "Add"); } [Test] @@ -487,9 +487,9 @@ public void AddMutableTest () TestRuntime.AssertXcodeVersion (15, 0); using var tagCollection = CMTagCollection.CreateMutable (); - Assert.AreEqual (CMTagCollectionError.Success, tagCollection.Add (CMTag.MediaTypeAudio), "Add 1"); - Assert.AreEqual (CMTagCollectionError.Success, tagCollection.Add (CMTag.MediaTypeAudio), "Add 2"); - Assert.AreEqual (1, (int) tagCollection.Count, "Count"); + Assert.That (tagCollection.Add (CMTag.MediaTypeAudio), Is.EqualTo (CMTagCollectionError.Success), "Add 1"); + Assert.That (tagCollection.Add (CMTag.MediaTypeAudio), Is.EqualTo (CMTagCollectionError.Success), "Add 2"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (1), "Count"); } [Test] @@ -499,7 +499,7 @@ public void RemoveTest () // Trying to modify a non-mutable collection using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo); - Assert.AreEqual (CMTagCollectionError.ParamErr, tagCollection.Remove (CMTag.MediaTypeAudio), "Remove"); + Assert.That (tagCollection.Remove (CMTag.MediaTypeAudio), Is.EqualTo (CMTagCollectionError.ParamErr), "Remove"); } [Test] @@ -508,11 +508,11 @@ public void RemoveMutableTest () TestRuntime.AssertXcodeVersion (15, 0); using var tagCollection = CMTagCollection.CreateMutable (); - Assert.AreEqual (CMTagCollectionError.TagNotFound, tagCollection.Remove (CMTag.MediaTypeAudio), "Remove 1"); - Assert.AreEqual (CMTagCollectionError.Success, tagCollection.Add (CMTag.MediaTypeAudio), "Add 1"); - Assert.AreEqual (CMTagCollectionError.Success, tagCollection.Remove (CMTag.MediaTypeAudio), "Remove 2"); - Assert.AreEqual (0, (int) tagCollection.Count, "Count"); - Assert.AreEqual (CMTagCollectionError.TagNotFound, tagCollection.Remove (CMTag.MediaTypeAudio), "Remove 3"); + Assert.That (tagCollection.Remove (CMTag.MediaTypeAudio), Is.EqualTo (CMTagCollectionError.TagNotFound), "Remove 1"); + Assert.That (tagCollection.Add (CMTag.MediaTypeAudio), Is.EqualTo (CMTagCollectionError.Success), "Add 1"); + Assert.That (tagCollection.Remove (CMTag.MediaTypeAudio), Is.EqualTo (CMTagCollectionError.Success), "Remove 2"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (0), "Count"); + Assert.That (tagCollection.Remove (CMTag.MediaTypeAudio), Is.EqualTo (CMTagCollectionError.TagNotFound), "Remove 3"); } [Test] @@ -522,7 +522,7 @@ public void RemoveAllTest () // Trying to modify a non-mutable collection using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo); - Assert.AreEqual (CMTagCollectionError.ParamErr, tagCollection.RemoveAllTags (), "Remove"); + Assert.That (tagCollection.RemoveAllTags (), Is.EqualTo (CMTagCollectionError.ParamErr), "Remove"); } [Test] @@ -531,10 +531,10 @@ public void RemoveAllMutableTest () TestRuntime.AssertXcodeVersion (15, 0); using var tagCollection = CMTagCollection.CreateMutable (); - Assert.AreEqual (CMTagCollectionError.Success, tagCollection.Add (CMTag.MediaTypeAudio), "Add 1"); - Assert.AreEqual (CMTagCollectionError.Success, tagCollection.Add (CMTag.MediaTypeVideo), "Add 2"); - Assert.AreEqual (CMTagCollectionError.Success, tagCollection.RemoveAllTags (), "RemoveAll"); - Assert.AreEqual (0, (int) tagCollection.Count, "Count"); + Assert.That (tagCollection.Add (CMTag.MediaTypeAudio), Is.EqualTo (CMTagCollectionError.Success), "Add 1"); + Assert.That (tagCollection.Add (CMTag.MediaTypeVideo), Is.EqualTo (CMTagCollectionError.Success), "Add 2"); + Assert.That (tagCollection.RemoveAllTags (), Is.EqualTo (CMTagCollectionError.Success), "RemoveAll"); + Assert.That ((int) tagCollection.Count, Is.EqualTo (0), "Count"); } [Test] @@ -546,7 +546,7 @@ public void AddCollection () using var tagCollection1 = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); using var tagCollection2 = CMTagCollection.Create (CMTag.MediaTypeAudio, CMTag.PackingTypeNone); Assert.Throws (() => tagCollection1.Add ((CMTagCollection) null), "Add null"); - Assert.AreEqual (CMTagCollectionError.ParamErr, tagCollection1.Add (tagCollection2), "Add"); + Assert.That (tagCollection1.Add (tagCollection2), Is.EqualTo (CMTagCollectionError.ParamErr), "Add"); } [Test] @@ -556,7 +556,7 @@ public void AddTags () using var tagCollection = CMTagCollection.Create (CMTag.MediaTypeVideo, CMTag.MediaTypeAudio); Assert.Throws (() => tagCollection.Add ((CMTag []) null), "Add null"); - Assert.AreEqual (CMTagCollectionError.ParamErr, tagCollection.Add (CMTag.MediaTypeAudio, CMTag.PackingTypeNone), "Add"); + Assert.That (tagCollection.Add (CMTag.MediaTypeAudio, CMTag.PackingTypeNone), Is.EqualTo (CMTagCollectionError.ParamErr), "Add"); } [Test] @@ -567,11 +567,11 @@ public void Dictionary () var roundTrip = new Action ((collection, message) => { var dict = collection.ToDictionary (); var deserializedCollection = CMTagCollection.Create (dict, out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, $"{message}: Status"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), $"{message}: Status"); // if the union of the original and deserialized collection has the same number of tags as the original collection, then the original and deserialized collections are identical. var union = collection.Union (deserializedCollection, out status); - Assert.AreEqual (CMTagCollectionError.Success, status, $"{message}: Status 2"); - Assert.AreEqual (collection.Count, union.Count, "Count"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), $"{message}: Status 2"); + Assert.That (union.Count, Is.EqualTo (collection.Count), "Count"); }); Assert.Multiple (() => { @@ -590,11 +590,11 @@ public void Data () var roundTrip = new Action ((collection, message) => { var data = collection.ToData (); var deserializedCollection = CMTagCollection.Create (data, out var status); - Assert.AreEqual (CMTagCollectionError.Success, status, $"{message}: Status"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), $"{message}: Status"); // if the union of the original and deserialized collection has the same number of tags as the original collection, then the original and deserialized collections are identical. var union = collection.Union (deserializedCollection, out status); - Assert.AreEqual (CMTagCollectionError.Success, status, $"{message}: Status 2"); - Assert.AreEqual (collection.Count, union.Count, "Count"); + Assert.That (status, Is.EqualTo (CMTagCollectionError.Success), $"{message}: Status 2"); + Assert.That (union.Count, Is.EqualTo (collection.Count), "Count"); }); Assert.Multiple (() => { diff --git a/tests/monotouch-test/CoreMedia/CMTagTests.cs b/tests/monotouch-test/CoreMedia/CMTagTests.cs index 916859abff9d..727c76d3fc24 100644 --- a/tests/monotouch-test/CoreMedia/CMTagTests.cs +++ b/tests/monotouch-test/CoreMedia/CMTagTests.cs @@ -73,58 +73,58 @@ public void Equals () TestRuntime.AssertXcodeVersion (15, 0); Assert.Multiple (() => { - Assert.AreEqual (true, CMTag.Equals (default (CMTag), default (CMTag)), "Default"); - Assert.AreEqual (true, CMTag.Equals (CMTag.Invalid, CMTag.Invalid), "Invalid"); - Assert.AreEqual (true, CMTag.Equals (CMTag.MediaTypeVideo, CMTag.MediaTypeVideo), "MediaTypeVideo"); - Assert.AreEqual (true, CMTag.Equals (CMTag.MediaSubTypeMebx, CMTag.MediaSubTypeMebx), "MediaSubTypeMebx"); - Assert.AreEqual (true, CMTag.Equals (CMTag.MediaTypeAudio, CMTag.MediaTypeAudio), "MediaTypeAudio"); - Assert.AreEqual (true, CMTag.Equals (CMTag.MediaTypeMetadata, CMTag.MediaTypeMetadata), "MediaTypeMetadata"); - Assert.AreEqual (true, CMTag.Equals (CMTag.StereoLeftEye, CMTag.StereoLeftEye), "StereoLeftEye"); - Assert.AreEqual (true, CMTag.Equals (CMTag.StereoRightEye, CMTag.StereoRightEye), "StereoRightEye"); - Assert.AreEqual (true, CMTag.Equals (CMTag.StereoLeftAndRightEye, CMTag.StereoLeftAndRightEye), "StereoLeftAndRightEye"); - Assert.AreEqual (true, CMTag.Equals (CMTag.StereoNone, CMTag.StereoNone), "StereoNone"); - Assert.AreEqual (true, CMTag.Equals (CMTag.StereoInterpretationOrderReversed, CMTag.StereoInterpretationOrderReversed), "StereoInterpretationOrderReversed"); - Assert.AreEqual (true, CMTag.Equals (CMTag.ProjectionTypeRectangular, CMTag.ProjectionTypeRectangular), "ProjectionTypeRectangular"); - Assert.AreEqual (true, CMTag.Equals (CMTag.ProjectionTypeEquirectangular, CMTag.ProjectionTypeEquirectangular), "ProjectionTypeEquirectangular"); - Assert.AreEqual (true, CMTag.Equals (CMTag.ProjectionTypeHalfEquirectangular, CMTag.ProjectionTypeHalfEquirectangular), "ProjectionTypeHalfEquirectangular"); - Assert.AreEqual (true, CMTag.Equals (CMTag.ProjectionTypeFisheye, CMTag.ProjectionTypeFisheye), "ProjectionTypeFisheye"); - Assert.AreEqual (true, CMTag.Equals (CMTag.PackingTypeNone, CMTag.PackingTypeNone), "PackingTypeNone"); - Assert.AreEqual (true, CMTag.Equals (CMTag.PackingTypeSideBySide, CMTag.PackingTypeSideBySide), "PackingTypeSideBySide"); - Assert.AreEqual (true, CMTag.Equals (CMTag.PackingTypeOverUnder, CMTag.PackingTypeOverUnder), "PackingTypeOverUnder"); - - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.MediaTypeVideo), "Invalid vs MediaTypeVideo"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.MediaSubTypeMebx), "Invalid vs MediaSubTypeMebx"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.MediaTypeAudio), "Invalid vs MediaTypeAudio"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.MediaTypeMetadata), "Invalid vs MediaTypeMetadata"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.StereoLeftEye), "Invalid vs StereoLeftEye"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.StereoRightEye), "Invalid vs StereoRightEye"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.StereoLeftAndRightEye), "Invalid vs StereoLeftAndRightEye"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.StereoNone), "Invalid vs StereoNone"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.StereoInterpretationOrderReversed), "Invalid vs StereoInterpretationOrderReversed"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.ProjectionTypeRectangular), "Invalid vs ProjectionTypeRectangular"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.ProjectionTypeEquirectangular), "Invalid vs ProjectionTypeEquirectangular"); - Assert.AreEqual (!TestRuntime.CheckXcodeVersion (16, 0), CMTag.Equals (CMTag.Invalid, CMTag.ProjectionTypeHalfEquirectangular), "Invalid vs ProjectionTypeHalfEquirectangular"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.ProjectionTypeFisheye), "Invalid vs ProjectionTypeFisheye"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.PackingTypeNone), "Invalid vs PackingTypeNone"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.PackingTypeSideBySide), "Invalid vs PackingTypeSideBySide"); - Assert.AreEqual (false, CMTag.Equals (CMTag.Invalid, CMTag.PackingTypeOverUnder), "Invalid vs PackingTypeOverUnder"); - - Assert.AreEqual (false, CMTag.Equals (CMTag.MediaTypeVideo, CMTag.Invalid), "MediaTypeVideo vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.MediaSubTypeMebx, CMTag.Invalid), "MediaSubTypeMebx vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.MediaTypeAudio, CMTag.Invalid), "MediaTypeAudio vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.MediaTypeMetadata, CMTag.Invalid), "MediaTypeMetadata vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.StereoLeftEye, CMTag.Invalid), "StereoLeftEye vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.StereoRightEye, CMTag.Invalid), "StereoRightEye vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.StereoLeftAndRightEye, CMTag.Invalid), "StereoLeftAndRightEye vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.StereoNone, CMTag.Invalid), "StereoNone vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.StereoInterpretationOrderReversed, CMTag.Invalid), "StereoInterpretationOrderReversed vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.ProjectionTypeRectangular, CMTag.Invalid), "ProjectionTypeRectangular vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.ProjectionTypeEquirectangular, CMTag.Invalid), "ProjectionTypeEquirectangular vs Invalid"); - Assert.AreEqual (!TestRuntime.CheckXcodeVersion (16, 0), CMTag.Equals (CMTag.ProjectionTypeHalfEquirectangular, CMTag.Invalid), "ProjectionTypeHalfEquirectangular vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.ProjectionTypeFisheye, CMTag.Invalid), "ProjectionTypeFisheye vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.PackingTypeNone, CMTag.Invalid), "PackingTypeNone vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.PackingTypeSideBySide, CMTag.Invalid), "PackingTypeSideBySide vs Invalid"); - Assert.AreEqual (false, CMTag.Equals (CMTag.PackingTypeOverUnder, CMTag.Invalid), "PackingTypeOverUnder vs Invalid"); + Assert.That (CMTag.Equals (default (CMTag), default (CMTag)), Is.EqualTo (true), "Default"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.Invalid), Is.EqualTo (true), "Invalid"); + Assert.That (CMTag.Equals (CMTag.MediaTypeVideo, CMTag.MediaTypeVideo), Is.EqualTo (true), "MediaTypeVideo"); + Assert.That (CMTag.Equals (CMTag.MediaSubTypeMebx, CMTag.MediaSubTypeMebx), Is.EqualTo (true), "MediaSubTypeMebx"); + Assert.That (CMTag.Equals (CMTag.MediaTypeAudio, CMTag.MediaTypeAudio), Is.EqualTo (true), "MediaTypeAudio"); + Assert.That (CMTag.Equals (CMTag.MediaTypeMetadata, CMTag.MediaTypeMetadata), Is.EqualTo (true), "MediaTypeMetadata"); + Assert.That (CMTag.Equals (CMTag.StereoLeftEye, CMTag.StereoLeftEye), Is.EqualTo (true), "StereoLeftEye"); + Assert.That (CMTag.Equals (CMTag.StereoRightEye, CMTag.StereoRightEye), Is.EqualTo (true), "StereoRightEye"); + Assert.That (CMTag.Equals (CMTag.StereoLeftAndRightEye, CMTag.StereoLeftAndRightEye), Is.EqualTo (true), "StereoLeftAndRightEye"); + Assert.That (CMTag.Equals (CMTag.StereoNone, CMTag.StereoNone), Is.EqualTo (true), "StereoNone"); + Assert.That (CMTag.Equals (CMTag.StereoInterpretationOrderReversed, CMTag.StereoInterpretationOrderReversed), Is.EqualTo (true), "StereoInterpretationOrderReversed"); + Assert.That (CMTag.Equals (CMTag.ProjectionTypeRectangular, CMTag.ProjectionTypeRectangular), Is.EqualTo (true), "ProjectionTypeRectangular"); + Assert.That (CMTag.Equals (CMTag.ProjectionTypeEquirectangular, CMTag.ProjectionTypeEquirectangular), Is.EqualTo (true), "ProjectionTypeEquirectangular"); + Assert.That (CMTag.Equals (CMTag.ProjectionTypeHalfEquirectangular, CMTag.ProjectionTypeHalfEquirectangular), Is.EqualTo (true), "ProjectionTypeHalfEquirectangular"); + Assert.That (CMTag.Equals (CMTag.ProjectionTypeFisheye, CMTag.ProjectionTypeFisheye), Is.EqualTo (true), "ProjectionTypeFisheye"); + Assert.That (CMTag.Equals (CMTag.PackingTypeNone, CMTag.PackingTypeNone), Is.EqualTo (true), "PackingTypeNone"); + Assert.That (CMTag.Equals (CMTag.PackingTypeSideBySide, CMTag.PackingTypeSideBySide), Is.EqualTo (true), "PackingTypeSideBySide"); + Assert.That (CMTag.Equals (CMTag.PackingTypeOverUnder, CMTag.PackingTypeOverUnder), Is.EqualTo (true), "PackingTypeOverUnder"); + + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.MediaTypeVideo), Is.EqualTo (false), "Invalid vs MediaTypeVideo"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.MediaSubTypeMebx), Is.EqualTo (false), "Invalid vs MediaSubTypeMebx"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.MediaTypeAudio), Is.EqualTo (false), "Invalid vs MediaTypeAudio"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.MediaTypeMetadata), Is.EqualTo (false), "Invalid vs MediaTypeMetadata"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.StereoLeftEye), Is.EqualTo (false), "Invalid vs StereoLeftEye"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.StereoRightEye), Is.EqualTo (false), "Invalid vs StereoRightEye"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.StereoLeftAndRightEye), Is.EqualTo (false), "Invalid vs StereoLeftAndRightEye"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.StereoNone), Is.EqualTo (false), "Invalid vs StereoNone"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.StereoInterpretationOrderReversed), Is.EqualTo (false), "Invalid vs StereoInterpretationOrderReversed"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.ProjectionTypeRectangular), Is.EqualTo (false), "Invalid vs ProjectionTypeRectangular"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.ProjectionTypeEquirectangular), Is.EqualTo (false), "Invalid vs ProjectionTypeEquirectangular"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.ProjectionTypeHalfEquirectangular), Is.EqualTo (!TestRuntime.CheckXcodeVersion (16, 0)), "Invalid vs ProjectionTypeHalfEquirectangular"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.ProjectionTypeFisheye), Is.EqualTo (false), "Invalid vs ProjectionTypeFisheye"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.PackingTypeNone), Is.EqualTo (false), "Invalid vs PackingTypeNone"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.PackingTypeSideBySide), Is.EqualTo (false), "Invalid vs PackingTypeSideBySide"); + Assert.That (CMTag.Equals (CMTag.Invalid, CMTag.PackingTypeOverUnder), Is.EqualTo (false), "Invalid vs PackingTypeOverUnder"); + + Assert.That (CMTag.Equals (CMTag.MediaTypeVideo, CMTag.Invalid), Is.EqualTo (false), "MediaTypeVideo vs Invalid"); + Assert.That (CMTag.Equals (CMTag.MediaSubTypeMebx, CMTag.Invalid), Is.EqualTo (false), "MediaSubTypeMebx vs Invalid"); + Assert.That (CMTag.Equals (CMTag.MediaTypeAudio, CMTag.Invalid), Is.EqualTo (false), "MediaTypeAudio vs Invalid"); + Assert.That (CMTag.Equals (CMTag.MediaTypeMetadata, CMTag.Invalid), Is.EqualTo (false), "MediaTypeMetadata vs Invalid"); + Assert.That (CMTag.Equals (CMTag.StereoLeftEye, CMTag.Invalid), Is.EqualTo (false), "StereoLeftEye vs Invalid"); + Assert.That (CMTag.Equals (CMTag.StereoRightEye, CMTag.Invalid), Is.EqualTo (false), "StereoRightEye vs Invalid"); + Assert.That (CMTag.Equals (CMTag.StereoLeftAndRightEye, CMTag.Invalid), Is.EqualTo (false), "StereoLeftAndRightEye vs Invalid"); + Assert.That (CMTag.Equals (CMTag.StereoNone, CMTag.Invalid), Is.EqualTo (false), "StereoNone vs Invalid"); + Assert.That (CMTag.Equals (CMTag.StereoInterpretationOrderReversed, CMTag.Invalid), Is.EqualTo (false), "StereoInterpretationOrderReversed vs Invalid"); + Assert.That (CMTag.Equals (CMTag.ProjectionTypeRectangular, CMTag.Invalid), Is.EqualTo (false), "ProjectionTypeRectangular vs Invalid"); + Assert.That (CMTag.Equals (CMTag.ProjectionTypeEquirectangular, CMTag.Invalid), Is.EqualTo (false), "ProjectionTypeEquirectangular vs Invalid"); + Assert.That (CMTag.Equals (CMTag.ProjectionTypeHalfEquirectangular, CMTag.Invalid), Is.EqualTo (!TestRuntime.CheckXcodeVersion (16, 0)), "ProjectionTypeHalfEquirectangular vs Invalid"); + Assert.That (CMTag.Equals (CMTag.ProjectionTypeFisheye, CMTag.Invalid), Is.EqualTo (false), "ProjectionTypeFisheye vs Invalid"); + Assert.That (CMTag.Equals (CMTag.PackingTypeNone, CMTag.Invalid), Is.EqualTo (false), "PackingTypeNone vs Invalid"); + Assert.That (CMTag.Equals (CMTag.PackingTypeSideBySide, CMTag.Invalid), Is.EqualTo (false), "PackingTypeSideBySide vs Invalid"); + Assert.That (CMTag.Equals (CMTag.PackingTypeOverUnder, CMTag.Invalid), Is.EqualTo (false), "PackingTypeOverUnder vs Invalid"); }); } @@ -134,87 +134,87 @@ public void Compare () TestRuntime.AssertXcodeVersion (15, 0); Assert.Multiple (() => { - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (default (CMTag), default (CMTag)), "Default"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.Invalid, CMTag.Invalid), "Invalid"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.MediaTypeVideo, CMTag.MediaTypeVideo), "MediaTypeVideo"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.MediaSubTypeMebx, CMTag.MediaSubTypeMebx), "MediaSubTypeMebx"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.MediaTypeAudio, CMTag.MediaTypeAudio), "MediaTypeAudio"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.MediaTypeMetadata, CMTag.MediaTypeMetadata), "MediaTypeMetadata"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.StereoLeftEye, CMTag.StereoLeftEye), "StereoLeftEye"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.StereoRightEye, CMTag.StereoRightEye), "StereoRightEye"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.StereoLeftAndRightEye, CMTag.StereoLeftAndRightEye), "StereoLeftAndRightEye"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.StereoNone, CMTag.StereoNone), "StereoNone"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.StereoInterpretationOrderReversed, CMTag.StereoInterpretationOrderReversed), "StereoInterpretationOrderReversed"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.ProjectionTypeRectangular, CMTag.ProjectionTypeRectangular), "ProjectionTypeRectangular"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.ProjectionTypeEquirectangular, CMTag.ProjectionTypeEquirectangular), "ProjectionTypeEquirectangular"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.ProjectionTypeHalfEquirectangular, CMTag.ProjectionTypeHalfEquirectangular), "ProjectionTypeHalfEquirectangular"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.ProjectionTypeFisheye, CMTag.ProjectionTypeFisheye), "ProjectionTypeFisheye"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.PackingTypeNone, CMTag.PackingTypeNone), "PackingTypeNone"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.PackingTypeSideBySide, CMTag.PackingTypeSideBySide), "PackingTypeSideBySide"); - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.PackingTypeOverUnder, CMTag.PackingTypeOverUnder), "PackingTypeOverUnder"); - - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.MediaTypeVideo), "Invalid vs MediaTypeVideo"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.MediaSubTypeMebx), "Invalid vs MediaSubTypeMebx"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.MediaTypeAudio), "Invalid vs MediaTypeAudio"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.MediaTypeMetadata), "Invalid vs MediaTypeMetadata"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.StereoLeftEye), "Invalid vs StereoLeftEye"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.StereoRightEye), "Invalid vs StereoRightEye"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.StereoLeftAndRightEye), "Invalid vs StereoLeftAndRightEye"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.StereoNone), "Invalid vs StereoNone"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.StereoInterpretationOrderReversed), "Invalid vs StereoInterpretationOrderReversed"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.ProjectionTypeRectangular), "Invalid vs ProjectionTypeRectangular"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.ProjectionTypeEquirectangular), "Invalid vs ProjectionTypeEquirectangular"); + Assert.That (CMTag.Compare (default (CMTag), default (CMTag)), Is.EqualTo (CFComparisonResult.EqualTo), "Default"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.Invalid), Is.EqualTo (CFComparisonResult.EqualTo), "Invalid"); + Assert.That (CMTag.Compare (CMTag.MediaTypeVideo, CMTag.MediaTypeVideo), Is.EqualTo (CFComparisonResult.EqualTo), "MediaTypeVideo"); + Assert.That (CMTag.Compare (CMTag.MediaSubTypeMebx, CMTag.MediaSubTypeMebx), Is.EqualTo (CFComparisonResult.EqualTo), "MediaSubTypeMebx"); + Assert.That (CMTag.Compare (CMTag.MediaTypeAudio, CMTag.MediaTypeAudio), Is.EqualTo (CFComparisonResult.EqualTo), "MediaTypeAudio"); + Assert.That (CMTag.Compare (CMTag.MediaTypeMetadata, CMTag.MediaTypeMetadata), Is.EqualTo (CFComparisonResult.EqualTo), "MediaTypeMetadata"); + Assert.That (CMTag.Compare (CMTag.StereoLeftEye, CMTag.StereoLeftEye), Is.EqualTo (CFComparisonResult.EqualTo), "StereoLeftEye"); + Assert.That (CMTag.Compare (CMTag.StereoRightEye, CMTag.StereoRightEye), Is.EqualTo (CFComparisonResult.EqualTo), "StereoRightEye"); + Assert.That (CMTag.Compare (CMTag.StereoLeftAndRightEye, CMTag.StereoLeftAndRightEye), Is.EqualTo (CFComparisonResult.EqualTo), "StereoLeftAndRightEye"); + Assert.That (CMTag.Compare (CMTag.StereoNone, CMTag.StereoNone), Is.EqualTo (CFComparisonResult.EqualTo), "StereoNone"); + Assert.That (CMTag.Compare (CMTag.StereoInterpretationOrderReversed, CMTag.StereoInterpretationOrderReversed), Is.EqualTo (CFComparisonResult.EqualTo), "StereoInterpretationOrderReversed"); + Assert.That (CMTag.Compare (CMTag.ProjectionTypeRectangular, CMTag.ProjectionTypeRectangular), Is.EqualTo (CFComparisonResult.EqualTo), "ProjectionTypeRectangular"); + Assert.That (CMTag.Compare (CMTag.ProjectionTypeEquirectangular, CMTag.ProjectionTypeEquirectangular), Is.EqualTo (CFComparisonResult.EqualTo), "ProjectionTypeEquirectangular"); + Assert.That (CMTag.Compare (CMTag.ProjectionTypeHalfEquirectangular, CMTag.ProjectionTypeHalfEquirectangular), Is.EqualTo (CFComparisonResult.EqualTo), "ProjectionTypeHalfEquirectangular"); + Assert.That (CMTag.Compare (CMTag.ProjectionTypeFisheye, CMTag.ProjectionTypeFisheye), Is.EqualTo (CFComparisonResult.EqualTo), "ProjectionTypeFisheye"); + Assert.That (CMTag.Compare (CMTag.PackingTypeNone, CMTag.PackingTypeNone), Is.EqualTo (CFComparisonResult.EqualTo), "PackingTypeNone"); + Assert.That (CMTag.Compare (CMTag.PackingTypeSideBySide, CMTag.PackingTypeSideBySide), Is.EqualTo (CFComparisonResult.EqualTo), "PackingTypeSideBySide"); + Assert.That (CMTag.Compare (CMTag.PackingTypeOverUnder, CMTag.PackingTypeOverUnder), Is.EqualTo (CFComparisonResult.EqualTo), "PackingTypeOverUnder"); + + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.MediaTypeVideo), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs MediaTypeVideo"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.MediaSubTypeMebx), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs MediaSubTypeMebx"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.MediaTypeAudio), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs MediaTypeAudio"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.MediaTypeMetadata), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs MediaTypeMetadata"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.StereoLeftEye), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs StereoLeftEye"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.StereoRightEye), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs StereoRightEye"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.StereoLeftAndRightEye), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs StereoLeftAndRightEye"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.StereoNone), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs StereoNone"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.StereoInterpretationOrderReversed), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs StereoInterpretationOrderReversed"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.ProjectionTypeRectangular), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs ProjectionTypeRectangular"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.ProjectionTypeEquirectangular), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs ProjectionTypeEquirectangular"); if (TestRuntime.CheckXcodeVersion (16, 0)) { - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.ProjectionTypeHalfEquirectangular), "Invalid vs ProjectionTypeHalfEquirectangular"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.ProjectionTypeHalfEquirectangular), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs ProjectionTypeHalfEquirectangular"); } else { - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.Invalid, CMTag.ProjectionTypeHalfEquirectangular), "Invalid vs ProjectionTypeHalfEquirectangular"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.ProjectionTypeHalfEquirectangular), Is.EqualTo (CFComparisonResult.EqualTo), "Invalid vs ProjectionTypeHalfEquirectangular"); } - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.ProjectionTypeFisheye), "Invalid vs ProjectionTypeFisheye"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.PackingTypeNone), "Invalid vs PackingTypeNone"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.PackingTypeSideBySide), "Invalid vs PackingTypeSideBySide"); - Assert.AreEqual (CFComparisonResult.LessThan, CMTag.Compare (CMTag.Invalid, CMTag.PackingTypeOverUnder), "Invalid vs PackingTypeOverUnder"); - - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.MediaTypeVideo, CMTag.Invalid), "MediaTypeVideo vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.MediaSubTypeMebx, CMTag.Invalid), "MediaSubTypeMebx vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.MediaTypeAudio, CMTag.Invalid), "MediaTypeAudio vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.MediaTypeMetadata, CMTag.Invalid), "MediaTypeMetadata vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.StereoLeftEye, CMTag.Invalid), "StereoLeftEye vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.StereoRightEye, CMTag.Invalid), "StereoRightEye vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.StereoLeftAndRightEye, CMTag.Invalid), "StereoLeftAndRightEye vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.StereoNone, CMTag.Invalid), "StereoNone vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.StereoInterpretationOrderReversed, CMTag.Invalid), "StereoInterpretationOrderReversed vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.ProjectionTypeRectangular, CMTag.Invalid), "ProjectionTypeRectangular vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.ProjectionTypeEquirectangular, CMTag.Invalid), "ProjectionTypeEquirectangular vs Invalid"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.ProjectionTypeFisheye), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs ProjectionTypeFisheye"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.PackingTypeNone), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs PackingTypeNone"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.PackingTypeSideBySide), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs PackingTypeSideBySide"); + Assert.That (CMTag.Compare (CMTag.Invalid, CMTag.PackingTypeOverUnder), Is.EqualTo (CFComparisonResult.LessThan), "Invalid vs PackingTypeOverUnder"); + + Assert.That (CMTag.Compare (CMTag.MediaTypeVideo, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "MediaTypeVideo vs Invalid"); + Assert.That (CMTag.Compare (CMTag.MediaSubTypeMebx, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "MediaSubTypeMebx vs Invalid"); + Assert.That (CMTag.Compare (CMTag.MediaTypeAudio, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "MediaTypeAudio vs Invalid"); + Assert.That (CMTag.Compare (CMTag.MediaTypeMetadata, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "MediaTypeMetadata vs Invalid"); + Assert.That (CMTag.Compare (CMTag.StereoLeftEye, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "StereoLeftEye vs Invalid"); + Assert.That (CMTag.Compare (CMTag.StereoRightEye, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "StereoRightEye vs Invalid"); + Assert.That (CMTag.Compare (CMTag.StereoLeftAndRightEye, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "StereoLeftAndRightEye vs Invalid"); + Assert.That (CMTag.Compare (CMTag.StereoNone, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "StereoNone vs Invalid"); + Assert.That (CMTag.Compare (CMTag.StereoInterpretationOrderReversed, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "StereoInterpretationOrderReversed vs Invalid"); + Assert.That (CMTag.Compare (CMTag.ProjectionTypeRectangular, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "ProjectionTypeRectangular vs Invalid"); + Assert.That (CMTag.Compare (CMTag.ProjectionTypeEquirectangular, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "ProjectionTypeEquirectangular vs Invalid"); if (TestRuntime.CheckXcodeVersion (16, 0)) { - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.ProjectionTypeHalfEquirectangular, CMTag.Invalid), "ProjectionTypeHalfEquirectangular vs Invalid"); + Assert.That (CMTag.Compare (CMTag.ProjectionTypeHalfEquirectangular, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "ProjectionTypeHalfEquirectangular vs Invalid"); } else { - Assert.AreEqual (CFComparisonResult.EqualTo, CMTag.Compare (CMTag.ProjectionTypeHalfEquirectangular, CMTag.Invalid), "ProjectionTypeHalfEquirectangular vs Invalid"); + Assert.That (CMTag.Compare (CMTag.ProjectionTypeHalfEquirectangular, CMTag.Invalid), Is.EqualTo (CFComparisonResult.EqualTo), "ProjectionTypeHalfEquirectangular vs Invalid"); } - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.ProjectionTypeFisheye, CMTag.Invalid), "ProjectionTypeFisheye vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.PackingTypeNone, CMTag.Invalid), "PackingTypeNone vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.PackingTypeSideBySide, CMTag.Invalid), "PackingTypeSideBySide vs Invalid"); - Assert.AreEqual (CFComparisonResult.GreaterThan, CMTag.Compare (CMTag.PackingTypeOverUnder, CMTag.Invalid), "PackingTypeOverUnder vs Invalid"); + Assert.That (CMTag.Compare (CMTag.ProjectionTypeFisheye, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "ProjectionTypeFisheye vs Invalid"); + Assert.That (CMTag.Compare (CMTag.PackingTypeNone, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "PackingTypeNone vs Invalid"); + Assert.That (CMTag.Compare (CMTag.PackingTypeSideBySide, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "PackingTypeSideBySide vs Invalid"); + Assert.That (CMTag.Compare (CMTag.PackingTypeOverUnder, CMTag.Invalid), Is.EqualTo (CFComparisonResult.GreaterThan), "PackingTypeOverUnder vs Invalid"); }); } void AssertTag (CMTag tag, CMTagCategory category, CMTagDataType dataType, ulong value, bool isValid, bool hasFloat64Value, double float64Value, bool hasOSTypeValue, uint osTypeValue, bool hasFlagsValue, ulong flagsValue, bool hasInt64Value, long int64Value, string message) { - Assert.AreEqual (category, tag.Category, $"{message}: Category"); - Assert.AreEqual (dataType, tag.DataType, $"{message}: DataType"); - Assert.AreEqual (value, tag.Value, $"{message}: Value"); - Assert.AreEqual (isValid, tag.IsValid, $"{message}: IsValid"); - Assert.AreEqual (hasFloat64Value, tag.HasFloat64Value, $"{message}: HasFloat64Value"); + Assert.That (tag.Category, Is.EqualTo (category), $"{message}: Category"); + Assert.That (tag.DataType, Is.EqualTo (dataType), $"{message}: DataType"); + Assert.That (tag.Value, Is.EqualTo (value), $"{message}: Value"); + Assert.That (tag.IsValid, Is.EqualTo (isValid), $"{message}: IsValid"); + Assert.That (tag.HasFloat64Value, Is.EqualTo (hasFloat64Value), $"{message}: HasFloat64Value"); if (hasFloat64Value) - Assert.AreEqual (float64Value, tag.Float64Value, $"{message}: Float64Value"); - Assert.AreEqual (hasOSTypeValue, tag.HasOSTypeValue, $"{message}: HasOSTypeValue"); + Assert.That (tag.Float64Value, Is.EqualTo (float64Value), $"{message}: Float64Value"); + Assert.That (tag.HasOSTypeValue, Is.EqualTo (hasOSTypeValue), $"{message}: HasOSTypeValue"); if (hasOSTypeValue) - Assert.AreEqual (osTypeValue, tag.OSTypeValue, $"{message}: OSTypeValue ({AVFoundationEnumTest.FourCC (osTypeValue)}={osTypeValue} vs {AVFoundationEnumTest.FourCC (tag.OSTypeValue)}={tag.OSTypeValue})"); - Assert.AreEqual (hasFlagsValue, tag.HasFlagsValue, $"{message}: HasFlagsValue"); + Assert.That (tag.OSTypeValue, Is.EqualTo (osTypeValue), $"{message}: OSTypeValue ({AVFoundationEnumTest.FourCC (osTypeValue)}={osTypeValue} vs {AVFoundationEnumTest.FourCC (tag.OSTypeValue)}={tag.OSTypeValue})"); + Assert.That (tag.HasFlagsValue, Is.EqualTo (hasFlagsValue), $"{message}: HasFlagsValue"); if (hasFlagsValue) - Assert.AreEqual (flagsValue, tag.FlagsValue, $"{message}: FlagsValue"); - Assert.AreEqual (hasInt64Value, tag.HasInt64Value, $"{message}: HasInt64Value"); + Assert.That (tag.FlagsValue, Is.EqualTo (flagsValue), $"{message}: FlagsValue"); + Assert.That (tag.HasInt64Value, Is.EqualTo (hasInt64Value), $"{message}: HasInt64Value"); if (hasInt64Value) - Assert.AreEqual (int64Value, tag.Int64Value, $"{message}: Int64Value"); + Assert.That (tag.Int64Value, Is.EqualTo (int64Value), $"{message}: Int64Value"); } [Test] @@ -253,28 +253,28 @@ public void ToStringTests () TestRuntime.AssertXcodeVersion (15, 0); Assert.Multiple (() => { - Assert.AreEqual ("{category:''{INVALID}", default (CMTag).ToString (), "Default"); - Assert.AreEqual ("{category:''{INVALID}", CMTag.Invalid.ToString (), "Invalid"); - Assert.AreEqual ("{category:'mdia' value:'vide' }", CMTag.MediaTypeVideo.ToString (), "MediaTypeVideo"); - Assert.AreEqual ("{category:'msub' value:'mebx' }", CMTag.MediaSubTypeMebx.ToString (), "MediaSubTypeMebx"); - Assert.AreEqual ("{category:'mdia' value:'soun' }", CMTag.MediaTypeAudio.ToString (), "MediaTypeAudio"); - Assert.AreEqual ("{category:'mdia' value:'meta' }", CMTag.MediaTypeMetadata.ToString (), "MediaTypeMetadata"); - Assert.AreEqual ("{category:'eyes' value:0x1 }", CMTag.StereoLeftEye.ToString (), "StereoLeftEye"); - Assert.AreEqual ("{category:'eyes' value:0x2 }", CMTag.StereoRightEye.ToString (), "StereoRightEye"); - Assert.AreEqual ("{category:'eyes' value:0x3 }", CMTag.StereoLeftAndRightEye.ToString (), "StereoLeftAndRightEye"); - Assert.AreEqual ("{category:'eyes' value:0x0 }", CMTag.StereoNone.ToString (), "StereoNone"); - Assert.AreEqual ("{category:'eyip' value:0x1 }", CMTag.StereoInterpretationOrderReversed.ToString (), "StereoInterpretationOrderReversed"); - Assert.AreEqual ("{category:'proj' value:'rect' }", CMTag.ProjectionTypeRectangular.ToString (), "ProjectionTypeRectangular"); - Assert.AreEqual ("{category:'proj' value:'equi' }", CMTag.ProjectionTypeEquirectangular.ToString (), "ProjectionTypeEquirectangular"); + Assert.That (default (CMTag).ToString (), Is.EqualTo ("{category:''{INVALID}"), "Default"); + Assert.That (CMTag.Invalid.ToString (), Is.EqualTo ("{category:''{INVALID}"), "Invalid"); + Assert.That (CMTag.MediaTypeVideo.ToString (), Is.EqualTo ("{category:'mdia' value:'vide' }"), "MediaTypeVideo"); + Assert.That (CMTag.MediaSubTypeMebx.ToString (), Is.EqualTo ("{category:'msub' value:'mebx' }"), "MediaSubTypeMebx"); + Assert.That (CMTag.MediaTypeAudio.ToString (), Is.EqualTo ("{category:'mdia' value:'soun' }"), "MediaTypeAudio"); + Assert.That (CMTag.MediaTypeMetadata.ToString (), Is.EqualTo ("{category:'mdia' value:'meta' }"), "MediaTypeMetadata"); + Assert.That (CMTag.StereoLeftEye.ToString (), Is.EqualTo ("{category:'eyes' value:0x1 }"), "StereoLeftEye"); + Assert.That (CMTag.StereoRightEye.ToString (), Is.EqualTo ("{category:'eyes' value:0x2 }"), "StereoRightEye"); + Assert.That (CMTag.StereoLeftAndRightEye.ToString (), Is.EqualTo ("{category:'eyes' value:0x3 }"), "StereoLeftAndRightEye"); + Assert.That (CMTag.StereoNone.ToString (), Is.EqualTo ("{category:'eyes' value:0x0 }"), "StereoNone"); + Assert.That (CMTag.StereoInterpretationOrderReversed.ToString (), Is.EqualTo ("{category:'eyip' value:0x1 }"), "StereoInterpretationOrderReversed"); + Assert.That (CMTag.ProjectionTypeRectangular.ToString (), Is.EqualTo ("{category:'proj' value:'rect' }"), "ProjectionTypeRectangular"); + Assert.That (CMTag.ProjectionTypeEquirectangular.ToString (), Is.EqualTo ("{category:'proj' value:'equi' }"), "ProjectionTypeEquirectangular"); if (TestRuntime.CheckXcodeVersion (16, 0)) { - Assert.AreEqual ("{category:'proj' value:'hequ' }", CMTag.ProjectionTypeHalfEquirectangular.ToString (), "ProjectionTypeHalfEquirectangular"); + Assert.That (CMTag.ProjectionTypeHalfEquirectangular.ToString (), Is.EqualTo ("{category:'proj' value:'hequ' }"), "ProjectionTypeHalfEquirectangular"); } else { - Assert.AreEqual ("{category:''{INVALID}", CMTag.ProjectionTypeHalfEquirectangular.ToString (), "ProjectionTypeHalfEquirectangular"); + Assert.That (CMTag.ProjectionTypeHalfEquirectangular.ToString (), Is.EqualTo ("{category:''{INVALID}"), "ProjectionTypeHalfEquirectangular"); } - Assert.AreEqual ("{category:'proj' value:'fish' }", CMTag.ProjectionTypeFisheye.ToString (), "ProjectionTypeFisheye"); - Assert.AreEqual ("{category:'pack' value:'none' }", CMTag.PackingTypeNone.ToString (), "PackingTypeNone"); - Assert.AreEqual ("{category:'pack' value:'side' }", CMTag.PackingTypeSideBySide.ToString (), "PackingTypeSideBySide"); - Assert.AreEqual ("{category:'pack' value:'over' }", CMTag.PackingTypeOverUnder.ToString (), "PackingTypeOverUnder"); + Assert.That (CMTag.ProjectionTypeFisheye.ToString (), Is.EqualTo ("{category:'proj' value:'fish' }"), "ProjectionTypeFisheye"); + Assert.That (CMTag.PackingTypeNone.ToString (), Is.EqualTo ("{category:'pack' value:'none' }"), "PackingTypeNone"); + Assert.That (CMTag.PackingTypeSideBySide.ToString (), Is.EqualTo ("{category:'pack' value:'side' }"), "PackingTypeSideBySide"); + Assert.That (CMTag.PackingTypeOverUnder.ToString (), Is.EqualTo ("{category:'pack' value:'over' }"), "PackingTypeOverUnder"); }); } @@ -286,7 +286,7 @@ public void Dictionary () var roundTrip = new Action ((tag, message) => { var dict = tag.ToDictionary (); var deserializedTag = CMTag.Create (dict); - Assert.AreEqual (true, CMTag.Equals (tag, deserializedTag), message); + Assert.That (CMTag.Equals (tag, deserializedTag), Is.EqualTo (true), message); }); Assert.Multiple (() => { @@ -317,24 +317,24 @@ public void Hash () TestRuntime.AssertXcodeVersion (15, 0); Assert.Multiple (() => { - Assert.AreNotEqual (0, default (CMTag).GetHashCode (), "Default"); - Assert.AreNotEqual (0, CMTag.Invalid.GetHashCode (), "Invalid"); - Assert.AreNotEqual (0, CMTag.MediaTypeVideo.GetHashCode (), "MediaTypeVideo"); - Assert.AreNotEqual (0, CMTag.MediaSubTypeMebx.GetHashCode (), "MediaSubTypeMebx"); - Assert.AreNotEqual (0, CMTag.MediaTypeAudio.GetHashCode (), "MediaTypeAudio"); - Assert.AreNotEqual (0, CMTag.MediaTypeMetadata.GetHashCode (), "MediaTypeMetadata"); - Assert.AreNotEqual (0, CMTag.StereoLeftEye.GetHashCode (), "StereoLeftEye"); - Assert.AreNotEqual (0, CMTag.StereoRightEye.GetHashCode (), "StereoRightEye"); - Assert.AreNotEqual (0, CMTag.StereoLeftAndRightEye.GetHashCode (), "StereoLeftAndRightEye"); - Assert.AreNotEqual (0, CMTag.StereoNone.GetHashCode (), "StereoNone"); - Assert.AreNotEqual (0, CMTag.StereoInterpretationOrderReversed.GetHashCode (), "StereoInterpretationOrderReversed"); - Assert.AreNotEqual (0, CMTag.ProjectionTypeRectangular.GetHashCode (), "ProjectionTypeRectangular"); - Assert.AreNotEqual (0, CMTag.ProjectionTypeEquirectangular.GetHashCode (), "ProjectionTypeEquirectangular"); - Assert.AreNotEqual (0, CMTag.ProjectionTypeHalfEquirectangular.GetHashCode (), "ProjectionTypeHalfEquirectangular"); - Assert.AreNotEqual (0, CMTag.ProjectionTypeFisheye.GetHashCode (), "ProjectionTypeFisheye"); - Assert.AreNotEqual (0, CMTag.PackingTypeNone.GetHashCode (), "PackingTypeNone"); - Assert.AreNotEqual (0, CMTag.PackingTypeSideBySide.GetHashCode (), "PackingTypeSideBySide"); - Assert.AreNotEqual (0, CMTag.PackingTypeOverUnder.GetHashCode (), "PackingTypeOverUnder"); + Assert.That (default (CMTag).GetHashCode (), Is.Not.EqualTo (0), "Default"); + Assert.That (CMTag.Invalid.GetHashCode (), Is.Not.EqualTo (0), "Invalid"); + Assert.That (CMTag.MediaTypeVideo.GetHashCode (), Is.Not.EqualTo (0), "MediaTypeVideo"); + Assert.That (CMTag.MediaSubTypeMebx.GetHashCode (), Is.Not.EqualTo (0), "MediaSubTypeMebx"); + Assert.That (CMTag.MediaTypeAudio.GetHashCode (), Is.Not.EqualTo (0), "MediaTypeAudio"); + Assert.That (CMTag.MediaTypeMetadata.GetHashCode (), Is.Not.EqualTo (0), "MediaTypeMetadata"); + Assert.That (CMTag.StereoLeftEye.GetHashCode (), Is.Not.EqualTo (0), "StereoLeftEye"); + Assert.That (CMTag.StereoRightEye.GetHashCode (), Is.Not.EqualTo (0), "StereoRightEye"); + Assert.That (CMTag.StereoLeftAndRightEye.GetHashCode (), Is.Not.EqualTo (0), "StereoLeftAndRightEye"); + Assert.That (CMTag.StereoNone.GetHashCode (), Is.Not.EqualTo (0), "StereoNone"); + Assert.That (CMTag.StereoInterpretationOrderReversed.GetHashCode (), Is.Not.EqualTo (0), "StereoInterpretationOrderReversed"); + Assert.That (CMTag.ProjectionTypeRectangular.GetHashCode (), Is.Not.EqualTo (0), "ProjectionTypeRectangular"); + Assert.That (CMTag.ProjectionTypeEquirectangular.GetHashCode (), Is.Not.EqualTo (0), "ProjectionTypeEquirectangular"); + Assert.That (CMTag.ProjectionTypeHalfEquirectangular.GetHashCode (), Is.Not.EqualTo (0), "ProjectionTypeHalfEquirectangular"); + Assert.That (CMTag.ProjectionTypeFisheye.GetHashCode (), Is.Not.EqualTo (0), "ProjectionTypeFisheye"); + Assert.That (CMTag.PackingTypeNone.GetHashCode (), Is.Not.EqualTo (0), "PackingTypeNone"); + Assert.That (CMTag.PackingTypeSideBySide.GetHashCode (), Is.Not.EqualTo (0), "PackingTypeSideBySide"); + Assert.That (CMTag.PackingTypeOverUnder.GetHashCode (), Is.Not.EqualTo (0), "PackingTypeOverUnder"); }); } } diff --git a/tests/monotouch-test/CoreMedia/CMTaggedBufferGroupTests.cs b/tests/monotouch-test/CoreMedia/CMTaggedBufferGroupTests.cs index eb638bf29f62..8f197d1038cf 100644 --- a/tests/monotouch-test/CoreMedia/CMTaggedBufferGroupTests.cs +++ b/tests/monotouch-test/CoreMedia/CMTaggedBufferGroupTests.cs @@ -24,7 +24,7 @@ public void GetTypeIdTest () { TestRuntime.AssertXcodeVersion (15, 0); - Assert.AreNotEqual (0, CMTaggedBufferGroup.GetTypeId (), "GetTypeId"); + Assert.That (CMTaggedBufferGroup.GetTypeId (), Is.Not.EqualTo (0), "GetTypeId"); } [Test] @@ -39,8 +39,8 @@ public void Create_PixelBuffers () new [] { tagCollection }, new [] { pixelBuffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status"); - Assert.AreEqual (1, (int) group.Count, "Count A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); Assert.Throws (() => CMTaggedBufferGroup.Create ( new [] { tagCollection }, @@ -79,8 +79,8 @@ public void Create_MediaBuffers () new [] { tagCollection }, new [] { sampleBuffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status"); - Assert.AreEqual (1, (int) group.Count, "Count A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); Assert.Throws (() => CMTaggedBufferGroup.Create ( new [] { tagCollection }, @@ -113,8 +113,8 @@ public void Create_MixedBuffers () new [] { tagCollection1, tagCollection2 }, new NativeObject [] { pixelBuffer, sampleBuffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status"); - Assert.AreEqual (2, (int) group.Count, "Count A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status"); + Assert.That ((int) group.Count, Is.EqualTo (2), "Count A"); Assert.Throws (() => CMTaggedBufferGroup.Create ( new [] { tagCollection1 }, @@ -159,8 +159,8 @@ public void Combine () out var status2); using var group = CMTaggedBufferGroup.Combine (out var status, group1, group2); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status"); - Assert.AreEqual (2, (int) group.Count, "Count A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status"); + Assert.That ((int) group.Count, Is.EqualTo (2), "Count A"); } } @@ -176,9 +176,9 @@ public void GetTagCollection () new [] { tagCollection }, new [] { pixelBuffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status"); - Assert.AreEqual (1, (int) group.Count, "Count A"); - Assert.AreEqual (tagCollection.Handle, group.GetTagCollection (0).Handle, "#0"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); + Assert.That (group.GetTagCollection (0).Handle, Is.EqualTo (tagCollection.Handle), "#0"); Assert.Throws (() => group.GetTagCollection (-1), "AOORE: -1"); Assert.Throws (() => group.GetTagCollection (1), "AOORE: 1"); @@ -197,9 +197,9 @@ public void GetPixelBuffer () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); - Assert.IsNotNull (group.GetPixelBuffer (0), "#0 A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); + Assert.That (group.GetPixelBuffer (0), Is.Not.Null, "#0 A"); Assert.Throws (() => group.GetPixelBuffer (-1), "AOORE: -1"); Assert.Throws (() => group.GetPixelBuffer (1), "AOORE: 1"); @@ -212,9 +212,9 @@ public void GetPixelBuffer () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status B"); - Assert.AreEqual (1, (int) group.Count, "Count B"); - Assert.IsNull (group.GetPixelBuffer (0), "#0 B"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status B"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count B"); + Assert.That (group.GetPixelBuffer (0), Is.Null, "#0 B"); } } @@ -230,9 +230,9 @@ public void GetSampleBuffer () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); - Assert.AreEqual (buffer.Handle, group.GetSampleBuffer (0).Handle, "#0 A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); + Assert.That (group.GetSampleBuffer (0).Handle, Is.EqualTo (buffer.Handle), "#0 A"); Assert.Throws (() => group.GetSampleBuffer (-1), "AOORE: -1"); Assert.Throws (() => group.GetSampleBuffer (1), "AOORE: 1"); @@ -245,9 +245,9 @@ public void GetSampleBuffer () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status B"); - Assert.AreEqual (1, (int) group.Count, "Count B"); - Assert.IsNull (group.GetSampleBuffer (0), "#0 B"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status B"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count B"); + Assert.That (group.GetSampleBuffer (0), Is.Null, "#0 B"); } } @@ -265,14 +265,14 @@ public void GetMixedBuffers () new [] { tagCollection1, tagCollection2 }, new NativeObject [] { pixelBuffer, sampleBuffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status C"); - Assert.AreEqual (2, (int) group.Count, "Count C"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status C"); + Assert.That ((int) group.Count, Is.EqualTo (2), "Count C"); - Assert.IsNotNull (group.GetPixelBuffer (0), "#0 C1"); - Assert.IsNull (group.GetPixelBuffer (1), "#1 C1"); + Assert.That (group.GetPixelBuffer (0), Is.Not.Null, "#0 C1"); + Assert.That (group.GetPixelBuffer (1), Is.Null, "#1 C1"); - Assert.IsNull (group.GetSampleBuffer (0), "#0 C2"); - Assert.IsNotNull (group.GetSampleBuffer (1), "#1 C2"); + Assert.That (group.GetSampleBuffer (0), Is.Null, "#0 C2"); + Assert.That (group.GetSampleBuffer (1), Is.Not.Null, "#1 C2"); } } @@ -288,11 +288,11 @@ public void GetPixelBuffer_Tag () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); - Assert.AreEqual (buffer.Handle, group.GetPixelBuffer (CMTag.MediaTypeVideo, out var index).Handle, "Video A"); - Assert.AreEqual (0, (int) index, "Index A"); - Assert.IsNull (group.GetPixelBuffer (CMTag.MediaTypeAudio, out index), "Audio A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); + Assert.That (group.GetPixelBuffer (CMTag.MediaTypeVideo, out var index).Handle, Is.EqualTo (buffer.Handle), "Video A"); + Assert.That ((int) index, Is.EqualTo (0), "Index A"); + Assert.That (group.GetPixelBuffer (CMTag.MediaTypeAudio, out index), Is.Null, "Audio A"); } { @@ -303,9 +303,9 @@ public void GetPixelBuffer_Tag () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); - Assert.IsNull (group.GetPixelBuffer (CMTag.MediaTypeVideo, out var index), "Video A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); + Assert.That (group.GetPixelBuffer (CMTag.MediaTypeVideo, out var index), Is.Null, "Video A"); } { @@ -318,9 +318,9 @@ public void GetPixelBuffer_Tag () new [] { tagCollection1, tagCollection2 }, new [] { buffer1, buffer2 }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (2, (int) group.Count, "Count A"); - Assert.IsNull (group.GetPixelBuffer (CMTag.MediaTypeVideo, out var index), "Video A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (2), "Count A"); + Assert.That (group.GetPixelBuffer (CMTag.MediaTypeVideo, out var index), Is.Null, "Video A"); } } @@ -336,12 +336,12 @@ public void GetPixelBuffer_TagCollection () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); - Assert.AreEqual (buffer.Handle, group.GetPixelBuffer (tagCollection, out var index).Handle, "Video A"); - Assert.AreEqual (0, (int) index, "Index A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); + Assert.That (group.GetPixelBuffer (tagCollection, out var index).Handle, Is.EqualTo (buffer.Handle), "Video A"); + Assert.That ((int) index, Is.EqualTo (0), "Index A"); using var tagCollection2 = CMTagCollection.Create (CMTag.MediaTypeAudio); - Assert.IsNull (group.GetPixelBuffer (tagCollection2, out index), "Audio A"); + Assert.That (group.GetPixelBuffer (tagCollection2, out index), Is.Null, "Audio A"); } { @@ -352,9 +352,9 @@ public void GetPixelBuffer_TagCollection () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); - Assert.IsNull (group.GetPixelBuffer (tagCollection, out var index), "Video A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); + Assert.That (group.GetPixelBuffer (tagCollection, out var index), Is.Null, "Video A"); } { @@ -367,9 +367,9 @@ public void GetPixelBuffer_TagCollection () new [] { tagCollection1, tagCollection2 }, new [] { buffer1, buffer2 }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (2, (int) group.Count, "Count A"); - Assert.IsNull (group.GetPixelBuffer (tagCollection1, out var index), "Video A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (2), "Count A"); + Assert.That (group.GetPixelBuffer (tagCollection1, out var index), Is.Null, "Video A"); } } @@ -385,11 +385,11 @@ public void GetSampleBuffer_Tag () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); - Assert.AreEqual (buffer.Handle, group.GetSampleBuffer (CMTag.MediaTypeVideo, out var index).Handle, "Video A"); - Assert.AreEqual (0, (int) index, "Index A"); - Assert.IsNull (group.GetSampleBuffer (CMTag.MediaTypeAudio, out index), "Audio A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); + Assert.That (group.GetSampleBuffer (CMTag.MediaTypeVideo, out var index).Handle, Is.EqualTo (buffer.Handle), "Video A"); + Assert.That ((int) index, Is.EqualTo (0), "Index A"); + Assert.That (group.GetSampleBuffer (CMTag.MediaTypeAudio, out index), Is.Null, "Audio A"); } { @@ -400,9 +400,9 @@ public void GetSampleBuffer_Tag () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); - Assert.IsNull (group.GetSampleBuffer (CMTag.MediaTypeVideo, out var index), "Video A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); + Assert.That (group.GetSampleBuffer (CMTag.MediaTypeVideo, out var index), Is.Null, "Video A"); } { @@ -415,9 +415,9 @@ public void GetSampleBuffer_Tag () new [] { tagCollection1, tagCollection2 }, new [] { buffer1, buffer2 }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (2, (int) group.Count, "Count A"); - Assert.IsNull (group.GetSampleBuffer (CMTag.MediaTypeVideo, out var index), "Video A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (2), "Count A"); + Assert.That (group.GetSampleBuffer (CMTag.MediaTypeVideo, out var index), Is.Null, "Video A"); } } @@ -433,12 +433,12 @@ public void GetSampleBuffer_TagCollection () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); - Assert.IsNotNull (group.GetSampleBuffer (tagCollection, out var index), "Video A"); - Assert.AreEqual (0, (int) index, "Index A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); + Assert.That (group.GetSampleBuffer (tagCollection, out var index), Is.Not.Null, "Video A"); + Assert.That ((int) index, Is.EqualTo (0), "Index A"); using var tagCollection2 = CMTagCollection.Create (CMTag.MediaTypeAudio); - Assert.IsNull (group.GetSampleBuffer (tagCollection2, out index), "Audio A"); + Assert.That (group.GetSampleBuffer (tagCollection2, out index), Is.Null, "Audio A"); } { @@ -449,9 +449,9 @@ public void GetSampleBuffer_TagCollection () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status B"); - Assert.AreEqual (1, (int) group.Count, "Count B"); - Assert.IsNull (group.GetSampleBuffer (tagCollection, out var index), "Video B"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status B"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count B"); + Assert.That (group.GetSampleBuffer (tagCollection, out var index), Is.Null, "Video B"); } { @@ -464,9 +464,9 @@ public void GetSampleBuffer_TagCollection () new [] { tagCollection1, tagCollection2 }, new [] { buffer1, buffer2 }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status C"); - Assert.AreEqual (2, (int) group.Count, "Count C"); - Assert.IsNull (group.GetSampleBuffer (tagCollection1, out var index), "Video C"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status C"); + Assert.That ((int) group.Count, Is.EqualTo (2), "Count C"); + Assert.That (group.GetSampleBuffer (tagCollection1, out var index), Is.Null, "Video C"); } } @@ -485,11 +485,11 @@ public void GetNumberOfMatches () new [] { tagCollection1, tagCollection2 }, new [] { buffer1, buffer2 }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (2, (int) group.Count, "Count A"); - Assert.AreEqual (2, (int) group.GetNumberOfMatches (tagCollection1), "Matches 1 A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (2), "Count A"); + Assert.That ((int) group.GetNumberOfMatches (tagCollection1), Is.EqualTo (2), "Matches 1 A"); using var tagCollection3 = CMTagCollection.Create (CMTag.MediaTypeAudio); - Assert.AreEqual (0, (int) group.GetNumberOfMatches (tagCollection3), "Matches 2 A"); + Assert.That ((int) group.GetNumberOfMatches (tagCollection3), Is.EqualTo (0), "Matches 2 A"); } } @@ -505,12 +505,12 @@ public void CreateFormatDescription () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); using var desc = group.CreateFormatDescription (out status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status Desc A"); - Assert.AreEqual (CMMediaType.TaggedBufferGroup, desc.MediaType, $"Desc.MediaType: {AVFoundationEnumTest.FourCC ((int) desc.MediaType)}"); - Assert.AreEqual (CMTaggedBufferGroupFormatType.TaggedBufferGroup, desc.TaggedBufferGroupFormatType, "Desc.TaggedBufferGroupFormatType"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status Desc A"); + Assert.That (desc.MediaType, Is.EqualTo (CMMediaType.TaggedBufferGroup), $"Desc.MediaType: {AVFoundationEnumTest.FourCC ((int) desc.MediaType)}"); + Assert.That (desc.TaggedBufferGroupFormatType, Is.EqualTo (CMTaggedBufferGroupFormatType.TaggedBufferGroup), "Desc.TaggedBufferGroupFormatType"); } } @@ -526,12 +526,12 @@ public void CreateFormatDescriptionWithExtensions () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); using var desc = group.CreateFormatDescription (null, out status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status Desc A"); - Assert.AreEqual (CMMediaType.TaggedBufferGroup, desc.MediaType, $"Desc.MediaType: {AVFoundationEnumTest.FourCC ((int) desc.MediaType)}"); - Assert.AreEqual (CMTaggedBufferGroupFormatType.TaggedBufferGroup, desc.TaggedBufferGroupFormatType, "Desc.TaggedBufferGroupFormatType A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status Desc A"); + Assert.That (desc.MediaType, Is.EqualTo (CMMediaType.TaggedBufferGroup), $"Desc.MediaType: {AVFoundationEnumTest.FourCC ((int) desc.MediaType)}"); + Assert.That (desc.TaggedBufferGroupFormatType, Is.EqualTo (CMTaggedBufferGroupFormatType.TaggedBufferGroup), "Desc.TaggedBufferGroupFormatType A"); } { @@ -541,13 +541,13 @@ public void CreateFormatDescriptionWithExtensions () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status B"); - Assert.AreEqual (1, (int) group.Count, "Count B"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status B"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count B"); using var extensions = new NSDictionary (); using var desc = group.CreateFormatDescription (extensions, out status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status Desc B"); - Assert.AreEqual (CMMediaType.TaggedBufferGroup, desc.MediaType, $"Desc.MediaType: {AVFoundationEnumTest.FourCC ((int) desc.MediaType)}"); - Assert.AreEqual (CMTaggedBufferGroupFormatType.TaggedBufferGroup, desc.TaggedBufferGroupFormatType, "Desc.TaggedBufferGroupFormatType B"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status Desc B"); + Assert.That (desc.MediaType, Is.EqualTo (CMMediaType.TaggedBufferGroup), $"Desc.MediaType: {AVFoundationEnumTest.FourCC ((int) desc.MediaType)}"); + Assert.That (desc.TaggedBufferGroupFormatType, Is.EqualTo (CMTaggedBufferGroupFormatType.TaggedBufferGroup), "Desc.TaggedBufferGroupFormatType B"); } } @@ -563,13 +563,13 @@ public void Matches () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); using var desc = group.CreateFormatDescription (out status); - Assert.IsTrue (group.Matches (desc), "Matches A"); + Assert.That (group.Matches (desc), Is.True, "Matches A"); using var desc2 = CMFormatDescription.Create (CMMediaType.ClosedCaption, (uint) CMClosedCaptionFormatType.CEA608, out var fde); - Assert.AreEqual (CMFormatDescriptionError.None, fde, "FDE"); - Assert.IsFalse (group.Matches (desc2), "Matches B"); + Assert.That (fde, Is.EqualTo (CMFormatDescriptionError.None), "FDE"); + Assert.That (group.Matches (desc2), Is.False, "Matches B"); } } @@ -585,12 +585,12 @@ public void CreateSampleBuffer () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); using var formatDescription = CMFormatDescription.Create (CMMediaType.TaggedBufferGroup, (uint) CMTaggedBufferGroupFormatType.TaggedBufferGroup, out var fde); - Assert.AreEqual (CMFormatDescriptionError.None, fde, "FDE A"); + Assert.That (fde, Is.EqualTo (CMFormatDescriptionError.None), "FDE A"); using var sampleBuffer = group.CreateSampleBuffer (CMTime.Zero, CMTime.FromSeconds (1, 1), formatDescription, out status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status CSB A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status CSB A"); } } @@ -606,18 +606,18 @@ public void GetTaggedBufferGroup () new [] { tagCollection }, new [] { buffer }, out var status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status A"); - Assert.AreEqual (1, (int) group.Count, "Count A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status A"); + Assert.That ((int) group.Count, Is.EqualTo (1), "Count A"); using var formatDescription = CMFormatDescription.Create (CMMediaType.TaggedBufferGroup, (uint) CMTaggedBufferGroupFormatType.TaggedBufferGroup, out var fde); - Assert.AreEqual (CMFormatDescriptionError.None, fde, "FDE A"); + Assert.That (fde, Is.EqualTo (CMFormatDescriptionError.None), "FDE A"); using var sampleBuffer = group.CreateSampleBuffer (CMTime.Zero, CMTime.FromSeconds (1, 1), formatDescription, out status); - Assert.AreEqual (CMTaggedBufferGroupError.Success, status, "Status CSB A"); + Assert.That (status, Is.EqualTo (CMTaggedBufferGroupError.Success), "Status CSB A"); - Assert.IsNotNull (sampleBuffer.TaggedBufferGroup, "CMSampleBuffer.GetTaggedBufferGroup A"); - Assert.IsNotNull (CMTaggedBufferGroup.GetTaggedBufferGroup (sampleBuffer), "CMTaggedBufferGroup.GetTaggedBufferGroup A"); + Assert.That (sampleBuffer.TaggedBufferGroup, Is.Not.Null, "CMSampleBuffer.GetTaggedBufferGroup A"); + Assert.That (CMTaggedBufferGroup.GetTaggedBufferGroup (sampleBuffer), Is.Not.Null, "CMTaggedBufferGroup.GetTaggedBufferGroup A"); - Assert.IsNull (buffer.TaggedBufferGroup, "CMSampleBuffer.GetTaggedBufferGroup B"); - Assert.IsNull (CMTaggedBufferGroup.GetTaggedBufferGroup (buffer), "CMTaggedBufferGroup.GetTaggedBufferGroup B"); + Assert.That (buffer.TaggedBufferGroup, Is.Null, "CMSampleBuffer.GetTaggedBufferGroup B"); + Assert.That (CMTaggedBufferGroup.GetTaggedBufferGroup (buffer), Is.Null, "CMTaggedBufferGroup.GetTaggedBufferGroup B"); Assert.Throws (() => CMTaggedBufferGroup.GetTaggedBufferGroup (null), "ANE"); } diff --git a/tests/monotouch-test/CoreMedia/CMTimeRangeTests.cs b/tests/monotouch-test/CoreMedia/CMTimeRangeTests.cs index b6b780bd0a9f..ba468b362c82 100644 --- a/tests/monotouch-test/CoreMedia/CMTimeRangeTests.cs +++ b/tests/monotouch-test/CoreMedia/CMTimeRangeTests.cs @@ -17,9 +17,9 @@ public class CMTimeRangeTests { public void InvalidRangeFieldTest () { var invalid = CMTimeRange.InvalidRange; - Assert.NotNull (invalid, "CMTimeRange.InvalidRange Should Not be null"); - Assert.NotNull (invalid.Duration, "CMTimeRange.InvalidRange.Duration Should Not be null"); - Assert.NotNull (invalid.Start, "CMTimeRange.InvalidRange.Duration Should Not be null"); + Assert.That (invalid, Is.Not.Null, "CMTimeRange.InvalidRange Should Not be null"); + Assert.That (invalid.Duration, Is.Not.Null, "CMTimeRange.InvalidRange.Duration Should Not be null"); + Assert.That (invalid.Start, Is.Not.Null, "CMTimeRange.InvalidRange.Duration Should Not be null"); Assert.That (invalid.Duration.IsInvalid, "CMTimeRange.InvalidRange.Duration.IsInvalid"); Assert.That (invalid.Start.IsInvalid, "CMTimeRange.InvalidRange.Start.IsInvalid"); Assert.That (invalid.Duration.Description, Is.EqualTo ("{INVALID}"), "Duration Description"); @@ -30,9 +30,9 @@ public void InvalidRangeFieldTest () public void InvalidMappingFieldTest () { var invalid = CMTimeRange.InvalidMapping; - Assert.NotNull (invalid, "CMTimeRange.InvalidMapping Should Not be null"); - Assert.NotNull (invalid.Duration, "CMTimeRange.InvalidMapping.Duration Should Not be null"); - Assert.NotNull (invalid.Start, "CMTimeRange.InvalidMapping.Duration Should Not be null"); + Assert.That (invalid, Is.Not.Null, "CMTimeRange.InvalidMapping Should Not be null"); + Assert.That (invalid.Duration, Is.Not.Null, "CMTimeRange.InvalidMapping.Duration Should Not be null"); + Assert.That (invalid.Start, Is.Not.Null, "CMTimeRange.InvalidMapping.Duration Should Not be null"); Assert.That (invalid.Duration.IsInvalid, "CMTimeRange.InvalidMapping.Duration.IsInvalid"); Assert.That (invalid.Start.IsInvalid, "CMTimeRange.InvalidMapping.Start.IsInvalid"); Assert.That (invalid.Duration.Description, Is.EqualTo ("{INVALID}"), "Duration Description"); @@ -43,9 +43,9 @@ public void InvalidMappingFieldTest () public void ZeroFieldTest () { var zero = CMTimeRange.Zero; - Assert.NotNull (zero, "CMTimeRange.Zero Should Not be null"); - Assert.NotNull (zero.Duration, "CMTimeRange.Zero.Duration Should Not be null"); - Assert.NotNull (zero.Start, "CMTimeRange.Zero.Duration Should Not be null"); + Assert.That (zero, Is.Not.Null, "CMTimeRange.Zero Should Not be null"); + Assert.That (zero.Duration, Is.Not.Null, "CMTimeRange.Zero.Duration Should Not be null"); + Assert.That (zero.Start, Is.Not.Null, "CMTimeRange.Zero.Duration Should Not be null"); Assert.That (!zero.Duration.IsInvalid, "CMTimeRange.Zero.Duration.IsInvalid"); Assert.That (!zero.Start.IsInvalid, "CMTimeRange.Zero.Start.IsInvalid"); Assert.That (zero.Duration.Description, Is.EqualTo ("{0/1 = 0.000}"), "Duration Description"); diff --git a/tests/monotouch-test/CoreMedia/CMTimeTests.cs b/tests/monotouch-test/CoreMedia/CMTimeTests.cs index f62ede6ac17e..b71e1f4b522f 100644 --- a/tests/monotouch-test/CoreMedia/CMTimeTests.cs +++ b/tests/monotouch-test/CoreMedia/CMTimeTests.cs @@ -140,15 +140,15 @@ public void CMTimeMappingFactoryMethods () CompareCMTimeRange (map.Source, CMTimeRange.InvalidRange, "CMTimeMapping.CreateFromDictionary"); CompareCMTimeRange (map.Target, CMTimeRange.InvalidRange, "CMTimeMapping.CreateFromDictionary"); - Assert.IsNotNull (map.AsDictionary (), "CMTimeMapping AsDictionary"); + Assert.That (map.AsDictionary (), Is.Not.Null, "CMTimeMapping AsDictionary"); - Assert.IsNotNull (map.Description, "CMTimeMapping Description"); + Assert.That (map.Description, Is.Not.Null, "CMTimeMapping Description"); } void CompareCMTimeRange (CMTimeRange first, CMTimeRange second, string description) { - Assert.AreEqual (first.Duration, second.Duration, "CompareCMTimeRange - duration - " + description); - Assert.AreEqual (first.Start, second.Start, "CompareCMTimeRange - start - " + description); + Assert.That (second.Duration, Is.EqualTo (first.Duration), "CompareCMTimeRange - duration - " + description); + Assert.That (second.Start, Is.EqualTo (first.Start), "CompareCMTimeRange - start - " + description); } [Test] @@ -159,7 +159,7 @@ public void CMTimeStrongDictionary () Time = time }; var retrievedTime = timeDict.Time; - Assert.IsTrue (time == retrievedTime, "CMTimeStrongDictionary"); + Assert.That (time == retrievedTime, Is.True, "CMTimeStrongDictionary"); } class CMTimeDict : DictionaryContainer { diff --git a/tests/monotouch-test/CoreMedia/CMTimebaseTest.cs b/tests/monotouch-test/CoreMedia/CMTimebaseTest.cs index 032d48e05866..35f1d9a3dbf1 100644 --- a/tests/monotouch-test/CoreMedia/CMTimebaseTest.cs +++ b/tests/monotouch-test/CoreMedia/CMTimebaseTest.cs @@ -21,8 +21,8 @@ public void DefaultValues () var htc = CMClock.HostTimeClock; using (var tb = new CMTimebase (htc)) { - Assert.AreEqual (0, tb.EffectiveRate, "EffectiveRate"); - Assert.AreEqual (0, tb.Rate, "Rate"); + Assert.That (tb.EffectiveRate, Is.EqualTo (0), "EffectiveRate"); + Assert.That (tb.Rate, Is.EqualTo (0), "Rate"); using (var m = tb.GetMaster ()) { Assert.That (m.Handle, Is.Not.EqualTo (IntPtr.Zero), "GetMaster"); @@ -30,7 +30,7 @@ public void DefaultValues () using (var m = tb.GetMasterClock ()) { Assert.That (m.Handle, Is.Not.EqualTo (IntPtr.Zero), "GetMasterClock"); } - Assert.Null (tb.GetMasterTimebase (), "GetMasterTimebase"); + Assert.That (tb.GetMasterTimebase (), Is.Null, "GetMasterTimebase"); } } @@ -40,9 +40,9 @@ public void SetAnchorTime () TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 10, 8, throwIfOtherPlatform: false); using (var tb = new CMTimebase (CMClock.HostTimeClock)) { - Assert.AreEqual (CMTimebaseError.None, tb.SetAnchorTime (new CMTime (1000000, 200), new CMTime (-1, -2))); + Assert.That (tb.SetAnchorTime (new CMTime (1000000, 200), new CMTime (-1, -2)), Is.EqualTo (CMTimebaseError.None)); var cmt = tb.GetTime (new CMTimeScale (int.MaxValue), CMTimeRoundingMethod.QuickTime); - Assert.AreEqual (5000, cmt.Seconds); + Assert.That (cmt.Seconds, Is.EqualTo (5000)); } } @@ -54,8 +54,8 @@ public void AddTimer () using (var tb = new CMTimebase (CMClock.HostTimeClock)) { var timer = NSTimer.CreateRepeatingTimer (CMTimebase.VeryLongTimeInterval, delegate { }); - Assert.AreEqual (CMTimebaseError.None, tb.AddTimer (timer, NSRunLoop.Current), "#1"); - Assert.AreEqual (CMTimebaseError.None, tb.SetTimerNextFireTime (timer, new CMTime (100, 2)), "#2"); + Assert.That (tb.AddTimer (timer, NSRunLoop.Current), Is.EqualTo (CMTimebaseError.None), "#1"); + Assert.That (tb.SetTimerNextFireTime (timer, new CMTime (100, 2)), Is.EqualTo (CMTimebaseError.None), "#2"); tb.RemoveTimer (timer); } @@ -106,7 +106,7 @@ void AssertNullOrValidHandle (INativeObject o, string description) { if (o is null) return; - Assert.AreNotEqual (IntPtr.Zero, o.Handle, "AssertNullOrValidHandle - " + description); + Assert.That (o.Handle, Is.Not.EqualTo (IntPtr.Zero), "AssertNullOrValidHandle - " + description); } [Test] @@ -119,7 +119,7 @@ public void CMClockConstructor () // if it throws we fail the test using var timebase = new CMTimebase (null, CMClock.HostTimeClock); - Assert.NotNull (timebase, "Not null"); + Assert.That (timebase, Is.Not.Null, "Not null"); } [Test] @@ -127,7 +127,7 @@ public void SourceClockProperty () { TestRuntime.AssertXcodeVersion (13, 0); using var timebase = new CMTimebase (null, CMClock.HostTimeClock); - Assert.NotNull (timebase.SourceClock, "not null source clock"); + Assert.That (timebase.SourceClock, Is.Not.Null, "not null source clock"); // set and if it throws we fail the test timebase.SourceClock = CMClock.HostTimeClock; } @@ -151,7 +151,7 @@ public void SourceTimebaseProperty () TestRuntime.AssertXcodeVersion (13, 0); using var mainTimebase = new CMTimebase (CMClock.HostTimeClock); using var timebase = new CMTimebase (null, mainTimebase); - Assert.NotNull (timebase.SourceTimebase, "Not null timebase"); + Assert.That (timebase.SourceTimebase, Is.Not.Null, "Not null timebase"); // if we throw we fail test test using var secondTimebase = new CMTimebase (CMClock.HostTimeClock); timebase.SourceTimebase = secondTimebase; diff --git a/tests/monotouch-test/CoreMedia/SampleBufferTest.cs b/tests/monotouch-test/CoreMedia/SampleBufferTest.cs index 22b6c53cb06d..caabf834bfb5 100644 --- a/tests/monotouch-test/CoreMedia/SampleBufferTest.cs +++ b/tests/monotouch-test/CoreMedia/SampleBufferTest.cs @@ -30,8 +30,8 @@ public void CreateForImageBuffer () CMSampleBufferError sbe; var sb = CMSampleBuffer.CreateForImageBuffer (pixelBuffer, true, desc, sampleTiming, out sbe); - Assert.IsNotNull (sb, "#1"); - Assert.AreEqual (CMSampleBufferError.None, sbe, "#2"); + Assert.That (sb, Is.Not.Null, "#1"); + Assert.That (sbe, Is.EqualTo (CMSampleBufferError.None), "#2"); } [Test] @@ -46,7 +46,7 @@ public void CreateReadyWithPacketDescriptions () using (var fd = CMFormatDescription.Create (CMMediaType.ClosedCaption, (uint) CMClosedCaptionFormatType.CEA608, out fde)) { CMSampleBufferError sbe; using (var sb = CMSampleBuffer.CreateReadyWithPacketDescriptions (bb, fd, 1, CMTime.Indefinite, null, out sbe)) { - Assert.Null (sb, "CMSampleBuffer"); + Assert.That (sb, Is.Null, "CMSampleBuffer"); // the `null` does not match format description (but I lack a better test, at least it's callable) Assert.That (sbe, Is.EqualTo (CMSampleBufferError.RequiredParameterMissing), "CMSampleBufferError"); } @@ -108,7 +108,7 @@ public void SetInvalidateCallback_Replace () result = sb.SetInvalidateCallback (delegate (CMSampleBuffer buffer) { i--; - Assert.AreSame (buffer, sb, "same"); + Assert.That (sb, Is.SameAs (buffer), "same"); }); Assert.That (result, Is.EqualTo (CMSampleBufferError.RequiredParameterMissing), "RequiredParameterMissing"); @@ -132,7 +132,7 @@ public void SetInvalidateCallback () var result = sb.SetInvalidateCallback (delegate (CMSampleBuffer buffer) { i++; - Assert.AreSame (buffer, sb, "same"); + Assert.That (sb, Is.SameAs (buffer), "same"); }); Assert.That (result, Is.EqualTo (CMSampleBufferError.None), "SetInvalidateCallback/None"); @@ -164,7 +164,7 @@ public void SetInvalidateCallback_Null () var result = sb.SetInvalidateCallback (delegate (CMSampleBuffer buffer) { i++; - Assert.AreSame (buffer, sb, "same"); + Assert.That (sb, Is.SameAs (buffer), "same"); }); Assert.That (result, Is.EqualTo (CMSampleBufferError.None), "SetInvalidateCallback/None"); @@ -192,7 +192,7 @@ public void CallForEachSample () var result = sb.CallForEachSample (delegate (CMSampleBuffer buffer, int index) { i++; - Assert.AreSame (buffer, sb, "same-1"); + Assert.That (sb, Is.SameAs (buffer), "same-1"); return CMSampleBufferError.CannotSubdivide; }); Assert.That (result, Is.EqualTo (CMSampleBufferError.CannotSubdivide), "custom error"); diff --git a/tests/monotouch-test/CoreMidi/Midi2DeviceManufacturerTest.cs b/tests/monotouch-test/CoreMidi/Midi2DeviceManufacturerTest.cs index 2af633824e76..5fc0c8708176 100644 --- a/tests/monotouch-test/CoreMidi/Midi2DeviceManufacturerTest.cs +++ b/tests/monotouch-test/CoreMidi/Midi2DeviceManufacturerTest.cs @@ -13,10 +13,10 @@ public class Midi2DeviceManufacturerTest { public void SysExIdByte () { var value = default (Midi2DeviceManufacturer); - CollectionAssert.AreEqual (new byte [] { 0, 0, 0 }, value.SysExIdByte, "A"); + Assert.That (value.SysExIdByte, Is.EqualTo (new byte [] { 0, 0, 0 }), "A"); value.SysExIdByte = new byte [] { 1, 2, 3 }; - CollectionAssert.AreEqual (new byte [] { 1, 2, 3 }, value.SysExIdByte, "B"); + Assert.That (value.SysExIdByte, Is.EqualTo (new byte [] { 1, 2, 3 }), "B"); Assert.Throws (() => value.SysExIdByte = null, "C"); Assert.Throws (() => value.SysExIdByte = new byte [2], "D"); diff --git a/tests/monotouch-test/CoreMidi/Midi2DeviceRevisionLevelTest.cs b/tests/monotouch-test/CoreMidi/Midi2DeviceRevisionLevelTest.cs index b0603c4dbc31..d236fabed47f 100644 --- a/tests/monotouch-test/CoreMidi/Midi2DeviceRevisionLevelTest.cs +++ b/tests/monotouch-test/CoreMidi/Midi2DeviceRevisionLevelTest.cs @@ -13,10 +13,10 @@ public class Midi2DeviceRevisionLevelTest { public void RevisionLevel () { var value = default (Midi2DeviceRevisionLevel); - CollectionAssert.AreEqual (new byte [] { 0, 0, 0, 0 }, value.RevisionLevel, "A"); + Assert.That (value.RevisionLevel, Is.EqualTo (new byte [] { 0, 0, 0, 0 }), "A"); value.RevisionLevel = new byte [] { 1, 2, 3, 4 }; - CollectionAssert.AreEqual (new byte [] { 1, 2, 3, 4 }, value.RevisionLevel, "B"); + Assert.That (value.RevisionLevel, Is.EqualTo (new byte [] { 1, 2, 3, 4 }), "B"); Assert.Throws (() => value.RevisionLevel = null, "C"); Assert.Throws (() => value.RevisionLevel = new byte [2], "D"); diff --git a/tests/monotouch-test/CoreMidi/MidiCIProfileIdTest.cs b/tests/monotouch-test/CoreMidi/MidiCIProfileIdTest.cs index f7f6c3db2681..ba779687b397 100644 --- a/tests/monotouch-test/CoreMidi/MidiCIProfileIdTest.cs +++ b/tests/monotouch-test/CoreMidi/MidiCIProfileIdTest.cs @@ -13,11 +13,11 @@ public class MidiCIProfileIdTest { public void Standard () { var value = default (MidiCIProfileId); - Assert.AreEqual (0, value.Standard.ProfileIdByte1, "ProfileIdByte1 A"); - Assert.AreEqual (0, value.Standard.ProfileBank, "ProfileBank A"); - Assert.AreEqual (0, value.Standard.ProfileNumber, "ProfileNumber A"); - Assert.AreEqual (0, value.Standard.ProfileVersion, "ProfileVersion A"); - Assert.AreEqual (0, value.Standard.ProfileLevel, "ProfileLevel A"); + Assert.That (value.Standard.ProfileIdByte1, Is.EqualTo (0), "ProfileIdByte1 A"); + Assert.That (value.Standard.ProfileBank, Is.EqualTo (0), "ProfileBank A"); + Assert.That (value.Standard.ProfileNumber, Is.EqualTo (0), "ProfileNumber A"); + Assert.That (value.Standard.ProfileVersion, Is.EqualTo (0), "ProfileVersion A"); + Assert.That (value.Standard.ProfileLevel, Is.EqualTo (0), "ProfileLevel A"); value.Standard = new MidiCIProfileIdStandard () { ProfileIdByte1 = 1, @@ -27,22 +27,22 @@ public void Standard () ProfileLevel = 5, }; - Assert.AreEqual (1, value.Standard.ProfileIdByte1, "ProfileIdByte1 B"); - Assert.AreEqual (2, value.Standard.ProfileBank, "ProfileBank B"); - Assert.AreEqual (3, value.Standard.ProfileNumber, "ProfileNumber B"); - Assert.AreEqual (4, value.Standard.ProfileVersion, "ProfileVersion B"); - Assert.AreEqual (5, value.Standard.ProfileLevel, "ProfileLevel B"); + Assert.That (value.Standard.ProfileIdByte1, Is.EqualTo (1), "ProfileIdByte1 B"); + Assert.That (value.Standard.ProfileBank, Is.EqualTo (2), "ProfileBank B"); + Assert.That (value.Standard.ProfileNumber, Is.EqualTo (3), "ProfileNumber B"); + Assert.That (value.Standard.ProfileVersion, Is.EqualTo (4), "ProfileVersion B"); + Assert.That (value.Standard.ProfileLevel, Is.EqualTo (5), "ProfileLevel B"); } [Test] public void ManufacturerSpecific () { var value = default (MidiCIProfileId); - Assert.AreEqual (0, value.ManufacturerSpecific.SysExId1, "SysExId1 A"); - Assert.AreEqual (0, value.ManufacturerSpecific.SysExId2, "SysExId2 A"); - Assert.AreEqual (0, value.ManufacturerSpecific.SysExId3, "SysExId3 A"); - Assert.AreEqual (0, value.ManufacturerSpecific.Info1, "Info1 A"); - Assert.AreEqual (0, value.ManufacturerSpecific.Info2, "Info2 A"); + Assert.That (value.ManufacturerSpecific.SysExId1, Is.EqualTo (0), "SysExId1 A"); + Assert.That (value.ManufacturerSpecific.SysExId2, Is.EqualTo (0), "SysExId2 A"); + Assert.That (value.ManufacturerSpecific.SysExId3, Is.EqualTo (0), "SysExId3 A"); + Assert.That (value.ManufacturerSpecific.Info1, Is.EqualTo (0), "Info1 A"); + Assert.That (value.ManufacturerSpecific.Info2, Is.EqualTo (0), "Info2 A"); value.ManufacturerSpecific = new MidiCIProfileIdManufacturerSpecific () { SysExId1 = 1, @@ -52,11 +52,11 @@ public void ManufacturerSpecific () Info2 = 5, }; - Assert.AreEqual (1, value.ManufacturerSpecific.SysExId1, "SysExId1 B"); - Assert.AreEqual (2, value.ManufacturerSpecific.SysExId2, "SysExId2 B"); - Assert.AreEqual (3, value.ManufacturerSpecific.SysExId3, "SysExId3 B"); - Assert.AreEqual (4, value.ManufacturerSpecific.Info1, "Info1 B"); - Assert.AreEqual (5, value.ManufacturerSpecific.Info2, "Info2 B"); + Assert.That (value.ManufacturerSpecific.SysExId1, Is.EqualTo (1), "SysExId1 B"); + Assert.That (value.ManufacturerSpecific.SysExId2, Is.EqualTo (2), "SysExId2 B"); + Assert.That (value.ManufacturerSpecific.SysExId3, Is.EqualTo (3), "SysExId3 B"); + Assert.That (value.ManufacturerSpecific.Info1, Is.EqualTo (4), "Info1 B"); + Assert.That (value.ManufacturerSpecific.Info2, Is.EqualTo (5), "Info2 B"); } } } diff --git a/tests/monotouch-test/CoreMidi/MidiClientTest.cs b/tests/monotouch-test/CoreMidi/MidiClientTest.cs index a53f8adf6cbd..8c40b41cf542 100644 --- a/tests/monotouch-test/CoreMidi/MidiClientTest.cs +++ b/tests/monotouch-test/CoreMidi/MidiClientTest.cs @@ -23,7 +23,7 @@ public void SendTest () Assert.Inconclusive ("No Midi Destinations"); using var ep = MidiEndpoint.GetDestination (0); - Assert.NotNull (ep, "EndPoint"); + Assert.That (ep, Is.Not.Null, "EndPoint"); var mevent = new byte [] { 0x90, 0x40, 0x70 }; using var client = new MidiClient ($"outputclient-{Process.GetCurrentProcess ().Id}"); diff --git a/tests/monotouch-test/CoreMidi/MidiThruConnectionParamsTest.cs b/tests/monotouch-test/CoreMidi/MidiThruConnectionParamsTest.cs index a97742d89aea..e1e2e663e482 100644 --- a/tests/monotouch-test/CoreMidi/MidiThruConnectionParamsTest.cs +++ b/tests/monotouch-test/CoreMidi/MidiThruConnectionParamsTest.cs @@ -60,13 +60,13 @@ void AssertAreEqualWithAnySuffix (string expectedWithoutSuffix, string actual, s public void ParamsTest () { var p = new MidiThruConnectionParams (); - Assert.IsNull (p.Sources, "Sources"); - Assert.IsNull (p.Destinations, "Destinations"); + Assert.That (p.Sources, Is.Null, "Sources"); + Assert.That (p.Destinations, Is.Null, "Destinations"); AreEqual (DefaultChannelMap, p.ChannelMap, "ChannelMap"); - Assert.AreEqual (0, p.LowVelocity, "LowVelocity"); - Assert.AreEqual (0, p.HighVelocity, "HighVelocity"); - Assert.AreEqual (0, p.LowNote, "LowNote"); - Assert.AreEqual (127, p.HighNote, "HighNote"); + Assert.That (p.LowVelocity, Is.EqualTo (0), "LowVelocity"); + Assert.That (p.HighVelocity, Is.EqualTo (0), "HighVelocity"); + Assert.That (p.LowNote, Is.EqualTo (0), "LowNote"); + Assert.That (p.HighNote, Is.EqualTo (127), "HighNote"); var defaultMidiTransform = default (MidiTransform); AreEqual (defaultMidiTransform, p.NoteNumber, "NoteNumber"); AreEqual (defaultMidiTransform, p.Velocity, "Velocity"); @@ -74,13 +74,13 @@ public void ParamsTest () AreEqual (defaultMidiTransform, p.ChannelPressure, "ChannelPressure"); AreEqual (defaultMidiTransform, p.ProgramChange, "ProgramChange"); AreEqual (defaultMidiTransform, p.PitchBend, "PitchBend"); - Assert.AreEqual (false, p.FilterOutSysEx, "FilterOutSysEx"); - Assert.AreEqual (false, p.FilterOutMtc, "FilterOutMtc"); - Assert.AreEqual (false, p.FilterOutBeatClock, "FilterOutBeatClock"); - Assert.AreEqual (false, p.FilterOutTuneRequest, "FilterOutTuneRequest"); - Assert.AreEqual (false, p.FilterOutAllControls, "FilterOutAllControls"); - Assert.IsNull (p.Controls, "Controls"); - Assert.IsNull (p.Maps, "Maps"); + Assert.That (p.FilterOutSysEx, Is.EqualTo (false), "FilterOutSysEx"); + Assert.That (p.FilterOutMtc, Is.EqualTo (false), "FilterOutMtc"); + Assert.That (p.FilterOutBeatClock, Is.EqualTo (false), "FilterOutBeatClock"); + Assert.That (p.FilterOutTuneRequest, Is.EqualTo (false), "FilterOutTuneRequest"); + Assert.That (p.FilterOutAllControls, Is.EqualTo (false), "FilterOutAllControls"); + Assert.That (p.Controls, Is.Null, "Controls"); + Assert.That (p.Maps, Is.Null, "Maps"); var bytes = GetData (p); AreEqual (DefaultStruct, bytes, "Bytes"); @@ -90,12 +90,12 @@ public void ParamsTest () public void PropertiesTest_Sources () { var p = new MidiThruConnectionParams (); - Assert.IsNull (p.Sources, "Sources 1"); + Assert.That (p.Sources, Is.Null, "Sources 1"); // Set to some array var array = new MidiThruConnectionEndpoint [] { new MidiThruConnectionEndpoint (0, 0), new MidiThruConnectionEndpoint (3, 4) }; p.Sources = array; - CollectionAssert.AreEqual (array, p.Sources, "Sources 2"); + Assert.That (p.Sources, Is.EqualTo (array), "Sources 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [4] = 2; expectedStruct2b [16] = 3; @@ -104,8 +104,8 @@ public void PropertiesTest_Sources () // Set back to default value p.Sources = null; - Assert.IsNull (p.Sources, "Sources 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "Sources 3b"); + Assert.That (p.Sources, Is.Null, "Sources 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "Sources 3b"); // Set to more than 8 sources var ex = Assert.Throws (() => { p.Sources = new MidiThruConnectionEndpoint [9]; }, "Sources 4"); @@ -116,12 +116,12 @@ public void PropertiesTest_Sources () public void PropertiesTest_Destinations () { var p = new MidiThruConnectionParams (); - Assert.IsNull (p.Destinations, "Destinations 1"); + Assert.That (p.Destinations, Is.Null, "Destinations 1"); // Set to some array var array = new MidiThruConnectionEndpoint [] { new MidiThruConnectionEndpoint (0, 0), new MidiThruConnectionEndpoint (3, 4) }; p.Destinations = array; - CollectionAssert.AreEqual (array, p.Destinations, "Destinations 2"); + Assert.That (p.Destinations, Is.EqualTo (array), "Destinations 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [72] = 2; expectedStruct2b [84] = 3; @@ -130,8 +130,8 @@ public void PropertiesTest_Destinations () // Set back to default value p.Destinations = null; - Assert.IsNull (p.Destinations, "Destinations 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "Destinations 3b"); + Assert.That (p.Destinations, Is.Null, "Destinations 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "Destinations 3b"); // Set to more than 8 destinations var ex = Assert.Throws (() => { p.Destinations = new MidiThruConnectionEndpoint [9]; }, "Sources 4"); @@ -203,83 +203,83 @@ public void PropertiesTest_ChannelMap () public void PropertiesTest_LowVelocity () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (0, p.LowVelocity, "LowVelocity 1"); + Assert.That (p.LowVelocity, Is.EqualTo (0), "LowVelocity 1"); // Set to some value p.LowVelocity = 42; - Assert.AreEqual (42, p.LowVelocity, "LowVelocity 2"); + Assert.That (p.LowVelocity, Is.EqualTo (42), "LowVelocity 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [156] = 42; AreEqual (expectedStruct2b, GetData (p), "LowVelocity 2b"); // Set back to default value p.LowVelocity = 0; - Assert.AreEqual (0, p.LowVelocity, "LowVelocity 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "LowVelocity 3b"); + Assert.That (p.LowVelocity, Is.EqualTo (0), "LowVelocity 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "LowVelocity 3b"); } [Test] public void PropertiesTest_HighVelocity () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (0, p.HighVelocity, "HighVelocity 1"); + Assert.That (p.HighVelocity, Is.EqualTo (0), "HighVelocity 1"); // Set to some value p.HighVelocity = 42; - Assert.AreEqual (42, p.HighVelocity, "HighVelocity 2"); + Assert.That (p.HighVelocity, Is.EqualTo (42), "HighVelocity 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [157] = 42; AreEqual (expectedStruct2b, GetData (p), "HighVelocity 2b"); // Set back to default value p.HighVelocity = 0; - Assert.AreEqual (0, p.HighVelocity, "HighVelocity 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "HighVelocity 3b"); + Assert.That (p.HighVelocity, Is.EqualTo (0), "HighVelocity 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "HighVelocity 3b"); } [Test] public void PropertiesTest_LowNote () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (0, p.LowNote, "LowNote 1"); + Assert.That (p.LowNote, Is.EqualTo (0), "LowNote 1"); // Set to some value p.LowNote = 42; - Assert.AreEqual (42, p.LowNote, "LowNote 2"); + Assert.That (p.LowNote, Is.EqualTo (42), "LowNote 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [158] = 42; AreEqual (expectedStruct2b, GetData (p), "LowNote 2b"); // Set back to default value p.LowNote = 0; - Assert.AreEqual (0, p.LowNote, "LowNote 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "LowNote 3b"); + Assert.That (p.LowNote, Is.EqualTo (0), "LowNote 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "LowNote 3b"); } [Test] public void PropertiesTest_HighNote () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (127, p.HighNote, "HighNote 1"); + Assert.That (p.HighNote, Is.EqualTo (127), "HighNote 1"); // Set to some value p.HighNote = 42; - Assert.AreEqual (42, p.HighNote, "HighNote 2"); + Assert.That (p.HighNote, Is.EqualTo (42), "HighNote 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [159] = 42; AreEqual (expectedStruct2b, GetData (p), "HighNote 2b"); // Set back to default value p.HighNote = 127; - Assert.AreEqual (127, p.HighNote, "HighNote 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "HighNote 3b"); + Assert.That (p.HighNote, Is.EqualTo (127), "HighNote 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "HighNote 3b"); } [Test] public void PropertiesTest_NoteNumber () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (default (MidiTransform), p.NoteNumber, "NoteNumber 1"); + Assert.That (p.NoteNumber, Is.EqualTo (default (MidiTransform)), "NoteNumber 1"); // Set to some value var someMidiTransformType = new MidiTransform (MidiTransformType.FilterOut /* 1 */, 2); @@ -293,14 +293,14 @@ public void PropertiesTest_NoteNumber () // Set back to default value p.NoteNumber = default (MidiTransform); AreEqual (default (MidiTransform), p.NoteNumber, "NoteNumber 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "NoteNumber 3b"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "NoteNumber 3b"); } [Test] public void PropertiesTest_Velocity () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (default (MidiTransform), p.Velocity, "Velocity 1"); + Assert.That (p.Velocity, Is.EqualTo (default (MidiTransform)), "Velocity 1"); // Set to some value var someMidiTransformType = new MidiTransform (MidiTransformType.FilterOut /* 1 */, 2); @@ -314,14 +314,14 @@ public void PropertiesTest_Velocity () // Set back to default value p.Velocity = default (MidiTransform); AreEqual (default (MidiTransform), p.Velocity, "Velocity 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "Velocity 3b"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "Velocity 3b"); } [Test] public void PropertiesTest_KeyPressure () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (default (MidiTransform), p.KeyPressure, "KeyPressure 1"); + Assert.That (p.KeyPressure, Is.EqualTo (default (MidiTransform)), "KeyPressure 1"); // Set to some value var someMidiTransformType = new MidiTransform (MidiTransformType.FilterOut /* 1 */, 2); @@ -335,14 +335,14 @@ public void PropertiesTest_KeyPressure () // Set back to default value p.KeyPressure = default (MidiTransform); AreEqual (default (MidiTransform), p.KeyPressure, "KeyPressure 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "KeyPressure 3b"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "KeyPressure 3b"); } [Test] public void PropertiesTest_ChannelPressure () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (default (MidiTransform), p.ChannelPressure, "ChannelPressure 1"); + Assert.That (p.ChannelPressure, Is.EqualTo (default (MidiTransform)), "ChannelPressure 1"); // Set to some value var someMidiTransformType = new MidiTransform (MidiTransformType.FilterOut /* 1 */, 2); @@ -356,14 +356,14 @@ public void PropertiesTest_ChannelPressure () // Set back to default value p.ChannelPressure = default (MidiTransform); AreEqual (default (MidiTransform), p.ChannelPressure, "ChannelPressure 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "ChannelPressure 3b"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "ChannelPressure 3b"); } [Test] public void PropertiesTest_ProgramChange () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (default (MidiTransform), p.ProgramChange, "ProgramChange 1"); + Assert.That (p.ProgramChange, Is.EqualTo (default (MidiTransform)), "ProgramChange 1"); // Set to some value var someMidiTransformType = new MidiTransform (MidiTransformType.FilterOut /* 1 */, 2); @@ -377,14 +377,14 @@ public void PropertiesTest_ProgramChange () // Set back to default value p.ProgramChange = default (MidiTransform); AreEqual (default (MidiTransform), p.ProgramChange, "ProgramChange 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "ProgramChange 3b"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "ProgramChange 3b"); } [Test] public void PropertiesTest_PitchBend () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (default (MidiTransform), p.PitchBend, "PitchBend 1"); + Assert.That (p.PitchBend, Is.EqualTo (default (MidiTransform)), "PitchBend 1"); // Set to some value var someMidiTransformType = new MidiTransform (MidiTransformType.FilterOut /* 1 */, 2); @@ -398,116 +398,116 @@ public void PropertiesTest_PitchBend () // Set back to default value p.PitchBend = default (MidiTransform); AreEqual (default (MidiTransform), p.PitchBend, "PitchBend 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "PitchBend 3b"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "PitchBend 3b"); } [Test] public void PropertiesTest_FilterOutSysEx () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (false, p.FilterOutSysEx, "FilterOutSysEx 1"); + Assert.That (p.FilterOutSysEx, Is.EqualTo (false), "FilterOutSysEx 1"); // Set to some value p.FilterOutSysEx = true; - Assert.AreEqual (true, p.FilterOutSysEx, "FilterOutSysEx 2"); + Assert.That (p.FilterOutSysEx, Is.EqualTo (true), "FilterOutSysEx 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [184] = 0x01; AreEqual (expectedStruct2b, GetData (p), "FilterOutSysEx 2b"); // Set back to default value p.FilterOutSysEx = false; - Assert.AreEqual (false, p.FilterOutSysEx, "FilterOutSysEx 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "FilterOutSysEx 3b"); + Assert.That (p.FilterOutSysEx, Is.EqualTo (false), "FilterOutSysEx 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "FilterOutSysEx 3b"); } [Test] public void PropertiesTest_FilterOutMtc () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (false, p.FilterOutMtc, "FilterOutMtc 1"); + Assert.That (p.FilterOutMtc, Is.EqualTo (false), "FilterOutMtc 1"); // Set to some value p.FilterOutMtc = true; - Assert.AreEqual (true, p.FilterOutMtc, "FilterOutMtc 2"); + Assert.That (p.FilterOutMtc, Is.EqualTo (true), "FilterOutMtc 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [185] = 0x01; AreEqual (expectedStruct2b, GetData (p), "FilterOutMtc 2b"); // Set back to default value p.FilterOutMtc = false; - Assert.AreEqual (false, p.FilterOutMtc, "FilterOutMtc 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "FilterOutMtc 3b"); + Assert.That (p.FilterOutMtc, Is.EqualTo (false), "FilterOutMtc 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "FilterOutMtc 3b"); } [Test] public void PropertiesTest_FilterOutBeatClock () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (false, p.FilterOutBeatClock, "FilterOutBeatClock 1"); + Assert.That (p.FilterOutBeatClock, Is.EqualTo (false), "FilterOutBeatClock 1"); // Set to some value p.FilterOutBeatClock = true; - Assert.AreEqual (true, p.FilterOutBeatClock, "FilterOutBeatClock 2"); + Assert.That (p.FilterOutBeatClock, Is.EqualTo (true), "FilterOutBeatClock 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [186] = 0x01; AreEqual (expectedStruct2b, GetData (p), "FilterOutBeatClock 2b"); // Set back to default value p.FilterOutBeatClock = false; - Assert.AreEqual (false, p.FilterOutBeatClock, "FilterOutBeatClock 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "FilterOutBeatClock 3b"); + Assert.That (p.FilterOutBeatClock, Is.EqualTo (false), "FilterOutBeatClock 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "FilterOutBeatClock 3b"); } [Test] public void PropertiesTest_FilterOutTuneRequest () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (false, p.FilterOutTuneRequest, "FilterOutTuneRequest 1"); + Assert.That (p.FilterOutTuneRequest, Is.EqualTo (false), "FilterOutTuneRequest 1"); // Set to some value p.FilterOutTuneRequest = true; - Assert.AreEqual (true, p.FilterOutTuneRequest, "FilterOutTuneRequest 2"); + Assert.That (p.FilterOutTuneRequest, Is.EqualTo (true), "FilterOutTuneRequest 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [187] = 0x01; AreEqual (expectedStruct2b, GetData (p), "FilterOutTuneRequest 2b"); // Set back to default value p.FilterOutTuneRequest = false; - Assert.AreEqual (false, p.FilterOutTuneRequest, "FilterOutTuneRequest 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "FilterOutTuneRequest 3b"); + Assert.That (p.FilterOutTuneRequest, Is.EqualTo (false), "FilterOutTuneRequest 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "FilterOutTuneRequest 3b"); } [Test] public void PropertiesTest_FilterOutAllControls () { var p = new MidiThruConnectionParams (); - Assert.AreEqual (false, p.FilterOutAllControls, "FilterOutAllControls 1"); + Assert.That (p.FilterOutAllControls, Is.EqualTo (false), "FilterOutAllControls 1"); // Set to some value p.FilterOutAllControls = true; - Assert.AreEqual (true, p.FilterOutAllControls, "FilterOutAllControls 2"); + Assert.That (p.FilterOutAllControls, Is.EqualTo (true), "FilterOutAllControls 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [191] = 0x01; AreEqual (expectedStruct2b, GetData (p), "FilterOutAllControls 2b"); // Set back to default value p.FilterOutAllControls = false; - Assert.AreEqual (false, p.FilterOutAllControls, "FilterOutAllControls 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "FilterOutAllControls 3b"); + Assert.That (p.FilterOutAllControls, Is.EqualTo (false), "FilterOutAllControls 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "FilterOutAllControls 3b"); } [Test] public void PropertiesTest_Controls () { var p = new MidiThruConnectionParams (); - Assert.IsNull (p.Controls, "Controls 1"); + Assert.That (p.Controls, Is.Null, "Controls 1"); // Set to some array var transform1 = new MidiControlTransform (MidiTransformControlType.FourteenBit /* 1 */, MidiTransformControlType.FourteenBitRpn /* 3 */, 4242, MidiTransformType.MinValue /* 10 */, short.MaxValue); var transform2 = new MidiControlTransform (MidiTransformControlType.SevenBitRpn /* 2 */, MidiTransformControlType.SevenBitNRpn /* 4 */, ushort.MaxValue, MidiTransformType.MaxValue /* 11 */, 136); var array = new MidiControlTransform [] { transform1, transform2 }; p.Controls = array; - CollectionAssert.AreEqual (array, p.Controls, "Controls 2"); + Assert.That (p.Controls, Is.EqualTo (array), "Controls 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [192] = 0x02; Array.Resize (ref expectedStruct2b, 220); @@ -525,8 +525,8 @@ public void PropertiesTest_Controls () // Set back to default value p.Controls = null; - Assert.IsNull (p.Controls, "Controls 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "Controls 3b"); + Assert.That (p.Controls, Is.Null, "Controls 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "Controls 3b"); // Set to a big array; the field with the number of controls is a UInt16, so overflow by one var toobigArray = new MidiControlTransform [1 + (int) ushort.MaxValue]; @@ -536,7 +536,7 @@ public void PropertiesTest_Controls () // Set to the maximum sized array; the field with the number of maps is a UInt16, so create exactly that var bigArray = new MidiControlTransform [ushort.MaxValue]; p.Controls = bigArray; - CollectionAssert.AreEqual (bigArray, p.Controls, "Controls 5"); + Assert.That (p.Controls, Is.EqualTo (bigArray), "Controls 5"); var expectedStruct5b = DefaultStruct; expectedStruct5b [192] = 0xFF; expectedStruct5b [193] = 0xFF; // ushort.MaxValue Array.Resize (ref expectedStruct5b, 524484); @@ -547,7 +547,7 @@ public void PropertiesTest_Controls () public void PropertiesTest_Maps () { var p = new MidiThruConnectionParams (); - Assert.IsNull (p.Maps, "Maps 1"); + Assert.That (p.Maps, Is.Null, "Maps 1"); // Set to some array var valueMap1 = new byte [128]; @@ -556,7 +556,7 @@ public void PropertiesTest_Maps () valueMap2 [124] = 136; var array = new MidiValueMap [] { new MidiValueMap { Value = valueMap1 }, new MidiValueMap { Value = valueMap2 } }; p.Maps = array; - CollectionAssert.AreEqual (array, p.Maps, "Maps 2"); + Assert.That (p.Maps, Is.EqualTo (array), "Maps 2"); var expectedStruct2b = DefaultStruct; expectedStruct2b [194] = 2; Array.Resize (ref expectedStruct2b, 460); @@ -566,8 +566,8 @@ public void PropertiesTest_Maps () // Set back to default value p.Maps = null; - Assert.IsNull (p.Maps, "Maps 3"); - CollectionAssert.AreEqual (DefaultStruct, GetData (p), "Maps 3b"); + Assert.That (p.Maps, Is.Null, "Maps 3"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "Maps 3b"); // Set to a too big array; the field with the number of maps is a UInt16, so overflow by one var toobigArray = new MidiValueMap [1 + (int) ushort.MaxValue]; @@ -577,7 +577,7 @@ public void PropertiesTest_Maps () // Set to the maximum sized array; the field with the number of maps is a UInt16, so create exactly that var bigArray = new MidiValueMap [ushort.MaxValue]; p.Maps = bigArray; - CollectionAssert.AreEqual (bigArray, p.Maps, "Maps 5"); + Assert.That (p.Maps, Is.EqualTo (bigArray), "Maps 5"); var expectedStruct5b = DefaultStruct; expectedStruct5b [194] = 0xff; expectedStruct5b [195] = 0xff; // ushort.MaxValue Array.Resize (ref expectedStruct5b, 8388684); @@ -588,7 +588,7 @@ public void PropertiesTest_Maps () public void ReadStructTest_Default () { var p = SetData (DefaultStruct); - Assert.AreEqual (DefaultStruct, GetData (p), "Default"); + Assert.That (GetData (p), Is.EqualTo (DefaultStruct), "Default"); } [Test] @@ -660,7 +660,7 @@ public void ReadStructTest_LowVelocity () expectedStruct2b [156] = 42; var p = SetData (expectedStruct2b); - Assert.AreEqual (42, p.LowVelocity, "ReadStruct LowVelocity 2"); + Assert.That (p.LowVelocity, Is.EqualTo (42), "ReadStruct LowVelocity 2"); AreEqual (expectedStruct2b, GetData (p), "ReadStruct LowVelocity 2b"); } @@ -672,7 +672,7 @@ public void ReadStructTest_HighVelocity () expectedStruct2b [157] = 42; var p = SetData (expectedStruct2b); - Assert.AreEqual (42, p.HighVelocity, "ReadStruct HighVelocity 2"); + Assert.That (p.HighVelocity, Is.EqualTo (42), "ReadStruct HighVelocity 2"); AreEqual (expectedStruct2b, GetData (p), "ReadStruct HighVelocity 2b"); } @@ -684,7 +684,7 @@ public void ReadStructTest_LowNote () expectedStruct2b [158] = 42; var p = SetData (expectedStruct2b); - Assert.AreEqual (42, p.LowNote, "ReadStruct LowNote 2"); + Assert.That (p.LowNote, Is.EqualTo (42), "ReadStruct LowNote 2"); AreEqual (expectedStruct2b, GetData (p), "ReadStruct LowNote 2b"); } @@ -696,7 +696,7 @@ public void ReadStructTest_HighNode () expectedStruct2b [159] = 42; var p = SetData (expectedStruct2b); - Assert.AreEqual (42, p.HighNote, "ReadStruct HighNote 2"); + Assert.That (p.HighNote, Is.EqualTo (42), "ReadStruct HighNote 2"); AreEqual (expectedStruct2b, GetData (p), "ReadStruct HighNote 2b"); } @@ -792,7 +792,7 @@ public void ReadStructTest_FilterOutSysEx () expectedStruct2b [184] = 0x01; var p = SetData (expectedStruct2b); - Assert.AreEqual (true, p.FilterOutSysEx, "ReadStruct FilterOutSysEx 2"); + Assert.That (p.FilterOutSysEx, Is.EqualTo (true), "ReadStruct FilterOutSysEx 2"); AreEqual (expectedStruct2b, GetData (p), "ReadStruct FilterOutSysEx 2b"); } @@ -804,7 +804,7 @@ public void ReadStructTest_FilterOutMtc () expectedStruct2b [185] = 0x01; var p = SetData (expectedStruct2b); - Assert.AreEqual (true, p.FilterOutMtc, "ReadStruct FilterOutMtc 2"); + Assert.That (p.FilterOutMtc, Is.EqualTo (true), "ReadStruct FilterOutMtc 2"); AreEqual (expectedStruct2b, GetData (p), "ReadStruct FilterOutMtc 2b"); } @@ -816,7 +816,7 @@ public void ReadStructTest_FilterOutBeatClock () expectedStruct2b [186] = 0x01; var p = SetData (expectedStruct2b); - Assert.AreEqual (true, p.FilterOutBeatClock, "ReadStruct FilterOutBeatClock 2"); + Assert.That (p.FilterOutBeatClock, Is.EqualTo (true), "ReadStruct FilterOutBeatClock 2"); AreEqual (expectedStruct2b, GetData (p), "ReadStruct FilterOutBeatClock 2b"); } @@ -828,7 +828,7 @@ public void ReadStructTest_FilterOutTuneRequest () expectedStruct2b [187] = 0x01; var p = SetData (expectedStruct2b); - Assert.AreEqual (true, p.FilterOutTuneRequest, "ReadStruct FilterOutTuneRequest 2"); + Assert.That (p.FilterOutTuneRequest, Is.EqualTo (true), "ReadStruct FilterOutTuneRequest 2"); AreEqual (expectedStruct2b, GetData (p), "ReadStruct FilterOutTuneRequest 2b"); } @@ -840,7 +840,7 @@ public void ReadStructTest_FilterOutAllControls () expectedStruct2b [191] = 0x01; var p = SetData (expectedStruct2b); - Assert.AreEqual (true, p.FilterOutAllControls, "ReadStruct FilterOutAllControls 2"); + Assert.That (p.FilterOutAllControls, Is.EqualTo (true), "ReadStruct FilterOutAllControls 2"); AreEqual (expectedStruct2b, GetData (p), "ReadStruct FilterOutAllControls 2b"); } @@ -867,7 +867,7 @@ public void ReadStructTest_Controls () var transform1 = new MidiControlTransform (MidiTransformControlType.FourteenBit /* 1 */, MidiTransformControlType.FourteenBitRpn /* 3 */, 4242, MidiTransformType.MinValue /* 10 */, short.MaxValue); var transform2 = new MidiControlTransform (MidiTransformControlType.SevenBitRpn /* 2 */, MidiTransformControlType.SevenBitNRpn /* 4 */, ushort.MaxValue, MidiTransformType.MaxValue /* 11 */, 136); var array = new MidiControlTransform [] { transform1, transform2 }; - CollectionAssert.AreEqual (array, p.Controls, "ReadStruct Controls 2"); + Assert.That (p.Controls, Is.EqualTo (array), "ReadStruct Controls 2"); AreEqual (expectedStruct2b, GetData (p), "ReadStruct Controls 2b"); @@ -879,7 +879,7 @@ public void ReadStructTest_Controls () p = SetData (expectedStruct5b); var bigArray = new MidiControlTransform [ushort.MaxValue]; - CollectionAssert.AreEqual (bigArray, p.Controls, "ReadStruct Controls 5"); + Assert.That (p.Controls, Is.EqualTo (bigArray), "ReadStruct Controls 5"); AreEqual (expectedStruct5b, GetData (p), "ReadStruct Controls 5b"); } @@ -918,7 +918,7 @@ static void AreEqual (MidiThruConnectionEndpoint [] expected, MidiThruConnection { if (expected is null && actual is null) return; - Assert.AreEqual (expected.Length, actual.Length, $"Length: {message}"); + Assert.That (actual.Length, Is.EqualTo (expected.Length), $"Length: {message}"); for (var i = 0; i < expected.Length; i++) { AreEqual (expected [i], actual [i], $"Item[{i}]: {message}"); } @@ -946,7 +946,7 @@ static void AreEqual (MidiValueMap [] expected, MidiValueMap [] actual, string m { if (expected is null && actual is null) return; - Assert.AreEqual (expected.Length, actual.Length, $"Length: {message}"); + Assert.That (actual.Length, Is.EqualTo (expected.Length), $"Length: {message}"); for (var i = 0; i < expected.Length; i++) { AreEqual (expected [i].Value, actual [i].Value, $"Item[{i}]: {message}"); } @@ -1022,7 +1022,7 @@ MidiThruConnectionParams SetData (byte [] data) public void MidiValueMapTest () { var map = default (MidiValueMap); - CollectionAssert.AreEqual (new byte [128], map.Value, "Default"); + Assert.That (map.Value, Is.EqualTo (new byte [128]), "Default"); var bytes = new byte [42]; var ex = Assert.Throws (() => { map.Value = bytes; }, "Invalid byte array"); @@ -1031,7 +1031,7 @@ public void MidiValueMapTest () bytes = new byte [128]; bytes [42] = 36; map.Value = bytes; - CollectionAssert.AreEqual (bytes, map.Value, "Bytes"); + Assert.That (map.Value, Is.EqualTo (bytes), "Bytes"); } } } diff --git a/tests/monotouch-test/CoreMidi/MidiThruConnectionTests.cs b/tests/monotouch-test/CoreMidi/MidiThruConnectionTests.cs index a02d3f23ce44..0c3909756800 100644 --- a/tests/monotouch-test/CoreMidi/MidiThruConnectionTests.cs +++ b/tests/monotouch-test/CoreMidi/MidiThruConnectionTests.cs @@ -44,8 +44,8 @@ public void ConnectionCreateTest () MidiError err; using (var connection = MidiThruConnection.Create ("com.xamarin.midi", cnnParams, out err)) { - Assert.IsTrue (err == MidiError.Ok, "midi connection error"); - Assert.IsNotNull (connection, "midi connection should not be null"); + Assert.That (err == MidiError.Ok, Is.True, "midi connection error"); + Assert.That (connection, Is.Not.Null, "midi connection should not be null"); } } @@ -74,22 +74,22 @@ public void GetSetParamsTest () MidiError err; using (var connection = MidiThruConnection.Create ("com.xamarin.midi", cnnParams, out err)) { - Assert.IsTrue (err == MidiError.Ok, "midi connection error"); - Assert.IsNotNull (connection, "midi connection should not be null"); + Assert.That (err == MidiError.Ok, Is.True, "midi connection error"); + Assert.That (connection, Is.Not.Null, "midi connection should not be null"); var gotParams = connection.GetParams (out err); - Assert.IsTrue (err == MidiError.Ok, "midi connection error"); + Assert.That (err == MidiError.Ok, Is.True, "midi connection error"); // Test dynamic part of the struct - Assert.IsTrue (gotParams.Controls.Length == cnnParams.Controls.Length, "midi params objects should be the same amount"); + Assert.That (gotParams.Controls.Length == cnnParams.Controls.Length, Is.True, "midi params objects should be the same amount"); for (var i = 0; i < gotParams.Controls.Length; i++) { - Assert.AreEqual (cnnParams.Controls [i].ControlNumber, gotParams.Controls [i].ControlNumber, $"ControlNumber [{i}]"); - Assert.AreEqual (cnnParams.Controls [i].ControlType, gotParams.Controls [i].ControlType, $"ControlType [{i}]"); - Assert.AreEqual (cnnParams.Controls [i].Param, gotParams.Controls [i].Param, $"Param [{i}]"); - Assert.AreEqual (cnnParams.Controls [i].RemappedControlType, gotParams.Controls [i].RemappedControlType, $"RemappedControlType [{i}]"); - Assert.AreEqual (cnnParams.Controls [i].Transform, gotParams.Controls [i].Transform, $"Transform [{i}]"); + Assert.That (gotParams.Controls [i].ControlNumber, Is.EqualTo (cnnParams.Controls [i].ControlNumber), $"ControlNumber [{i}]"); + Assert.That (gotParams.Controls [i].ControlType, Is.EqualTo (cnnParams.Controls [i].ControlType), $"ControlType [{i}]"); + Assert.That (gotParams.Controls [i].Param, Is.EqualTo (cnnParams.Controls [i].Param), $"Param [{i}]"); + Assert.That (gotParams.Controls [i].RemappedControlType, Is.EqualTo (cnnParams.Controls [i].RemappedControlType), $"RemappedControlType [{i}]"); + Assert.That (gotParams.Controls [i].Transform, Is.EqualTo (cnnParams.Controls [i].Transform), $"Transform [{i}]"); } - Assert.IsTrue (gotParams.Maps.Length == cnnParams.Maps.Length, "midi params objects should be the same amount"); + Assert.That (gotParams.Maps.Length == cnnParams.Maps.Length, Is.True, "midi params objects should be the same amount"); for (var i = 0; i < gotParams.Maps.Length; i++) { Assert.That (cnnParams.Maps [i].Value, Is.EqualTo (gotParams.Maps [i].Value), $"Maps [{i}]"); } @@ -104,13 +104,13 @@ public void GetSetParamsTest () }; err = connection.SetParams (newParams); - Assert.IsTrue (err == MidiError.Ok, "midi connection error"); + Assert.That (err == MidiError.Ok, Is.True, "midi connection error"); gotParams = connection.GetParams (out err); - Assert.IsTrue (err == MidiError.Ok, "midi connection error"); - Assert.IsTrue (gotParams.FilterOutBeatClock, "FilterOutBeatClock should be true"); - Assert.IsFalse (gotParams.FilterOutAllControls, "FilterOutAllControls should be false"); - Assert.IsTrue (gotParams.HighNote == 5, "HighNote should be 5"); + Assert.That (err == MidiError.Ok, Is.True, "midi connection error"); + Assert.That (gotParams.FilterOutBeatClock, Is.True, "FilterOutBeatClock should be true"); + Assert.That (gotParams.FilterOutAllControls, Is.False, "FilterOutAllControls should be false"); + Assert.That (gotParams.HighNote == 5, Is.True, "HighNote should be 5"); } } @@ -137,8 +137,8 @@ public void FindTest () using (var connection1 = MidiThruConnection.Create (ownerId, cnnParams1)) using (var connection2 = MidiThruConnection.Create (ownerId, cnnParams2)) { var connections = MidiThruConnection.Find (ownerId, out var err); - Assert.IsTrue (err == MidiError.Ok, "midi connection error"); - Assert.NotNull (connections, "connections should not be null"); + Assert.That (err == MidiError.Ok, Is.True, "midi connection error"); + Assert.That (connections, Is.Not.Null, "connections should not be null"); Assert.That (connections.Length, Is.EqualTo (2), "2 midi connections expected"); } } diff --git a/tests/monotouch-test/CoreServices/FSEventStreamTest.cs b/tests/monotouch-test/CoreServices/FSEventStreamTest.cs index ecca416f30e1..a7401e0c8f32 100644 --- a/tests/monotouch-test/CoreServices/FSEventStreamTest.cs +++ b/tests/monotouch-test/CoreServices/FSEventStreamTest.cs @@ -48,11 +48,9 @@ public void TestPathsBeingWatched () var stream = createOptions.CreateStream (); - CollectionAssert.AreEqual ( - createOptions.PathsToWatch, - stream.PathsBeingWatched); + Assert.That (stream.PathsBeingWatched, Is.EqualTo (createOptions.PathsToWatch)); - Assert.AreEqual (0, stream.DeviceBeingWatched); + Assert.That (stream.DeviceBeingWatched, Is.EqualTo (0)); } [Test] @@ -66,11 +64,9 @@ public void TestPathsBeingWatchedRelativeToDevice () var stream = createOptions.CreateStream (); - CollectionAssert.AreEqual ( - createOptions.PathsToWatch, - stream.PathsBeingWatched); + Assert.That (stream.PathsBeingWatched, Is.EqualTo (createOptions.PathsToWatch)); - Assert.AreEqual (123456789, stream.DeviceBeingWatched); + Assert.That (stream.DeviceBeingWatched, Is.EqualTo (123456789)); } [Test] @@ -151,7 +147,7 @@ protected override void Dispose (bool disposing) public void Run () { SetDispatchQueue (_dispatchQueue); - Assert.IsTrue (Start ()); + Assert.That (Start (), Is.True); log.Add ($"{DateTime.Now} Started monitor"); var isWorking = true; @@ -184,13 +180,13 @@ public void Run () throw _exceptions [0]; } - Assert.IsEmpty (_createdDirectories); - Assert.IsEmpty (_createdFiles); - Assert.IsNotEmpty (_removedFiles); + Assert.That (_createdDirectories, Is.Empty); + Assert.That (_createdFiles, Is.Empty); + Assert.That (_removedFiles, Is.Not.Empty); _removedFiles.Sort (); _createdThenRemovedFiles.Sort (); - CollectionAssert.AreEqual (_createdThenRemovedFiles, _removedFiles); + Assert.That (_removedFiles, Is.EqualTo (_createdThenRemovedFiles)); Console.WriteLine ( "Observed {0} files created and then removed (flags: {1})", @@ -279,13 +275,13 @@ protected override void OnEvents (FSEvent [] events) void HandleEvent (FSEvent evnt) { log.Add ($"{DateTime.Now} HandleEvent ({evnt}) Path: {evnt.Path} Flags: {evnt.Flags}"); - Assert.IsNotNull (evnt.Path); + Assert.That (evnt.Path, Is.Not.Null); // Roslyn analyzer doesn't consider the assert above wrt nullability if (evnt.Path is null) return; if (_createFlags.HasFlag (UseExtendedData)) - Assert.Greater (evnt.FileId, 0); + Assert.That (evnt.FileId, Is.GreaterThan (0)); if (evnt.Flags.HasFlag (ItemCreated)) { if (evnt.Flags.HasFlag (ItemIsFile)) { diff --git a/tests/monotouch-test/CoreServices/HttpMessageTest.cs b/tests/monotouch-test/CoreServices/HttpMessageTest.cs index 825d1cba566b..442e1ff5bf9d 100644 --- a/tests/monotouch-test/CoreServices/HttpMessageTest.cs +++ b/tests/monotouch-test/CoreServices/HttpMessageTest.cs @@ -25,8 +25,8 @@ public void CreateEmptyTrue () { using (var m = CFHTTPMessage.CreateEmpty (true)) { Assert.That (m.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); - Assert.False (m.IsHeaderComplete, "IsHeaderComplete"); - Assert.True (m.IsRequest, "IsRequest"); + Assert.That (m.IsHeaderComplete, Is.False, "IsHeaderComplete"); + Assert.That (m.IsRequest, Is.True, "IsRequest"); Assert.Throws (delegate { var x = m.ResponseStatusCode; }, "ResponseStatusCode"); Assert.Throws (delegate { var x = m.ResponseStatusLine; }, "ResponseStatusLine"); Assert.That (m.Version.ToString (), Is.EqualTo ("1.1"), "Version"); @@ -39,8 +39,8 @@ public void CreateEmptyFalse () { using (var m = CFHTTPMessage.CreateEmpty (false)) { Assert.That (m.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); - Assert.False (m.IsHeaderComplete, "IsHeaderComplete"); - Assert.False (m.IsRequest, "IsRequest"); + Assert.That (m.IsHeaderComplete, Is.False, "IsHeaderComplete"); + Assert.That (m.IsRequest, Is.False, "IsRequest"); Assert.That (m.ResponseStatusCode, Is.EqualTo (HttpStatusCode.OK), "ResponseStatusCode"); Assert.That (m.ResponseStatusLine, Is.Empty, "ResponseStatusLine"); Assert.That (m.Version.ToString (), Is.EqualTo ("1.1"), "Version"); @@ -53,8 +53,8 @@ public void CreateRequest10 () { using (var m = CFHTTPMessage.CreateRequest (NetworkResources.XamarinUri, "GET", new Version (1, 0))) { Assert.That (m.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); - Assert.False (m.IsHeaderComplete, "IsHeaderComplete"); - Assert.True (m.IsRequest, "IsRequest"); + Assert.That (m.IsHeaderComplete, Is.False, "IsHeaderComplete"); + Assert.That (m.IsRequest, Is.True, "IsRequest"); Assert.Throws (delegate { var x = m.ResponseStatusCode; }, "ResponseStatusCode"); Assert.Throws (delegate { var x = m.ResponseStatusLine; }, "ResponseStatusLine"); Assert.That (m.Version.ToString (), Is.EqualTo ("1.0"), "Version"); @@ -68,7 +68,7 @@ public void GetAllHeaderFields () using (var m = CFHTTPMessage.CreateRequest (NetworkResources.XamarinUri, "GET", new Version (1, 1))) { m.SetHeaderFieldValue ("X-Test", "value"); var headers = m.GetAllHeaderFields (); - Assert.NotNull (headers, "headers"); + Assert.That (headers, Is.Not.Null, "headers"); Assert.That (headers.Count, Is.GreaterThan ((nuint) 0), "Count"); } } @@ -86,7 +86,7 @@ public void CreateResponseAuth () new Uri (NetworkResources.Httpbin.GetStatusCodeUrl (HttpStatusCode.Unauthorized)), "GET", null)) { request.SetBody (Array.Empty ()); // empty body, we are not interested using (var stream = CFStream.CreateForHTTPRequest (request)) { - Assert.IsNotNull (stream, "Null stream"); + Assert.That (stream, Is.Not.Null, "Null stream"); // we are only interested in the completed event stream.ClosedEvent += (sender, e) => { taskCompletionSource.SetResult (stream.GetResponseHeader ()); @@ -101,10 +101,10 @@ public void CreateResponseAuth () }, () => done); if (!done) TestRuntime.IgnoreInCI ("Transient network failure - ignore in CI"); - Assert.IsTrue (done, "Network request completed"); + Assert.That (done, Is.True, "Network request completed"); using (var auth = CFHTTPAuthentication.CreateFromResponse (response)) { - Assert.NotNull (auth, "Null Auth"); - Assert.IsTrue (auth.IsValid, "Auth is valid"); + Assert.That (auth, Is.Not.Null, "Null Auth"); + Assert.That (auth.IsValid, Is.True, "Auth is valid"); Assert.That (TestRuntime.CFGetRetainCount (auth.Handle), Is.EqualTo ((nint) 1), "RetainCount"); } } diff --git a/tests/monotouch-test/CoreText/CTFontCollectionTest.cs b/tests/monotouch-test/CoreText/CTFontCollectionTest.cs index 6e969bf338b0..0f573eff12ae 100644 --- a/tests/monotouch-test/CoreText/CTFontCollectionTest.cs +++ b/tests/monotouch-test/CoreText/CTFontCollectionTest.cs @@ -25,7 +25,7 @@ public void GetMatchingFontDescriptorsTest () return 0; }); - Assert.IsTrue (sortIsCalled, "GetMatchingFontDescriptors delegate is called"); + Assert.That (sortIsCalled, Is.True, "GetMatchingFontDescriptors delegate is called"); // Native crash (can't assert on it) if https://github.com/dotnet/macios/pull/3871 fix not present. descList.First ().GetAttributes (); @@ -38,12 +38,12 @@ public void GetMatchingFontDescriptorsCollectionOptionsTest () using (var collection = new CTFontCollection (null)) { var fd1 = collection.GetMatchingFontDescriptors (); var fd2 = collection.GetMatchingFontDescriptors (options: null); // documented to return the same thing as the parameterless if null - Assert.NotNull (fd1, "fd1"); - Assert.NotNull (fd2, "fd2"); - Assert.AreEqual (fd1.Length, fd2.Length, "equal collections"); + Assert.That (fd1, Is.Not.Null, "fd1"); + Assert.That (fd2, Is.Not.Null, "fd2"); + Assert.That (fd2.Length, Is.EqualTo (fd1.Length), "equal collections"); var fd3 = collection.GetMatchingFontDescriptors (new CTFontCollectionOptions { RemoveDuplicates = true }); - Assert.NotNull (fd3, "fd3"); + Assert.That (fd3, Is.Not.Null, "fd3"); } } } diff --git a/tests/monotouch-test/CoreText/CTFontGetAvailableTablesTest.cs b/tests/monotouch-test/CoreText/CTFontGetAvailableTablesTest.cs index ff8e83e6dde5..cc33f4c32f08 100644 --- a/tests/monotouch-test/CoreText/CTFontGetAvailableTablesTest.cs +++ b/tests/monotouch-test/CoreText/CTFontGetAvailableTablesTest.cs @@ -18,7 +18,7 @@ public void GetAvailableTables () { using var font = new CTFont ("Helvetica", 12); var tables = font.GetAvailableTables (CTFontTableOptions.None); - Assert.IsNotNull (tables, "tables"); + Assert.That (tables, Is.Not.Null, "tables"); Assert.That (tables.Length, Is.GreaterThan (0), "tables/length"); } } diff --git a/tests/monotouch-test/CoreText/CTFrameTests.cs b/tests/monotouch-test/CoreText/CTFrameTests.cs index 021a3a415da3..6b7b8537c11f 100644 --- a/tests/monotouch-test/CoreText/CTFrameTests.cs +++ b/tests/monotouch-test/CoreText/CTFrameTests.cs @@ -37,10 +37,10 @@ public void CTTypesetterCreateTest () using (var framesetter = new CTFramesetter (new NSAttributedString ("Testing, testing, 1, 2, 3..."))) using (var type = framesetter.GetTypesetter ()) using (var newFrame = CTFramesetter.Create (type)) { - Assert.NotNull (type, "Create"); + Assert.That (type, Is.Not.Null, "Create"); var type2 = newFrame.GetTypesetter (); - Assert.NotNull (type, "type2"); - Assert.AreEqual (type.Handle, type2.Handle, "Same typesetter"); + Assert.That (type, Is.Not.Null, "type2"); + Assert.That (type2.Handle, Is.EqualTo (type.Handle), "Same typesetter"); } } } diff --git a/tests/monotouch-test/CoreText/CTLineTest.cs b/tests/monotouch-test/CoreText/CTLineTest.cs index f2e9d3f2420e..bb8b84e1e60f 100644 --- a/tests/monotouch-test/CoreText/CTLineTest.cs +++ b/tests/monotouch-test/CoreText/CTLineTest.cs @@ -41,7 +41,7 @@ public void EnumerateCaretOffsets () line.EnumerateCaretOffsets ((double o, nint charIndex, bool leadingEdge, ref bool stop) => { executed = true; }); - Assert.IsTrue (executed); + Assert.That (executed, Is.True); } [Test] @@ -49,7 +49,7 @@ public void GetImageBounds () { using (var a = new NSAttributedString ()) using (var l = new CTLine (a)) { - Assert.True (l.GetImageBounds (null).IsEmpty, "GetImageBounds"); + Assert.That (l.GetImageBounds (null).IsEmpty, Is.True, "GetImageBounds"); } } } diff --git a/tests/monotouch-test/CoreText/CTParagraphStyleTests.cs b/tests/monotouch-test/CoreText/CTParagraphStyleTests.cs index 770ad15462f9..90dfa1e7438a 100644 --- a/tests/monotouch-test/CoreText/CTParagraphStyleTests.cs +++ b/tests/monotouch-test/CoreText/CTParagraphStyleTests.cs @@ -42,24 +42,24 @@ public void StylePropertiesTest () var style = new CTParagraphStyle (settings); Assert.DoesNotThrow (() => { - Assert.AreEqual (settings.TailIndent, (nfloat) style.TailIndent, "TailIndent"); - Assert.AreEqual (settings.ParagraphSpacingBefore, (nfloat) style.ParagraphSpacingBefore, "ParagraphSpacingBefore"); - Assert.AreEqual (settings.ParagraphSpacing, (nfloat) style.ParagraphSpacing, "ParagraphSpacing"); - Assert.AreEqual (settings.LineSpacing, (nfloat) style.LineSpacing, "LineSpacing"); - Assert.AreEqual (settings.MinimumLineHeight, (nfloat) style.MinimumLineHeight, "MinimumLineHeight"); - Assert.AreEqual (settings.MaximumLineHeight, (nfloat) style.MaximumLineHeight, "MaximumLineHeight"); - Assert.AreEqual (settings.LineHeightMultiple, (nfloat) style.LineHeightMultiple, "LineHeightMultiple"); - Assert.AreEqual (settings.DefaultTabInterval, (nfloat) style.DefaultTabInterval, "DefaultTabInterval"); - Assert.AreEqual (settings.HeadIndent, (nfloat) style.HeadIndent, "HeadIndent"); - Assert.AreEqual (settings.FirstLineHeadIndent, (nfloat) style.FirstLineHeadIndent, "FirstLineHeadIndent"); - Assert.AreEqual (settings.LineBreakMode, style.LineBreakMode, "LineBreakMode"); - Assert.AreEqual (settings.BaseWritingDirection, style.BaseWritingDirection, "LineBreakMode"); - Assert.AreEqual (settings.Alignment, style.Alignment, "Alignment"); + Assert.That ((nfloat) style.TailIndent, Is.EqualTo (settings.TailIndent), "TailIndent"); + Assert.That ((nfloat) style.ParagraphSpacingBefore, Is.EqualTo (settings.ParagraphSpacingBefore), "ParagraphSpacingBefore"); + Assert.That ((nfloat) style.ParagraphSpacing, Is.EqualTo (settings.ParagraphSpacing), "ParagraphSpacing"); + Assert.That ((nfloat) style.LineSpacing, Is.EqualTo (settings.LineSpacing), "LineSpacing"); + Assert.That ((nfloat) style.MinimumLineHeight, Is.EqualTo (settings.MinimumLineHeight), "MinimumLineHeight"); + Assert.That ((nfloat) style.MaximumLineHeight, Is.EqualTo (settings.MaximumLineHeight), "MaximumLineHeight"); + Assert.That ((nfloat) style.LineHeightMultiple, Is.EqualTo (settings.LineHeightMultiple), "LineHeightMultiple"); + Assert.That ((nfloat) style.DefaultTabInterval, Is.EqualTo (settings.DefaultTabInterval), "DefaultTabInterval"); + Assert.That ((nfloat) style.HeadIndent, Is.EqualTo (settings.HeadIndent), "HeadIndent"); + Assert.That ((nfloat) style.FirstLineHeadIndent, Is.EqualTo (settings.FirstLineHeadIndent), "FirstLineHeadIndent"); + Assert.That (style.LineBreakMode, Is.EqualTo (settings.LineBreakMode), "LineBreakMode"); + Assert.That (style.BaseWritingDirection, Is.EqualTo (settings.BaseWritingDirection), "LineBreakMode"); + Assert.That (style.Alignment, Is.EqualTo (settings.Alignment), "Alignment"); var styleTabStops = style.GetTabStops (); - Assert.AreEqual (settings.TabStops.Count (), styleTabStops.Length, "TabStops"); - Assert.True (styleTabStops.Any (t => t.Location == 2 && t.TextAlignment == CTTextAlignment.Justified)); - Assert.True (styleTabStops.Any (t => t.Location == 1 && t.TextAlignment == CTTextAlignment.Natural)); + Assert.That (styleTabStops.Length, Is.EqualTo (settings.TabStops.Count ()), "TabStops"); + Assert.That (styleTabStops.Any (t => t.Location == 2 && t.TextAlignment == CTTextAlignment.Justified), Is.True, "Has Justified tab at 2"); + Assert.That (styleTabStops.Any (t => t.Location == 1 && t.TextAlignment == CTTextAlignment.Natural), Is.True, "Has Natural tab at 1"); }); } } diff --git a/tests/monotouch-test/CoreText/FontDescriptorTest.cs b/tests/monotouch-test/CoreText/FontDescriptorTest.cs index 3bae08d6a4a7..cfbbf130eaf9 100644 --- a/tests/monotouch-test/CoreText/FontDescriptorTest.cs +++ b/tests/monotouch-test/CoreText/FontDescriptorTest.cs @@ -40,7 +40,7 @@ public void FromAttributes () Assert.That (font.FullName, Is.EqualTo ("Courier Bold"), "FullName"); Assert.That (font.Size, Is.EqualTo ((nfloat) 16), "Size"); // that changed in iOS 8.3, there's an undocumented flag + MonoSpace (make sense) + bold - Assert.True ((font.SymbolicTraits & CTFontSymbolicTraits.Bold) != 0, "SymbolicTraits"); + Assert.That ((font.SymbolicTraits & CTFontSymbolicTraits.Bold) != 0, Is.True, "SymbolicTraits"); } } @@ -82,8 +82,8 @@ public void MatchFontDescriptors () var rv = CTFontDescriptor.MatchFontDescriptors (new CTFontDescriptor [] { desc1 }, null, (CTFontDescriptorMatchingState state, CTFontDescriptorMatchingProgress progress) => { try { if (state == CTFontDescriptorMatchingState.Finished) { - Assert.AreEqual (1, progress.Result.Length, "Result.Length"); - Assert.AreEqual (fda1.Name, progress.Result [0].GetAttributes ().Name, "Result[0].Name"); + Assert.That (progress.Result.Length, Is.EqualTo (1), "Result.Length"); + Assert.That (progress.Result [0].GetAttributes ().Name, Is.EqualTo (fda1.Name), "Result[0].Name"); tcs.TrySetResult (true); } } catch (Exception e) { @@ -91,7 +91,7 @@ public void MatchFontDescriptors () } return true; }); - Assert.IsTrue (rv, "Return value"); + Assert.That (rv, Is.True, "Return value"); TestRuntime.RunAsync (TimeSpan.FromSeconds (30), tcs.Task); } diff --git a/tests/monotouch-test/CoreText/FontManagerTest.cs b/tests/monotouch-test/CoreText/FontManagerTest.cs index 072bb530ed46..4113bd7bea19 100644 --- a/tests/monotouch-test/CoreText/FontManagerTest.cs +++ b/tests/monotouch-test/CoreText/FontManagerTest.cs @@ -47,23 +47,23 @@ public void RegisterTTF () { using (var url = NSUrl.FromFilename (pacifico_ttf_path)) { var err = CTFontManager.RegisterFontsForUrl (url, CTFontManagerScope.Process); - Assert.IsNull (err, "err 1"); + Assert.That (err, Is.Null, "err 1"); err = CTFontManager.UnregisterFontsForUrl (url, CTFontManagerScope.Process); - Assert.IsNull (err, "err 2"); + Assert.That (err, Is.Null, "err 2"); } using (var url = NSUrl.FromFilename (non_existent_path)) { var err = CTFontManager.RegisterFontsForUrl (url, CTFontManagerScope.Process); // xcode 11 beta 4 stopped reporting errors - // Assert.IsNotNull (err, "err 3"); + // Assert.That (err, Is.Not.Null, "err 3"); err = CTFontManager.UnregisterFontsForUrl (url, CTFontManagerScope.Process); #if MONOMAC || __MACCATALYST__ if (TestRuntime.CheckXcodeVersion (12, 2)) - Assert.IsNotNull (err, "err 4"); + Assert.That (err, Is.Not.Null, "err 4"); else - Assert.IsNull (err, "err 4"); + Assert.That (err, Is.Null, "err 4"); #else - Assert.IsNotNull (err, "err 4"); + Assert.That (err, Is.Not.Null, "err 4"); #endif } } @@ -105,16 +105,16 @@ public void RegisterFonts_NoCallback () static bool SuccessDone (NSError [] errors, bool done) { Assert.That (errors.Length, Is.EqualTo (0), "errors"); - Assert.True (done, "done"); + Assert.That (done, Is.True, "done"); return true; } static bool FailureDone (NSError [] errors, bool done) { Assert.That (errors.Length, Is.EqualTo (1), "errors"); - Assert.True (errors [0].UserInfo.TryGetValue (CTFontManagerErrorKeys.FontUrlsKey, out var urls), "FontUrlsKey"); - Assert.True ((urls as NSArray).GetItem (0).AbsoluteString.EndsWith ("NonExistent.ttf", StringComparison.Ordinal), "NonExistent"); - Assert.True (done, "done"); + Assert.That (errors [0].UserInfo.TryGetValue (CTFontManagerErrorKeys.FontUrlsKey, out var urls), Is.True, "FontUrlsKey"); + Assert.That ((urls as NSArray).GetItem (0).AbsoluteString.EndsWith ("NonExistent.ttf", StringComparison.Ordinal), Is.True, "NonExistent"); + Assert.That (done, Is.True, "done"); return true; } @@ -142,29 +142,29 @@ public void RegisterTTFs () { using (var url = NSUrl.FromFilename (pacifico_ttf_path)) { var err = CTFontManager.RegisterFontsForUrl (new [] { url }, CTFontManagerScope.Process); - Assert.IsNull (err, "err 1"); + Assert.That (err, Is.Null, "err 1"); err = CTFontManager.UnregisterFontsForUrl (new [] { url }, CTFontManagerScope.Process); - Assert.IsNull (err, "err 2"); + Assert.That (err, Is.Null, "err 2"); } using (var url = NSUrl.FromFilename (non_existent_path)) { var err = CTFontManager.RegisterFontsForUrl (new [] { url }, CTFontManagerScope.Process); // xcode 11 beta 4 stopped reporting errors - // Assert.IsNotNull (err, "err 3"); - // Assert.AreEqual (1, err.Length, "err 3 l"); - // Assert.IsNotNull (err [0], "err 3[0]"); + // Assert.That (err, Is.Not.Null, "err 3"); + // Assert.That (err.Length, Is.EqualTo (1), "err 3 l"); + // Assert.That (err [0], Is.Not.Null, "err 3[0]"); err = CTFontManager.UnregisterFontsForUrl (new [] { url }, CTFontManagerScope.Process); #if MONOMAC || __MACCATALYST__ if (TestRuntime.CheckXcodeVersion (12, 2)) { - Assert.IsNotNull (err, "err 4"); - Assert.AreEqual (1, err.Length, "err 4 l"); - Assert.IsNotNull (err [0], "err 4[0]"); + Assert.That (err, Is.Not.Null, "err 4"); + Assert.That (err.Length, Is.EqualTo (1), "err 4 l"); + Assert.That (err [0], Is.Not.Null, "err 4[0]"); } else - Assert.IsNull (err, "err 4"); + Assert.That (err, Is.Null, "err 4"); #else - Assert.IsNotNull (err, "err 4"); - Assert.AreEqual (1, err.Length, "err 4 l"); - Assert.IsNotNull (err [0], "err 4[0]"); + Assert.That (err, Is.Not.Null, "err 4"); + Assert.That (err.Length, Is.EqualTo (1), "err 4 l"); + Assert.That (err [0], Is.Not.Null, "err 4[0]"); #endif } } @@ -216,7 +216,7 @@ public void RegisterFontDescriptors_WithCallback () var array = new [] { fd }; CTFontManager.RegisterFontDescriptors (array, CTFontManagerScope.Process, true, (NSError [] errors, bool done) => { try { - Assert.True (done, "done: RegisterFontDescriptors"); + Assert.That (done, Is.True, "done: RegisterFontDescriptors"); } catch (Exception e) { ex = e; } @@ -226,7 +226,7 @@ public void RegisterFontDescriptors_WithCallback () CTFontManager.UnregisterFontDescriptors (array, CTFontManagerScope.Process, (NSError [] errors, bool done) => { try { - Assert.True (done, "done: UnregisterFontDescriptors"); + Assert.That (done, Is.True, "done: UnregisterFontDescriptors"); } catch (Exception e) { ex = e; } @@ -250,15 +250,15 @@ public void GetFontsPresent () var url = NSUrl.FromFilename (pacifico_ttf_path); var err = CTFontManager.RegisterFontsForUrl (url, CTFontManagerScope.Process); - Assert.IsNull (err, "Register error"); + Assert.That (err, Is.Null, "Register error"); // method under test var fonts = CTFontManager.GetFonts (url); - Assert.AreEqual (1, fonts.Length); - Assert.AreEqual ("Pacifico", fonts [0].GetAttributes ().Name?.ToString ()); + Assert.That (fonts.Length, Is.EqualTo (1)); + Assert.That (fonts [0].GetAttributes ().Name?.ToString (), Is.EqualTo ("Pacifico")); err = CTFontManager.UnregisterFontsForUrl (url, CTFontManagerScope.Process); - Assert.IsNull (err, "Unregister error"); + Assert.That (err, Is.Null, "Unregister error"); } [Test] @@ -268,7 +268,7 @@ public void GetFontsMissing () using (var url = NSUrl.FromFilename (non_existent_path)) { var fonts = CTFontManager.GetFonts (url); - Assert.AreEqual (0, fonts.Length); + Assert.That (fonts.Length, Is.EqualTo (0)); } } @@ -278,10 +278,10 @@ public void CreateFontDescriptor () Assert.Throws (() => CTFontManager.CreateFontDescriptor (null), "null"); using (var data = NSData.FromFile (pacifico_ttf_path)) - Assert.NotNull (CTFontManager.CreateFontDescriptor (data), "font"); + Assert.That (CTFontManager.CreateFontDescriptor (data), Is.Not.Null, "font"); using (var data = NSData.FromFile (tamarin_pdf_path)) - Assert.Null (CTFontManager.CreateFontDescriptor (data), "not a font"); + Assert.That (CTFontManager.CreateFontDescriptor (data), Is.Null, "not a font"); } [Test] @@ -320,7 +320,7 @@ public void RequestFonts () Assert.That (unresolved.Length, Is.EqualTo (0), "all resolved"); callback = true; }); - Assert.True (callback, "callback"); + Assert.That (callback, Is.True, "callback"); } } #endif diff --git a/tests/monotouch-test/CoreText/FontTest.cs b/tests/monotouch-test/CoreText/FontTest.cs index bc18e97eb113..932d026959b6 100644 --- a/tests/monotouch-test/CoreText/FontTest.cs +++ b/tests/monotouch-test/CoreText/FontTest.cs @@ -57,7 +57,7 @@ public void GetCascadeList () TestRuntime.AssertXcodeVersion (5, 0); using (var font = new CTFont ("HoeflerText-Regular", 10, CTFontOptions.Default)) { - Assert.NotNull (font.GetDefaultCascadeList (null), "null"); + Assert.That (font.GetDefaultCascadeList (null), Is.Not.Null, "null"); } } @@ -67,7 +67,7 @@ public void GetLocalizedName () TestRuntime.AssertXcodeVersion (5, 0); using (var font = new CTFont ("HoeflerText-Regular", 10, CTFontOptions.Default)) { - Assert.NotNull (font.GetLocalizedName (CTFontNameKey.Copyright), "1"); + Assert.That (font.GetLocalizedName (CTFontNameKey.Copyright), Is.Not.Null, "1"); // We need to check if we are using english as our main language since this is the known case // that the following code works. It fails with spanish for example but it is a false positive @@ -75,8 +75,8 @@ public void GetLocalizedName () var language = NSLocale.PreferredLanguages [0]; if (language == "en") { string str; - Assert.NotNull (font.GetLocalizedName (CTFontNameKey.Full, out str), "2"); - Assert.NotNull (str, "out str"); + Assert.That (font.GetLocalizedName (CTFontNameKey.Full, out str), Is.Not.Null, "2"); + Assert.That (str, Is.Not.Null, "out str"); } } } @@ -87,7 +87,7 @@ public void GetGlyphsForCharacters_35048 () using (var font = CreateAppleColorEmojiFont ()) using (var ctfont = font.ToCTFont ((nfloat) 10.0)) { ushort [] gid = new ushort [2]; - Assert.True (ctfont.GetGlyphsForCharacters ("\ud83d\ude00".ToCharArray (), gid), "GetGlyphsForCharacters"); + Assert.That (ctfont.GetGlyphsForCharacters ("\ud83d\ude00".ToCharArray (), gid), Is.True, "GetGlyphsForCharacters"); Assert.That (gid [0], Is.Not.EqualTo (0), "0"); Assert.That (gid [1], Is.EqualTo (0), "1"); } @@ -135,7 +135,7 @@ public void CTFontCopyNameForGlyph () using (var font = CreateAppleColorEmojiFont ()) using (var ctfont = font.ToCTFont ((nfloat) 10.0)) - Assert.Null (ctfont.GetGlyphName ('\ud83d'), "2"); + Assert.That (ctfont.GetGlyphName ('\ud83d'), Is.Null, "2"); } [Test] @@ -148,7 +148,7 @@ public void DrawImage () using var space = CGColorSpace.CreateDeviceRGB (); using var context = new CGBitmapContext (null, 10, 10, 8, 40, space, CGBitmapFlags.PremultipliedLast); font.DrawImage (provider, CGPoint.Empty, context); - Assert.AreEqual (1, provider.Count, "#Count"); + Assert.That (provider.Count, Is.EqualTo (1), "#Count"); } [Test] @@ -164,7 +164,7 @@ public void GetTypographicBoundsForAdaptiveImageProvider () new CGRect (0, -3.90625, 35, 16.40625) }; Assert.That (bounds, Is.AnyOf (candidates).Using ((x, y) => x == y), "Bounds"); - Assert.AreEqual (0, provider.Count, "#Count"); + Assert.That (provider.Count, Is.EqualTo (0), "#Count"); } [Test] @@ -172,7 +172,7 @@ public void GetAttribute () { using (var font = new CTFont ("HoeflerText-Regular", 10, CTFontOptions.Default)) { using (var name = font.GetAttribute (CTFontDescriptorAttributeKey.Name)) { - Assert.NotNull (name, "Name"); + Assert.That (name, Is.Not.Null, "Name"); } } } @@ -193,7 +193,7 @@ public void GetVariationAxes () { using (var font = new CTFont ("HoeflerText-Regular", 10)) { var axes = font.GetVariationAxes (); - Assert.IsNotNull (axes, "axes"); + Assert.That (axes, Is.Not.Null, "axes"); // HoeflerText-Regular has no variation axes, so we expect an empty array Assert.That (axes.Length, Is.EqualTo (0), "Length"); } diff --git a/tests/monotouch-test/CoreText/RunTest.cs b/tests/monotouch-test/CoreText/RunTest.cs index 5571d4677ed7..53bb161f7900 100644 --- a/tests/monotouch-test/CoreText/RunTest.cs +++ b/tests/monotouch-test/CoreText/RunTest.cs @@ -48,7 +48,7 @@ public void CustomOps () { using (var o = new MyOps ()) using (var d = new CTRunDelegate (o)) { - Assert.AreSame (o, d.Operations, "same"); + Assert.That (d.Operations, Is.SameAs (o), "same"); } } @@ -62,9 +62,9 @@ public void Runs () }; mas.SetAttributes (sa, new NSRange (3, 3)); using (var fs = new CTFramesetter (mas)) { - Assert.True (MyOps.Ascent, "Ascent called"); - Assert.True (MyOps.Descent, "Descent called"); - Assert.True (MyOps.Width, "Width called"); + Assert.That (MyOps.Ascent, Is.True, "Ascent called"); + Assert.That (MyOps.Descent, Is.True, "Descent called"); + Assert.That (MyOps.Width, Is.True, "Width called"); } } } @@ -79,8 +79,8 @@ public void GetBaseAdvancesAndOrigins () var runs = line.GetGlyphRuns (); Assert.That (runs.Length, Is.EqualTo (1), "runs"); runs [0].GetBaseAdvancesAndOrigins (new NSRange (0, 10), out var advances, out var origins); - Assert.IsNotNull (advances, "advances"); - Assert.IsNotNull (origins, "origins"); + Assert.That (advances, Is.Not.Null, "advances"); + Assert.That (origins, Is.Not.Null, "origins"); } } } diff --git a/tests/monotouch-test/CoreText/StringAttributes.cs b/tests/monotouch-test/CoreText/StringAttributes.cs index e0dac19f34d9..21781eaec66e 100644 --- a/tests/monotouch-test/CoreText/StringAttributes.cs +++ b/tests/monotouch-test/CoreText/StringAttributes.cs @@ -31,9 +31,9 @@ public void NoCTLine () sa.UnderlineColor = UIColor.Blue.CGColor; sa.UnderlineStyleModifiers = CTUnderlineStyleModifiers.PatternDashDotDot; - Assert.IsNull (sa.BaselineClass, "#0"); + Assert.That (sa.BaselineClass, Is.Null, "#0"); sa.BaselineClass = CTBaselineClass.IdeographicHigh; - Assert.AreEqual (CTBaselineClass.IdeographicHigh, sa.BaselineClass, "#1"); + Assert.That (sa.BaselineClass, Is.EqualTo (CTBaselineClass.IdeographicHigh), "#1"); sa.SetBaselineInfo (CTBaselineClass.Roman, 13); sa.SetBaselineInfo (CTBaselineClass.IdeographicHigh, 3); @@ -45,7 +45,7 @@ public void NoCTLine () AdaptiveImageProvider? provider = null; if (TestRuntime.CheckXcodeVersion (16, 0)) { sa.AdaptiveImageProvider = provider = new AdaptiveImageProvider (); - Assert.AreSame (provider, sa.AdaptiveImageProvider, "AdaptiveImageProvider"); + Assert.That (sa.AdaptiveImageProvider, Is.SameAs (provider), "AdaptiveImageProvider"); } } @@ -59,9 +59,9 @@ public void SimpleValuesSet () sa.UnderlineColor = UIColor.Blue.CGColor; sa.UnderlineStyleModifiers = CTUnderlineStyleModifiers.PatternDashDotDot; - Assert.IsNull (sa.BaselineClass, "#0"); + Assert.That (sa.BaselineClass, Is.Null, "#0"); sa.BaselineClass = CTBaselineClass.IdeographicHigh; - Assert.AreEqual (CTBaselineClass.IdeographicHigh, sa.BaselineClass, "#1"); + Assert.That (sa.BaselineClass, Is.EqualTo (CTBaselineClass.IdeographicHigh), "#1"); // Calling sa.SetBaselineInfo makes the CTLine ctor crash (https://github.com/xamarin/maccore/issues/2947) // so don't do that here. @@ -101,7 +101,7 @@ public void SimpleValuesSet () } if (TestRuntime.CheckXcodeVersion (16, 0)) - Assert.AreEqual (1, provider!.Count, "AdaptiveImageProvider #0"); + Assert.That (provider!.Count, Is.EqualTo (1), "AdaptiveImageProvider #0"); attributedString = new NSAttributedString ("🙈`", sa); using (var textLine = new CTLine (attributedString)) { @@ -109,7 +109,7 @@ public void SimpleValuesSet () } if (TestRuntime.CheckXcodeVersion (16, 0)) - Assert.AreEqual (2, provider!.Count, "AdaptiveImageProvider #1"); + Assert.That (provider!.Count, Is.EqualTo (2), "AdaptiveImageProvider #1"); #if MONOMAC img.UnlockFocus (); diff --git a/tests/monotouch-test/CoreVideo/CVDisplayLinkTest.cs b/tests/monotouch-test/CoreVideo/CVDisplayLinkTest.cs index 63d9d99d287a..35b5e56c690e 100644 --- a/tests/monotouch-test/CoreVideo/CVDisplayLinkTest.cs +++ b/tests/monotouch-test/CoreVideo/CVDisplayLinkTest.cs @@ -14,8 +14,8 @@ public void CreateFromDisplayIdValidIdTest () TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 12, 0); Assert.DoesNotThrow (() => { using var displayLink = CVDisplayLink.CreateFromDisplayId ((uint) CGDisplay.MainDisplayID); - Assert.NotNull (displayLink, "Not null"); - Assert.AreEqual (CGDisplay.MainDisplayID, displayLink.GetCurrentDisplay (), "DisplayId"); + Assert.That (displayLink, Is.Not.Null, "Not null"); + Assert.That (displayLink.GetCurrentDisplay (), Is.EqualTo (CGDisplay.MainDisplayID), "DisplayId"); }, "Throws"); } @@ -25,7 +25,7 @@ public void CreateFromDisplayWrongIdTest () TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 12, 0); Assert.DoesNotThrow (() => { using var displayLink = CVDisplayLink.CreateFromDisplayId (UInt32.MaxValue); - Assert.Null (displayLink, "null"); + Assert.That (displayLink, Is.Null, "null"); }, "Throws"); } @@ -37,7 +37,7 @@ public void CreateFromDisplayIdsTest () // with a single one, there is nothing in the docs that say that we cannot do that Assert.DoesNotThrow (() => { using var displayLink = CVDisplayLink.CreateFromDisplayIds (new [] { (uint) CGDisplay.MainDisplayID }); - Assert.NotNull (displayLink, "Not null"); + Assert.That (displayLink, Is.Not.Null, "Not null"); }, "Throws"); } @@ -48,7 +48,7 @@ public void CreateFromOpenGLMaskTest () var openGLMask = CGDisplay.GetOpenGLDisplayMask (CGDisplay.MainDisplayID); Assert.DoesNotThrow (() => { using var displayLink = CVDisplayLink.CreateFromOpenGLMask ((uint) openGLMask); - Assert.NotNull (displayLink, "Not null"); + Assert.That (displayLink, Is.Not.Null, "Not null"); }, "Throws"); } @@ -80,7 +80,7 @@ public void GetCurrentDisplayTest () TestRuntime.IgnoreIfLockedScreen (); Assert.DoesNotThrow (() => { using var displayLink = new CVDisplayLink (); - Assert.AreEqual (CGDisplay.MainDisplayID, displayLink.GetCurrentDisplay ()); + Assert.That (displayLink.GetCurrentDisplay (), Is.EqualTo (CGDisplay.MainDisplayID)); }); } @@ -107,7 +107,7 @@ public void TryTranslateTimeValidTest () // it has to be running else you will get a crash if (displayLink.Start () == 0) { displayLink.GetCurrentTime (out var timeStamp); - Assert.True (displayLink.TryTranslateTime (timeStamp, ref outTime)); + Assert.That (displayLink.TryTranslateTime (timeStamp, ref outTime), Is.True); displayLink.Stop (); } } diff --git a/tests/monotouch-test/CoreVideo/CVImageBufferTests.cs b/tests/monotouch-test/CoreVideo/CVImageBufferTests.cs index 6fb930980c42..a6e30a3fd5eb 100644 --- a/tests/monotouch-test/CoreVideo/CVImageBufferTests.cs +++ b/tests/monotouch-test/CoreVideo/CVImageBufferTests.cs @@ -22,19 +22,19 @@ public void CVImageBufferYCbCrMatrixTest () var codepoint = CVImageBuffer.GetCodePoint (CVImageBufferYCbCrMatrix.ItuR2020); var matrixOption = CVImageBuffer.GetYCbCrMatrixOption (codepoint); - Assert.AreEqual (CVImageBufferYCbCrMatrix.ItuR2020, matrixOption, "ItuR2020"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferYCbCrMatrix.ItuR2020), "ItuR2020"); codepoint = CVImageBuffer.GetCodePoint (CVImageBufferYCbCrMatrix.ItuR601_4); matrixOption = CVImageBuffer.GetYCbCrMatrixOption (codepoint); - Assert.AreEqual (CVImageBufferYCbCrMatrix.ItuR601_4, matrixOption, "ItuR601_4"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferYCbCrMatrix.ItuR601_4), "ItuR601_4"); codepoint = CVImageBuffer.GetCodePoint (CVImageBufferYCbCrMatrix.ItuR709_2); matrixOption = CVImageBuffer.GetYCbCrMatrixOption (codepoint); - Assert.AreEqual (CVImageBufferYCbCrMatrix.ItuR709_2, matrixOption, "ItuR709_2"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferYCbCrMatrix.ItuR709_2), "ItuR709_2"); codepoint = CVImageBuffer.GetCodePoint (CVImageBufferYCbCrMatrix.Smpte240M1995); matrixOption = CVImageBuffer.GetYCbCrMatrixOption (codepoint); - Assert.AreEqual (CVImageBufferYCbCrMatrix.Smpte240M1995, matrixOption, "Smpte240M1995"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferYCbCrMatrix.Smpte240M1995), "Smpte240M1995"); } [Test] @@ -44,23 +44,23 @@ public void CVImageBufferColorPrimariesTest () var codepoint = CVImageBuffer.GetCodePoint (CVImageBufferColorPrimaries.ItuR2020); var matrixOption = CVImageBuffer.GetColorPrimariesOption (codepoint); - Assert.AreEqual (CVImageBufferColorPrimaries.ItuR2020, matrixOption, "ItuR2020"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferColorPrimaries.ItuR2020), "ItuR2020"); codepoint = CVImageBuffer.GetCodePoint (CVImageBufferColorPrimaries.Ebu3213); matrixOption = CVImageBuffer.GetColorPrimariesOption (codepoint); - Assert.AreEqual (CVImageBufferColorPrimaries.Ebu3213, matrixOption, "Ebu3213"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferColorPrimaries.Ebu3213), "Ebu3213"); codepoint = CVImageBuffer.GetCodePoint (CVImageBufferColorPrimaries.ItuR709_2); matrixOption = CVImageBuffer.GetColorPrimariesOption (codepoint); - Assert.AreEqual (CVImageBufferColorPrimaries.ItuR709_2, matrixOption, "ItuR709_2"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferColorPrimaries.ItuR709_2), "ItuR709_2"); codepoint = CVImageBuffer.GetCodePoint (CVImageBufferColorPrimaries.P22); matrixOption = CVImageBuffer.GetColorPrimariesOption (codepoint); - Assert.AreEqual (CVImageBufferColorPrimaries.P22, matrixOption, "P22"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferColorPrimaries.P22), "P22"); codepoint = CVImageBuffer.GetCodePoint (CVImageBufferColorPrimaries.SmpteC); matrixOption = CVImageBuffer.GetColorPrimariesOption (codepoint); - Assert.AreEqual (CVImageBufferColorPrimaries.SmpteC, matrixOption, "SmpteC"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferColorPrimaries.SmpteC), "SmpteC"); } [Test] @@ -70,23 +70,23 @@ public void CVImageBufferTransferFunctionTest () var codepoint = CVImageBuffer.GetCodePoint (CVImageBufferTransferFunction.ItuR2100Hlg); var matrixOption = CVImageBuffer.GetTransferFunctionOption (codepoint); - Assert.AreEqual (CVImageBufferTransferFunction.ItuR2100Hlg, matrixOption, "ItuR2100Hlg"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferTransferFunction.ItuR2100Hlg), "ItuR2100Hlg"); codepoint = CVImageBuffer.GetCodePoint (CVImageBufferTransferFunction.ItuR709_2); matrixOption = CVImageBuffer.GetTransferFunctionOption (codepoint); - Assert.AreEqual (CVImageBufferTransferFunction.ItuR709_2, matrixOption, "ItuR709_2"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferTransferFunction.ItuR709_2), "ItuR709_2"); codepoint = CVImageBuffer.GetCodePoint (CVImageBufferTransferFunction.Smpte240M1995); matrixOption = CVImageBuffer.GetTransferFunctionOption (codepoint); - Assert.AreEqual (CVImageBufferTransferFunction.Smpte240M1995, matrixOption, "Smpte240M1995"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferTransferFunction.Smpte240M1995), "Smpte240M1995"); codepoint = CVImageBuffer.GetCodePoint (CVImageBufferTransferFunction.SmpteST2084PQ); matrixOption = CVImageBuffer.GetTransferFunctionOption (codepoint); - Assert.AreEqual (CVImageBufferTransferFunction.SmpteST2084PQ, matrixOption, "SmpteST2084PQ"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferTransferFunction.SmpteST2084PQ), "SmpteST2084PQ"); codepoint = CVImageBuffer.GetCodePoint (CVImageBufferTransferFunction.SmpteST428_1); matrixOption = CVImageBuffer.GetTransferFunctionOption (codepoint); - Assert.AreEqual (CVImageBufferTransferFunction.SmpteST428_1, matrixOption, "SmpteST428_1"); + Assert.That (matrixOption, Is.EqualTo (CVImageBufferTransferFunction.SmpteST428_1), "SmpteST428_1"); } } } diff --git a/tests/monotouch-test/CoreVideo/CVMetalBufferCacheTest.cs b/tests/monotouch-test/CoreVideo/CVMetalBufferCacheTest.cs index f8434b21532a..912e9d99698c 100644 --- a/tests/monotouch-test/CoreVideo/CVMetalBufferCacheTest.cs +++ b/tests/monotouch-test/CoreVideo/CVMetalBufferCacheTest.cs @@ -39,7 +39,7 @@ public void GetTypeIdTest () { TestRuntime.AssertXcodeVersion (16, 0); - Assert.AreNotEqual (0, CVMetalBufferCache.GetTypeId (), "GetTypeId"); + Assert.That (CVMetalBufferCache.GetTypeId (), Is.Not.EqualTo (0), "GetTypeId"); } [Test] @@ -50,7 +50,7 @@ public void CtorTest_NSDictionary () using var device = MTLDevice.SystemDefault; using var cache = new CVMetalBufferCache (device, (NSDictionary) null); - Assert.IsNotNull (cache); + Assert.That (cache, Is.Not.Null); } [Test] @@ -63,11 +63,11 @@ public void TryCreate () var rv = CVMetalBufferCache.TryCreate (device, (NSDictionary) null, out var metalBufferCache, out var status); if (rv) { - Assert.AreEqual (CVReturn.Success, status, "Status A"); - Assert.IsNotNull (metalBufferCache, "MetalBufferCache A"); + Assert.That (status, Is.EqualTo (CVReturn.Success), "Status A"); + Assert.That (metalBufferCache, Is.Not.Null, "MetalBufferCache A"); } else { - Assert.AreEqual (CVReturn.Unsupported, status, "Status B"); - Assert.IsNull (metalBufferCache, "MetalBufferCache B"); + Assert.That (status, Is.EqualTo (CVReturn.Unsupported), "Status B"); + Assert.That (metalBufferCache, Is.Null, "MetalBufferCache B"); } metalBufferCache?.Dispose (); } @@ -82,11 +82,11 @@ public void TryCreateHandle () var rv = CVMetalBufferCache.TryCreateHandle (device, (NSDictionary) null, out var metalBufferCache, out var status); if (rv) { - Assert.AreEqual (CVReturn.Success, status, "Status A"); - Assert.AreNotEqual (IntPtr.Zero, metalBufferCache, "MetalBufferCache A"); + Assert.That (status, Is.EqualTo (CVReturn.Success), "Status A"); + Assert.That (metalBufferCache, Is.Not.EqualTo (IntPtr.Zero), "MetalBufferCache A"); } else { - Assert.AreEqual (CVReturn.Unsupported, status, "Status B"); - Assert.AreEqual (IntPtr.Zero, metalBufferCache, "MetalBufferCache B"); + Assert.That (status, Is.EqualTo (CVReturn.Unsupported), "Status B"); + Assert.That (metalBufferCache, Is.EqualTo (IntPtr.Zero), "MetalBufferCache B"); } if (metalBufferCache != IntPtr.Zero) TestRuntime.CFRelease (metalBufferCache); @@ -100,7 +100,7 @@ public void CtorTest_CVMetalBufferCacheAttributes () using var device = MTLDevice.SystemDefault; using var cache = new CVMetalBufferCache (device, (CVMetalBufferCacheAttributes) null); - Assert.IsNotNull (cache); + Assert.That (cache, Is.Not.Null); } #if !MONOMAC @@ -119,7 +119,7 @@ public void CreateBufferFromImageTest (CVPixelFormatType pft) }; using var image = new CVPixelBuffer (320, 320, pft, dict); using var buffer = cache.CreateBufferFromImage (image); - Assert.IsNotNull (buffer, "Buffer"); + Assert.That (buffer, Is.Not.Null, "Buffer"); } #endif // !MONOMAC diff --git a/tests/monotouch-test/CoreVideo/CVMetalBufferTest.cs b/tests/monotouch-test/CoreVideo/CVMetalBufferTest.cs index 71f64c7a9f2a..2e0fa0962570 100644 --- a/tests/monotouch-test/CoreVideo/CVMetalBufferTest.cs +++ b/tests/monotouch-test/CoreVideo/CVMetalBufferTest.cs @@ -16,7 +16,7 @@ public void GetTypeIdTest () { TestRuntime.AssertXcodeVersion (16, 0); - Assert.AreNotEqual (0, CVMetalBuffer.GetTypeId (), "GetTypeId"); + Assert.That (CVMetalBuffer.GetTypeId (), Is.Not.EqualTo (0), "GetTypeId"); } #if !MONOMAC @@ -35,9 +35,9 @@ public void GetMetalBufferTest (CVPixelFormatType pft) }; using var image = new CVPixelBuffer (320, 320, pft, dict); using var buffer = cache.CreateBufferFromImage (image); - Assert.IsNotNull (buffer, "Buffer"); + Assert.That (buffer, Is.Not.Null, "Buffer"); using var metalBuffer = buffer.GetMetalBuffer (); - Assert.IsNotNull (metalBuffer, "GetMetalBuffer"); + Assert.That (metalBuffer, Is.Not.Null, "GetMetalBuffer"); } #endif // !MONOMAC } diff --git a/tests/monotouch-test/CoreVideo/CVMetalTextureCacheTests.cs b/tests/monotouch-test/CoreVideo/CVMetalTextureCacheTests.cs index 0410390b9b80..8988b4dafe10 100644 --- a/tests/monotouch-test/CoreVideo/CVMetalTextureCacheTests.cs +++ b/tests/monotouch-test/CoreVideo/CVMetalTextureCacheTests.cs @@ -29,7 +29,7 @@ public void CVMetalTextureCacheCtorTest () Usage = MTLTextureUsage.PixelFormatView }); - Assert.NotNull (cache); + Assert.That (cache, Is.Not.Null); } [Test] @@ -43,7 +43,7 @@ public void FromDeviceTest () Usage = MTLTextureUsage.PixelFormatView }); - Assert.NotNull (cache); + Assert.That (cache, Is.Not.Null); } } } diff --git a/tests/monotouch-test/CoreVideo/PixelBufferAttributesTest.cs b/tests/monotouch-test/CoreVideo/PixelBufferAttributesTest.cs index 998c15b09940..ee52c3c0bf54 100644 --- a/tests/monotouch-test/CoreVideo/PixelBufferAttributesTest.cs +++ b/tests/monotouch-test/CoreVideo/PixelBufferAttributesTest.cs @@ -19,7 +19,7 @@ public void Defaults () { var options = new CVPixelBufferAttributes (); Assert.That (options.Dictionary.Count, Is.EqualTo ((nuint) 0), "Count"); - Assert.Null (options.MemoryAllocator, "MemoryAllocator"); + Assert.That (options.MemoryAllocator, Is.Null, "MemoryAllocator"); } [Test] diff --git a/tests/monotouch-test/CoreVideo/PixelBufferPoolTest.cs b/tests/monotouch-test/CoreVideo/PixelBufferPoolTest.cs index 5d883bc3cd4e..70c0a46b0043 100644 --- a/tests/monotouch-test/CoreVideo/PixelBufferPoolTest.cs +++ b/tests/monotouch-test/CoreVideo/PixelBufferPoolTest.cs @@ -28,10 +28,10 @@ public void AllocationSettings_Threshold () }; CVReturn error; - Assert.IsNotNull (pbp.CreatePixelBuffer (a, out error), "#1"); - Assert.IsNotNull (pbp.CreatePixelBuffer (a, out error), "#2"); - Assert.IsNull (pbp.CreatePixelBuffer (a, out error), "#3"); - Assert.AreEqual (CVReturn.WouldExceedAllocationThreshold, error, "#3a"); + Assert.That (pbp.CreatePixelBuffer (a, out error), Is.Not.Null, "#1"); + Assert.That (pbp.CreatePixelBuffer (a, out error), Is.Not.Null, "#2"); + Assert.That (pbp.CreatePixelBuffer (a, out error), Is.Null, "#3"); + Assert.That (error, Is.EqualTo (CVReturn.WouldExceedAllocationThreshold), "#3a"); } } } diff --git a/tests/monotouch-test/CoreVideo/PixelBufferTest.cs b/tests/monotouch-test/CoreVideo/PixelBufferTest.cs index 1e4e6b5e15ce..687d921885ed 100644 --- a/tests/monotouch-test/CoreVideo/PixelBufferTest.cs +++ b/tests/monotouch-test/CoreVideo/PixelBufferTest.cs @@ -26,18 +26,18 @@ public void CreateWithBytes () var data = new byte [height * bytesPerRow]; using (var buf = CVPixelBuffer.Create (width, height, CVPixelFormatType.CV32RGBA, data, bytesPerRow, null, out status)) { - Assert.AreEqual (status, CVReturn.InvalidPixelFormat, "CV32RGBA"); - Assert.IsNull (buf, "CV32RGBA - null"); + Assert.That (CVReturn.InvalidPixelFormat, Is.EqualTo (status), "CV32RGBA"); + Assert.That (buf, Is.Null, "CV32RGBA - null"); } using (var buf = CVPixelBuffer.Create (width, height, CVPixelFormatType.CV32BGRA, data, bytesPerRow, null, out status)) { - Assert.AreEqual (status, CVReturn.Success, "CV32RGBA"); - Assert.IsNotNull (buf, "CV32BGRA - null"); + Assert.That (CVReturn.Success, Is.EqualTo (status), "CV32RGBA"); + Assert.That (buf, Is.Not.Null, "CV32BGRA - null"); } var dict = new CVPixelBufferAttributes (); using (var buf = CVPixelBuffer.Create (width, height, CVPixelFormatType.CV32BGRA, data, bytesPerRow, dict)) { - Assert.IsNotNull (buf); + Assert.That (buf, Is.Not.Null); } Assert.Throws (() => CVPixelBuffer.Create (width, height, CVPixelFormatType.CV32BGRA, null, bytesPerRow, null), "null data"); @@ -61,17 +61,17 @@ public void CreateWithPlanarBytes () }; using (var buf = CVPixelBuffer.Create (width, height, CVPixelFormatType.CV32RGBA, data, planeWidths, planeHeights, planeBytesPerRow, null, out status)) { - Assert.IsNull (buf); - Assert.AreEqual (CVReturn.InvalidPixelFormat, status, "invalid status"); + Assert.That (buf, Is.Null); + Assert.That (status, Is.EqualTo (CVReturn.InvalidPixelFormat), "invalid status"); } using (var buf = CVPixelBuffer.Create (width, height, CVPixelFormatType.CV420YpCbCr8BiPlanarVideoRange, data, planeWidths, planeHeights, planeBytesPerRow, null)) { - Assert.IsNotNull (buf); + Assert.That (buf, Is.Not.Null); } var dict = new CVPixelBufferAttributes (); using (var buf = CVPixelBuffer.Create (width, height, CVPixelFormatType.CV420YpCbCr8BiPlanarVideoRange, data, planeWidths, planeHeights, planeBytesPerRow, dict)) { - Assert.IsNotNull (buf); + Assert.That (buf, Is.Not.Null); } Assert.Throws (() => CVPixelBuffer.Create (width, height, CVPixelFormatType.CV420YpCbCr8BiPlanarVideoRange, null, planeWidths, planeHeights, planeBytesPerRow, null), "null data"); @@ -91,7 +91,7 @@ public void CreateWithPlanarBytes () public void CheckInvalidPtr () { var invalid = Runtime.GetINativeObject (IntPtr.Zero, false); - Assert.Null (invalid, "CheckInvalidPtr"); + Assert.That (invalid, Is.Null, "CheckInvalidPtr"); } [Test] @@ -109,8 +109,8 @@ public void IsCompatibleWithAttributeTest () var data = new byte [height * bytesPerRow]; using var buffer = CVPixelBuffer.Create (width, height, pixelFormat, data, bytesPerRow, null, out var status); - Assert.AreEqual (status, CVReturn.Success, "Status"); - Assert.IsNotNull (buffer, "Buffer"); + Assert.That (CVReturn.Success, Is.EqualTo (status), "Status"); + Assert.That (buffer, Is.Not.Null, "Buffer"); var attributes = new CVPixelBufferAttributes (pixelFormat, width, height); Assert.That (buffer.IsCompatibleWithAttributes (attributes), Is.EqualTo (true), "IsCompatible 1"); diff --git a/tests/monotouch-test/CoreVideo/PixelFormatDescriptionTest.cs b/tests/monotouch-test/CoreVideo/PixelFormatDescriptionTest.cs index 7624f76e94ff..6f2702d49e42 100644 --- a/tests/monotouch-test/CoreVideo/PixelFormatDescriptionTest.cs +++ b/tests/monotouch-test/CoreVideo/PixelFormatDescriptionTest.cs @@ -23,21 +23,21 @@ public class PixelFormatDescriptionTest { public void AllTypes () { // https://bugzilla.xamarin.com/show_bug.cgi?id=13917 - Assert.NotNull (CVPixelFormatDescription.AllTypes); + Assert.That (CVPixelFormatDescription.AllTypes, Is.Not.Null); } [Test] public void Create () { // 0 is not defined - Assert.Null (CVPixelFormatDescription.Create (0), "0"); + Assert.That (CVPixelFormatDescription.Create (0), Is.Null, "0"); using (var dict = CVPixelFormatDescription.Create (CVPixelFormatType.CV16Gray)) { - Assert.NotNull (dict, "CV16Gray"); + Assert.That (dict, Is.Not.Null, "CV16Gray"); } using (var dict = CVPixelFormatDescription.Create (CVPixelFormatType.CV32ARGB)) { - Assert.NotNull (dict, "CV32ARGB"); + Assert.That (dict, Is.Not.Null, "CV32ARGB"); } } @@ -49,14 +49,14 @@ public void Register () Assert.Ignore ("This test can only be executed once, it modifies global state."); registerDone = true; - Assert.Null (CVPixelFormatDescription.Create ((CVPixelFormatType) 3), "3a"); + Assert.That (CVPixelFormatDescription.Create ((CVPixelFormatType) 3), Is.Null, "3a"); using (var dict = CVPixelFormatDescription.Create (CVPixelFormatType.CV24RGB)) { - Assert.NotNull (dict, "CV24RGB"); + Assert.That (dict, Is.Not.Null, "CV24RGB"); CVPixelFormatDescription.Register (dict, (CVPixelFormatType) 3); } - Assert.NotNull (CVPixelFormatDescription.Create ((CVPixelFormatType) 3), "3b"); + Assert.That (CVPixelFormatDescription.Create ((CVPixelFormatType) 3), Is.Not.Null, "3b"); } [Test] @@ -65,44 +65,44 @@ public void CV32ARGB () Assert.Multiple (() => { var pf = CVPixelFormatType.CV32ARGB; var desc = CVPixelFormatDescription.CreatePixelFormat (pf); - Assert.IsNull (desc.Name, "Name"); - Assert.AreEqual (pf, desc.Constant ?? ((CVPixelFormatType) 0xFFFFFFFF), "Constant"); - Assert.IsNull (desc.CodecType, "CodecType"); - Assert.IsNull (desc.FourCC, "FourCC"); - Assert.AreEqual (true, desc.ContainsAlpha, "ContainsAlpha"); - Assert.AreEqual (false, desc.FormatContainsYCbCr, "FormatContainsYCbCr"); - Assert.AreEqual (true, desc.FormatContainsRgb, "FormatContainsRgb"); - Assert.AreEqual (false, desc.ContainsGrayscale, "ContainsGrayscale"); + Assert.That (desc.Name, Is.Null, "Name"); + Assert.That (desc.Constant ?? ((CVPixelFormatType) 0xFFFFFFFF), Is.EqualTo (pf), "Constant"); + Assert.That (desc.CodecType, Is.Null, "CodecType"); + Assert.That (desc.FourCC, Is.Null, "FourCC"); + Assert.That (desc.ContainsAlpha, Is.EqualTo (true), "ContainsAlpha"); + Assert.That (desc.FormatContainsYCbCr, Is.EqualTo (false), "FormatContainsYCbCr"); + Assert.That (desc.FormatContainsRgb, Is.EqualTo (true), "FormatContainsRgb"); + Assert.That (desc.ContainsGrayscale, Is.EqualTo (false), "ContainsGrayscale"); if (TestRuntime.CheckXcodeVersion (14, 0)) - Assert.IsNull (desc.FormatContainsSenselArray, "FormatContainsSenselArray"); + Assert.That (desc.FormatContainsSenselArray, Is.Null, "FormatContainsSenselArray"); if (TestRuntime.CheckXcodeVersion (16, 0)) - Assert.AreEqual (CVPixelFormatComponentRangeValues.FullRange, desc.ComponentRangeValue, "ComponentRangeValue"); - Assert.IsNull (desc.Planes, "Planes"); - Assert.IsNull (desc.BlockWidth, "BlockWidth"); - Assert.IsNull (desc.BlockHeight, "BlockHeight"); - Assert.AreEqual (32, desc.BitsPerBlock, "BitsPerBlock"); - Assert.IsNull (desc.BlockHorizontalAlignment, "BlockHorizontalAlignment"); - Assert.IsNull (desc.BlockVerticalAlignment, "BlockVerticalAlignment"); - Assert.IsNotNull (desc.BlackBlock, "BlackBlock"); - Assert.IsNull (desc.HorizontalSubsampling, "HorizontalSubsampling"); - Assert.IsNull (desc.VerticalSubsampling, "VerticalSubsampling"); + Assert.That (desc.ComponentRangeValue, Is.EqualTo (CVPixelFormatComponentRangeValues.FullRange), "ComponentRangeValue"); + Assert.That (desc.Planes, Is.Null, "Planes"); + Assert.That (desc.BlockWidth, Is.Null, "BlockWidth"); + Assert.That (desc.BlockHeight, Is.Null, "BlockHeight"); + Assert.That (desc.BitsPerBlock, Is.EqualTo (32), "BitsPerBlock"); + Assert.That (desc.BlockHorizontalAlignment, Is.Null, "BlockHorizontalAlignment"); + Assert.That (desc.BlockVerticalAlignment, Is.Null, "BlockVerticalAlignment"); + Assert.That (desc.BlackBlock, Is.Not.Null, "BlackBlock"); + Assert.That (desc.HorizontalSubsampling, Is.Null, "HorizontalSubsampling"); + Assert.That (desc.VerticalSubsampling, Is.Null, "VerticalSubsampling"); #if (__IOS__ && !__MACCATALYST__) || __TVOS__ - Assert.IsNull (desc.OpenGLFormat, "OpenGLFormat"); - Assert.IsNull (desc.OpenGLType, "OpenGLType"); - Assert.IsNull (desc.OpenGLInternalFormat, "OpenGLInternalFormat"); - Assert.IsNull (desc.OpenGLCompatibility, "OpenGLCompatibility"); + Assert.That (desc.OpenGLFormat, Is.Null, "OpenGLFormat"); + Assert.That (desc.OpenGLType, Is.Null, "OpenGLType"); + Assert.That (desc.OpenGLInternalFormat, Is.Null, "OpenGLInternalFormat"); + Assert.That (desc.OpenGLCompatibility, Is.Null, "OpenGLCompatibility"); #else - Assert.AreEqual (32993, desc.OpenGLFormat, "OpenGLFormat"); - Assert.AreEqual (32821, desc.OpenGLType, "OpenGLType"); - Assert.AreEqual (32856, desc.OpenGLInternalFormat, "OpenGLInternalFormat"); - Assert.AreEqual (true, desc.OpenGLCompatibility, "OpenGLCompatibility"); + Assert.That (desc.OpenGLFormat, Is.EqualTo (32993), "OpenGLFormat"); + Assert.That (desc.OpenGLType, Is.EqualTo (32821), "OpenGLType"); + Assert.That (desc.OpenGLInternalFormat, Is.EqualTo (32856), "OpenGLInternalFormat"); + Assert.That (desc.OpenGLCompatibility, Is.EqualTo (true), "OpenGLCompatibility"); #endif - Assert.AreEqual (CGBitmapFlags.ByteOrder32Big | CGBitmapFlags.First, desc.CGBitmapInfo, "CGBitmapInfo"); - Assert.AreEqual (true, desc.QDCompatibility, "QDCompatibility"); - Assert.AreEqual (true, desc.CGBitmapContextCompatibility, "CGBitmapContextCompatibility"); - Assert.AreEqual (true, desc.CGImageCompatibility, "CGImageCompatibility"); - Assert.IsNotNull (desc.FillExtendedPixelsCallback, "FillExtendedPixelsCallback"); - Assert.IsNotNull (desc.FillExtendedPixelsCallbackStruct, "FillExtendedPixelsCallbackStruct"); + Assert.That (desc.CGBitmapInfo, Is.EqualTo (CGBitmapFlags.ByteOrder32Big | CGBitmapFlags.First), "CGBitmapInfo"); + Assert.That (desc.QDCompatibility, Is.EqualTo (true), "QDCompatibility"); + Assert.That (desc.CGBitmapContextCompatibility, Is.EqualTo (true), "CGBitmapContextCompatibility"); + Assert.That (desc.CGImageCompatibility, Is.EqualTo (true), "CGImageCompatibility"); + Assert.That (desc.FillExtendedPixelsCallback, Is.Not.Null, "FillExtendedPixelsCallback"); + Assert.That (desc.FillExtendedPixelsCallbackStruct, Is.Not.Null, "FillExtendedPixelsCallbackStruct"); }); } } diff --git a/tests/monotouch-test/CoreWlan/CWKeychainTests.cs b/tests/monotouch-test/CoreWlan/CWKeychainTests.cs index e65cf4ae13f3..e151d8031d2f 100644 --- a/tests/monotouch-test/CoreWlan/CWKeychainTests.cs +++ b/tests/monotouch-test/CoreWlan/CWKeychainTests.cs @@ -29,12 +29,12 @@ public void SetUp () public void TryFindWiFiEAPIdentityMissingTest () { RunOnBackgroundThread (() => { - Assert.False (CWKeychain.TryFindWiFiEAPIdentity (domain, ssid, out var secIdentity), "A"); - Assert.IsNull (secIdentity, "A Identity"); + Assert.That (CWKeychain.TryFindWiFiEAPIdentity (domain, ssid, out var secIdentity), Is.False, "A"); + Assert.That (secIdentity, Is.Null, "A Identity"); - Assert.False (CWKeychain.TryFindWiFiEAPIdentity (domain, ssid, out secIdentity, out var status), "B"); - Assert.IsNull (secIdentity, "B Identity"); - Assert.AreEqual (SecStatusCode.ItemNotFound, (SecStatusCode) status, "Status B"); + Assert.That (CWKeychain.TryFindWiFiEAPIdentity (domain, ssid, out secIdentity, out var status), Is.False, "B"); + Assert.That (secIdentity, Is.Null, "B Identity"); + Assert.That ((SecStatusCode) status, Is.EqualTo (SecStatusCode.ItemNotFound), "Status B"); }); } @@ -42,10 +42,10 @@ public void TryFindWiFiEAPIdentityMissingTest () public void TryDeleteWiFiEAPUsernameAndPasswordMissingTest () { RunOnBackgroundThread (() => { - Assert.False (CWKeychain.TryDeleteWiFiEAPUsernameAndPassword (domain, ssid), "A"); + Assert.That (CWKeychain.TryDeleteWiFiEAPUsernameAndPassword (domain, ssid), Is.False, "A"); - Assert.False (CWKeychain.TryDeleteWiFiEAPUsernameAndPassword (domain, ssid, out var status)); - Assert.AreEqual (SecStatusCode.ItemNotFound, (SecStatusCode) status, "Status B"); + Assert.That (CWKeychain.TryDeleteWiFiEAPUsernameAndPassword (domain, ssid, out var status), Is.False); + Assert.That ((SecStatusCode) status, Is.EqualTo (SecStatusCode.ItemNotFound), "Status B"); }); } @@ -53,10 +53,10 @@ public void TryDeleteWiFiEAPUsernameAndPasswordMissingTest () public void TryDeleteWiFiPasswordMissingTest () { RunOnBackgroundThread (() => { - Assert.False (CWKeychain.TryDeleteWiFiPassword (domain, ssid), "A"); + Assert.That (CWKeychain.TryDeleteWiFiPassword (domain, ssid), Is.False, "A"); - Assert.False (CWKeychain.TryDeleteWiFiPassword (domain, ssid, out var status), "B"); - Assert.AreEqual (SecStatusCode.Param, (SecStatusCode) status, "Status B"); + Assert.That (CWKeychain.TryDeleteWiFiPassword (domain, ssid, out var status), Is.False, "B"); + Assert.That ((SecStatusCode) status, Is.EqualTo (SecStatusCode.Param), "Status B"); }); } @@ -64,14 +64,14 @@ public void TryDeleteWiFiPasswordMissingTest () public void TryFindWiFiEAPUsernameAndPasswordMissingTest () { RunOnBackgroundThread (() => { - Assert.False (CWKeychain.TryFindWiFiEAPUsernameAndPassword (domain, ssid, out string username, out string password), "A"); - Assert.IsNull (username, "A username"); - Assert.IsNull (password, "A password"); - - Assert.False (CWKeychain.TryFindWiFiEAPUsernameAndPassword (domain, ssid, out username, out password, out var status), "B"); - Assert.IsNull (username, "B username"); - Assert.IsNull (password, "B password"); - Assert.AreEqual (SecStatusCode.ItemNotFound, (SecStatusCode) status, "Status B"); + Assert.That (CWKeychain.TryFindWiFiEAPUsernameAndPassword (domain, ssid, out string username, out string password), Is.False, "A"); + Assert.That (username, Is.Null, "A username"); + Assert.That (password, Is.Null, "A password"); + + Assert.That (CWKeychain.TryFindWiFiEAPUsernameAndPassword (domain, ssid, out username, out password, out var status), Is.False, "B"); + Assert.That (username, Is.Null, "B username"); + Assert.That (password, Is.Null, "B password"); + Assert.That ((SecStatusCode) status, Is.EqualTo (SecStatusCode.ItemNotFound), "Status B"); }); } @@ -79,12 +79,12 @@ public void TryFindWiFiEAPUsernameAndPasswordMissingTest () public void TryFindWiFiPasswordMissingTest () { RunOnBackgroundThread (() => { - Assert.False (CWKeychain.TryFindWiFiPassword (domain, ssid, out string password), "A"); - Assert.IsNull (password, "A password"); + Assert.That (CWKeychain.TryFindWiFiPassword (domain, ssid, out string password), Is.False, "A"); + Assert.That (password, Is.Null, "A password"); - Assert.False (CWKeychain.TryFindWiFiPassword (domain, ssid, out password, out var status), "B"); - Assert.IsNull (password, "B password"); - Assert.AreEqual (SecStatusCode.Param, (SecStatusCode) status, "Status B"); + Assert.That (CWKeychain.TryFindWiFiPassword (domain, ssid, out password, out var status), Is.False, "B"); + Assert.That (password, Is.Null, "B password"); + Assert.That ((SecStatusCode) status, Is.EqualTo (SecStatusCode.Param), "Status B"); }); } @@ -100,10 +100,10 @@ public void TrySetWiFiEAPIdentityTest () Assert.That ((SecStatusCode) status, Is.EqualTo (SecStatusCode.Success).Or.EqualTo (SecStatusCode.Allocate), "Status B"); // remove it to clean behind - Assert.False (CWKeychain.TryDeleteWiFiEAPUsernameAndPassword (domain, ssid), "C"); + Assert.That (CWKeychain.TryDeleteWiFiEAPUsernameAndPassword (domain, ssid), Is.False, "C"); - Assert.False (CWKeychain.TryDeleteWiFiEAPUsernameAndPassword (domain, ssid, out status), "D"); - Assert.AreEqual (SecStatusCode.ItemNotFound, (SecStatusCode) status, "Status D"); + Assert.That (CWKeychain.TryDeleteWiFiEAPUsernameAndPassword (domain, ssid, out status), Is.False, "D"); + Assert.That ((SecStatusCode) status, Is.EqualTo (SecStatusCode.ItemNotFound), "Status D"); }); } @@ -111,17 +111,17 @@ public void TrySetWiFiEAPIdentityTest () public void TrySetWiFiEAPUsernameAndPasswordTest () { RunOnBackgroundThread (() => { - Assert.True (CWKeychain.TrySetWiFiEAPUsernameAndPassword (domain, ssid, "mandel", "test"), "Both present A"); - Assert.True (CWKeychain.TrySetWiFiEAPUsernameAndPassword (domain, ssid, "mandel", "test", out var status), "Both present B"); - Assert.AreEqual (SecStatusCode.Success, (SecStatusCode) status, "Both present B Status"); + Assert.That (CWKeychain.TrySetWiFiEAPUsernameAndPassword (domain, ssid, "mandel", "test"), Is.True, "Both present A"); + Assert.That (CWKeychain.TrySetWiFiEAPUsernameAndPassword (domain, ssid, "mandel", "test", out var status), Is.True, "Both present B"); + Assert.That ((SecStatusCode) status, Is.EqualTo (SecStatusCode.Success), "Both present B Status"); - Assert.True (CWKeychain.TrySetWiFiEAPUsernameAndPassword (domain, ssid, "mandel", null), "Null pwd A"); - Assert.True (CWKeychain.TrySetWiFiEAPUsernameAndPassword (domain, ssid, "mandel", null, out status), "Null pwd B"); - Assert.AreEqual (SecStatusCode.Success, (SecStatusCode) status, "Null pwd B Status"); + Assert.That (CWKeychain.TrySetWiFiEAPUsernameAndPassword (domain, ssid, "mandel", null), Is.True, "Null pwd A"); + Assert.That (CWKeychain.TrySetWiFiEAPUsernameAndPassword (domain, ssid, "mandel", null, out status), Is.True, "Null pwd B"); + Assert.That ((SecStatusCode) status, Is.EqualTo (SecStatusCode.Success), "Null pwd B Status"); - Assert.False (CWKeychain.TrySetWiFiEAPUsernameAndPassword (domain, ssid, null, "test"), "Null user A"); - Assert.False (CWKeychain.TrySetWiFiEAPUsernameAndPassword (domain, ssid, null, "test", out status), "Null user B"); - Assert.AreEqual (SecStatusCode.Param, (SecStatusCode) status, "Null user B Status"); + Assert.That (CWKeychain.TrySetWiFiEAPUsernameAndPassword (domain, ssid, null, "test"), Is.False, "Null user A"); + Assert.That (CWKeychain.TrySetWiFiEAPUsernameAndPassword (domain, ssid, null, "test", out status), Is.False, "Null user B"); + Assert.That ((SecStatusCode) status, Is.EqualTo (SecStatusCode.Param), "Null user B Status"); }); } @@ -129,10 +129,10 @@ public void TrySetWiFiEAPUsernameAndPasswordTest () public void TrySetWiFiPasswordTest () { RunOnBackgroundThread (() => { - Assert.False (CWKeychain.TrySetWiFiPassword (domain, ssid, "password"), "A"); + Assert.That (CWKeychain.TrySetWiFiPassword (domain, ssid, "password"), Is.False, "A"); - Assert.False (CWKeychain.TrySetWiFiPassword (domain, ssid, "password", out var status), "B"); - Assert.AreEqual (SecStatusCode.Param, (SecStatusCode) status, "Status B"); + Assert.That (CWKeychain.TrySetWiFiPassword (domain, ssid, "password", out var status), Is.False, "B"); + Assert.That ((SecStatusCode) status, Is.EqualTo (SecStatusCode.Param), "Status B"); }); } @@ -151,7 +151,7 @@ void RunOnBackgroundThread (Action action) thread.Start (); if (!thread.Join (TimeSpan.FromSeconds (10))) Assert.Fail ("Test timed out"); - Assert.IsNull (ex, "No exception"); + Assert.That (ex, Is.Null, "No exception"); } } } diff --git a/tests/monotouch-test/Darwin/KernelNotificationTest.cs b/tests/monotouch-test/Darwin/KernelNotificationTest.cs index a85d608a90cc..9c4c53093061 100644 --- a/tests/monotouch-test/Darwin/KernelNotificationTest.cs +++ b/tests/monotouch-test/Darwin/KernelNotificationTest.cs @@ -35,7 +35,7 @@ public void KEvent () using (var sleep = Process.Start ("/bin/sleep", sleep_duration)) { using (var kqueue = new KernelQueue ()) { var events = CreateEvents (sleep); - Assert.AreEqual (1, kqueue.KEvent (events, events, TimeSpan.FromSeconds (5)), "kevent"); + Assert.That (kqueue.KEvent (events, events, TimeSpan.FromSeconds (5)), Is.EqualTo (1), "kevent"); } } @@ -43,7 +43,7 @@ public void KEvent () using (var sleep = Process.Start ("/bin/sleep", sleep_duration)) { using (var kqueue = new KernelQueue ()) { var events = CreateEvents (sleep); - Assert.AreEqual (1, kqueue.KEvent (events, events, null), "kevent"); + Assert.That (kqueue.KEvent (events, events, null), Is.EqualTo (1), "kevent"); } } @@ -54,7 +54,7 @@ public void KEvent () TimeSpec ts = new TimeSpec { Seconds = 5, }; - Assert.AreEqual (1, kqueue.KEvent (events, events.Length, events, events.Length, ts), "kevent"); + Assert.That (kqueue.KEvent (events, events.Length, events, events.Length, ts), Is.EqualTo (1), "kevent"); } } @@ -62,7 +62,7 @@ public void KEvent () using (var sleep = Process.Start ("/bin/sleep", sleep_duration)) { using (var kqueue = new KernelQueue ()) { var events = CreateEvents (sleep); - Assert.AreEqual (1, kqueue.KEvent (events, events.Length, events, events.Length, null), "kevent"); + Assert.That (kqueue.KEvent (events, events.Length, events, events.Length, null), Is.EqualTo (1), "kevent"); } } diff --git a/tests/monotouch-test/DeviceDiscoveryExtension/DDDeviceTest.cs b/tests/monotouch-test/DeviceDiscoveryExtension/DDDeviceTest.cs index fdfcb1133e91..2c267680c818 100644 --- a/tests/monotouch-test/DeviceDiscoveryExtension/DDDeviceTest.cs +++ b/tests/monotouch-test/DeviceDiscoveryExtension/DDDeviceTest.cs @@ -34,7 +34,7 @@ public void NetworkEndpointTest () device.NetworkEndpoint = endpoint; var tmpEndpoint = device.NetworkEndpoint; - Assert.True (endpoint.GetHandle () == tmpEndpoint.GetHandle (), "NetworkEndpoint"); + Assert.That (endpoint.GetHandle () == tmpEndpoint.GetHandle (), Is.True, "NetworkEndpoint"); } } } diff --git a/tests/monotouch-test/DeviceDiscoveryUI/DDDevicePickerViewControllerTest.cs b/tests/monotouch-test/DeviceDiscoveryUI/DDDevicePickerViewControllerTest.cs index 0213cb1b3cdc..4d2cca6f3bd8 100644 --- a/tests/monotouch-test/DeviceDiscoveryUI/DDDevicePickerViewControllerTest.cs +++ b/tests/monotouch-test/DeviceDiscoveryUI/DDDevicePickerViewControllerTest.cs @@ -33,9 +33,9 @@ public void IsSupportedTest () // DDDevicePickerViewController seems to work only for devices if (TestRuntime.IsSimulator) - Assert.IsFalse (isSupported, "IsSupported"); + Assert.That (isSupported, Is.False, "IsSupported"); else - Assert.IsTrue (isSupported, "IsSupported"); + Assert.That (isSupported, Is.True, "IsSupported"); } [Test] @@ -50,7 +50,7 @@ public void InitWithBrowseDescriptorAndParametersTest () // If this fails, please, double check that MyAppService is registered within the Info.plist // https://developer.apple.com/documentation/bundleresources/information_property_list/nsapplicationservices - Assert.IsTrue (isSupported, $"The {serviceName} key might not be registered in the Info.plist."); + Assert.That (isSupported, Is.True, $"The {serviceName} key might not be registered in the Info.plist."); Assert.DoesNotThrow (() => { var devicePicker = new DDDevicePickerViewController (browserDescriptor, parameters); }, "InitWithBrowseDescriptorAndParameters"); @@ -68,7 +68,7 @@ public void SetDevicePickerTest () // If this fails, please, double check that MyAppService is registered within the Info.plist // https://developer.apple.com/documentation/bundleresources/information_property_list/nsapplicationservices - Assert.IsTrue (isSupported, $"The {serviceName} key might not be registered in the Info.plist."); + Assert.That (isSupported, Is.True, $"The {serviceName} key might not be registered in the Info.plist."); Assert.DoesNotThrow (() => { var devicePicker = new DDDevicePickerViewController (browserDescriptor, parameters); diff --git a/tests/monotouch-test/EventKit/CalendarTest.cs b/tests/monotouch-test/EventKit/CalendarTest.cs index 8d28e49f1adf..0db3faff3bbf 100644 --- a/tests/monotouch-test/EventKit/CalendarTest.cs +++ b/tests/monotouch-test/EventKit/CalendarTest.cs @@ -46,19 +46,19 @@ public void FromEventStore () var c = EKCalendar.FromEventStore (store); #endif // defaults - Assert.True (c.AllowsContentModifications, "AllowsContentModifications"); - Assert.NotNull (c.CalendarIdentifier, "CalendarIdentifier"); + Assert.That (c.AllowsContentModifications, Is.True, "AllowsContentModifications"); + Assert.That (c.CalendarIdentifier, Is.Not.Null, "CalendarIdentifier"); #if MONOMAC - Assert.Null (c.Color, "Color"); + Assert.That (c.Color, Is.Null, "Color"); #else - Assert.Null (c.CGColor, "CGColor"); + Assert.That (c.CGColor, Is.Null, "CGColor"); #endif Assert.That (c.Immutable, Is.EqualTo (true).Or.EqualTo (false), "Immutable"); - Assert.AreEqual (EKEntityMask.Event, c.AllowedEntityTypes, "AllowedEntityTypes"); + Assert.That (c.AllowedEntityTypes, Is.EqualTo (EKEntityMask.Event), "AllowedEntityTypes"); - Assert.Null (c.Source, "Source"); - Assert.False (c.Subscribed, "Subscribed"); + Assert.That (c.Source, Is.Null, "Source"); + Assert.That (c.Subscribed, Is.False, "Subscribed"); #if MONOMAC || __MACCATALYST__ if (TestRuntime.CheckXcodeVersion (14, 0)) Assert.That (c.SupportedEventAvailabilities, Is.EqualTo (EKCalendarEventAvailability.None), "SupportedEventAvailabilities"); @@ -71,7 +71,7 @@ public void FromEventStore () if (TestRuntime.CheckXcodeVersion (13, 2)) Assert.That (c.Title, Is.EqualTo (string.Empty), "Title"); else - Assert.Null (c.Title, "Title"); + Assert.That (c.Title, Is.Null, "Title"); #endif Assert.That (c.Type, Is.EqualTo (EKCalendarType.Local), "Type"); } @@ -86,17 +86,17 @@ public void FromEventStoreWithReminder () var c = EKCalendar.Create (EKEntityType.Reminder, new EKEventStore ()); // defaults - Assert.True (c.AllowsContentModifications, "AllowsContentModifications"); - Assert.NotNull (c.CalendarIdentifier, "CalendarIdentifier"); + Assert.That (c.AllowsContentModifications, Is.True, "AllowsContentModifications"); + Assert.That (c.CalendarIdentifier, Is.Not.Null, "CalendarIdentifier"); #if MONOMAC - Assert.Null (c.Color, "Color"); + Assert.That (c.Color, Is.Null, "Color"); #else - Assert.Null (c.CGColor, "CGColor"); + Assert.That (c.CGColor, Is.Null, "CGColor"); #endif - Assert.False (c.Immutable, "Immutable"); - Assert.Null (c.Source, "Source"); - Assert.False (c.Subscribed, "Subscribed"); + Assert.That (c.Immutable, Is.False, "Immutable"); + Assert.That (c.Source, Is.Null, "Source"); + Assert.That (c.Subscribed, Is.False, "Subscribed"); #if MONOMAC || __MACCATALYST__ if (TestRuntime.CheckXcodeVersion (14, 0)) Assert.That (c.SupportedEventAvailabilities, Is.EqualTo (EKCalendarEventAvailability.None), "SupportedEventAvailabilities"); @@ -109,11 +109,11 @@ public void FromEventStoreWithReminder () if (TestRuntime.CheckXcodeVersion (13, 2)) Assert.That (c.Title, Is.EqualTo (string.Empty), "Title"); else - Assert.Null (c.Title, "Title"); + Assert.That (c.Title, Is.Null, "Title"); #endif Assert.That (c.Type, Is.EqualTo (EKCalendarType.Local), "Type"); - Assert.AreEqual (EKEntityMask.Reminder, c.AllowedEntityTypes, "AllowedEntityTypes"); - Assert.IsNotNull (c.CalendarIdentifier, "CalendarIdentifier"); + Assert.That (c.AllowedEntityTypes, Is.EqualTo (EKEntityMask.Reminder), "AllowedEntityTypes"); + Assert.That (c.CalendarIdentifier, Is.Not.Null, "CalendarIdentifier"); } [Test] diff --git a/tests/monotouch-test/EventKit/EKUIBundleTest.cs b/tests/monotouch-test/EventKit/EKUIBundleTest.cs index 7921bce4663c..19ab3ddb0e95 100644 --- a/tests/monotouch-test/EventKit/EKUIBundleTest.cs +++ b/tests/monotouch-test/EventKit/EKUIBundleTest.cs @@ -23,8 +23,8 @@ public void BundleTest () Assert.Ignore ("Ignoring tests: Requires iOS11+"); var bundle = EKUIBundle.UIBundle; - Assert.NotNull (bundle, "Was Null"); - Assert.AreEqual ("com.apple.eventkitui", bundle.BundleIdentifier, "BundleIdentifier"); + Assert.That (bundle, Is.Not.Null, "Was Null"); + Assert.That (bundle.BundleIdentifier, Is.EqualTo ("com.apple.eventkitui"), "BundleIdentifier"); } } } diff --git a/tests/monotouch-test/EventKit/EventStoreTest.cs b/tests/monotouch-test/EventKit/EventStoreTest.cs index a45d9a2093c9..114b3c247b72 100644 --- a/tests/monotouch-test/EventKit/EventStoreTest.cs +++ b/tests/monotouch-test/EventKit/EventStoreTest.cs @@ -23,12 +23,12 @@ public class EventStoreTest { public void DefaultCalendar () { var store = new EKEventStore (); - Assert.AreEqual ("Calendar", store.DefaultCalendarForNewEvents.Title, "DefaultCalendarForNewEvents"); - Assert.IsNull (store.DefaultCalendarForNewReminders, "DefaultCalendarForNewReminders"); + Assert.That (store.DefaultCalendarForNewEvents.Title, Is.EqualTo ("Calendar"), "DefaultCalendarForNewEvents"); + Assert.That (store.DefaultCalendarForNewReminders, Is.Null, "DefaultCalendarForNewReminders"); #if !MONOMAC // Not available on Mac - Assert.IsNotNull (store.Calendars, "Calendars"); + Assert.That (store.Calendars, Is.Not.Null, "Calendars"); #endif - Assert.IsNotNull (store.Sources, "Sources"); + Assert.That (store.Sources, Is.Not.Null, "Sources"); } #if false @@ -39,10 +39,10 @@ public void DefaultCalendar () public void DefaultReminder () { var store = new EKEventStore (EKEntityMask.Reminder); - Assert.AreEqual ("Reminders", store.DefaultCalendarForNewReminders.Title, "DefaultCalendarForNewReminders"); - Assert.IsNull (store.DefaultCalendarForNewEvents, "DefaultCalendarForNewEvents"); - Assert.IsNotNull (store.Calendars, "Calendars"); - Assert.IsNotNull (store.Sources, "Sources"); + Assert.That (store.DefaultCalendarForNewReminders.Title, Is.EqualTo ("Reminders"), "DefaultCalendarForNewReminders"); + Assert.That (store.DefaultCalendarForNewEvents, Is.Null, "DefaultCalendarForNewEvents"); + Assert.That (store.Calendars, Is.Not.Null, "Calendars"); + Assert.That (store.Sources, Is.Not.Null, "Sources"); } [Test] @@ -51,10 +51,10 @@ public void GetCalendars () { var store = new EKEventStore (EKEntityMask.Reminder); var calendars = store.GetCalendars (EKEntityType.Reminder); - Assert.AreEqual ("Reminders", calendars[0].Title, "#1"); + Assert.That (calendars[0].Title, Is.EqualTo ("Reminders"), "#1"); calendars = store.GetCalendars (EKEntityType.Event); - Assert.AreEqual (0, calendars.Length, "#2"); + Assert.That (calendars.Length, Is.EqualTo (0), "#2"); } [Test] @@ -68,7 +68,7 @@ public void Predicates() rem.Calendar = store.DefaultCalendarForNewReminders; NSError error; - Assert.IsTrue (store.SaveReminder (rem, true, out error), "SaveReminder"); + Assert.That (store.SaveReminder (rem, true, out error), Is.True, "SaveReminder"); var predicate = store.PredicateForIncompleteReminders (null, null, new [] { rem.Calendar }); var mre = new ManualResetEvent (false); @@ -78,22 +78,22 @@ public void Predicates() mre.Set (); }); - Assert.IsTrue (mre.WaitOne (3000), "#1"); - Assert.IsTrue (found, "#2"); + Assert.That (mre.WaitOne (3000), Is.True, "#1"); + Assert.That (found, Is.True, "#2"); mre.Reset (); predicate = store.PredicateForReminders (null); store.FetchReminders (predicate, l => mre.Set ()); - Assert.IsTrue (mre.WaitOne (3000), "#10"); + Assert.That (mre.WaitOne (3000), Is.True, "#10"); mre.Reset (); predicate = store.PredicateForCompleteReminders (null, null, null); store.FetchReminders (predicate, l => mre.Set ()); - Assert.IsTrue (mre.WaitOne (3000), "#20"); + Assert.That (mre.WaitOne (3000), Is.True, "#20"); - Assert.IsTrue (store.RemoveReminder (rem, true, out error), "RemoveReminder"); + Assert.That (store.RemoveReminder (rem, true, out error), Is.True, "RemoveReminder"); } #endif } diff --git a/tests/monotouch-test/EventKit/RecurrenceRule.cs b/tests/monotouch-test/EventKit/RecurrenceRule.cs index 0011691f850b..d137734e47da 100644 --- a/tests/monotouch-test/EventKit/RecurrenceRule.cs +++ b/tests/monotouch-test/EventKit/RecurrenceRule.cs @@ -27,17 +27,17 @@ public void Setup () public void DefaultProperties () { using (var rule = new EKRecurrenceRule ()) { - Assert.AreEqual ("gregorian", rule.CalendarIdentifier, "CalendarIdentifier"); - Assert.IsNull (rule.RecurrenceEnd, "RecurrenceEnd"); - Assert.AreEqual (EKRecurrenceFrequency.Weekly, rule.Frequency, "Frequency"); - Assert.AreEqual ((nint) 1, rule.Interval, "Interval"); - Assert.AreEqual (EKWeekday.Monday, rule.FirstDayOfTheWeek, "FirstDayOfTheWeek"); - Assert.IsNull (rule.DaysOfTheWeek, "DaysOfTheWeek"); - Assert.IsNull (rule.DaysOfTheMonth, "DaysOfTheMonth"); - Assert.IsNull (rule.DaysOfTheYear, "DaysOfTheYear"); - Assert.IsNull (rule.WeeksOfTheYear, "WeeksOfTheYear"); - Assert.IsNull (rule.MonthsOfTheYear, "MonthsOfTheYear"); - Assert.IsNull (rule.SetPositions, "SetPositions"); + Assert.That (rule.CalendarIdentifier, Is.EqualTo ("gregorian"), "CalendarIdentifier"); + Assert.That (rule.RecurrenceEnd, Is.Null, "RecurrenceEnd"); + Assert.That (rule.Frequency, Is.EqualTo (EKRecurrenceFrequency.Weekly), "Frequency"); + Assert.That (rule.Interval, Is.EqualTo ((nint) 1), "Interval"); + Assert.That (rule.FirstDayOfTheWeek, Is.EqualTo (EKWeekday.Monday), "FirstDayOfTheWeek"); + Assert.That (rule.DaysOfTheWeek, Is.Null, "DaysOfTheWeek"); + Assert.That (rule.DaysOfTheMonth, Is.Null, "DaysOfTheMonth"); + Assert.That (rule.DaysOfTheYear, Is.Null, "DaysOfTheYear"); + Assert.That (rule.WeeksOfTheYear, Is.Null, "WeeksOfTheYear"); + Assert.That (rule.MonthsOfTheYear, Is.Null, "MonthsOfTheYear"); + Assert.That (rule.SetPositions, Is.Null, "SetPositions"); } } diff --git a/tests/monotouch-test/EventKit/ReminderTest.cs b/tests/monotouch-test/EventKit/ReminderTest.cs index f36a5739aca5..8f16f904ff17 100644 --- a/tests/monotouch-test/EventKit/ReminderTest.cs +++ b/tests/monotouch-test/EventKit/ReminderTest.cs @@ -29,14 +29,14 @@ public void DefaultProperties () { using var store = new EKEventStore (); using (var rem = EKReminder.Create (store)) { - Assert.AreEqual (0, rem.Priority, "Priority"); - Assert.IsFalse (rem.Completed, "Completed"); - Assert.IsNull (rem.CompletionDate, "CompletionDate"); - Assert.IsNull (rem.StartDateComponents, "StartDateComponents"); - Assert.IsNull (rem.DueDateComponents, "DueDateComponents"); + Assert.That (rem.Priority, Is.EqualTo (0), "Priority"); + Assert.That (rem.Completed, Is.False, "Completed"); + Assert.That (rem.CompletionDate, Is.Null, "CompletionDate"); + Assert.That (rem.StartDateComponents, Is.Null, "StartDateComponents"); + Assert.That (rem.DueDateComponents, Is.Null, "DueDateComponents"); rem.Completed = true; - Assert.IsTrue (rem.Completed, "Completed - Changed"); + Assert.That (rem.Completed, Is.True, "Completed - Changed"); } } diff --git a/tests/monotouch-test/EventKit/StructuredLocationTest.cs b/tests/monotouch-test/EventKit/StructuredLocationTest.cs index 50d9eb92236a..8ab261b224e0 100644 --- a/tests/monotouch-test/EventKit/StructuredLocationTest.cs +++ b/tests/monotouch-test/EventKit/StructuredLocationTest.cs @@ -23,9 +23,9 @@ public void DefaultValues () Assert.Inconclusive ("EKStructuredLocation is new in 6.0"); var sl = new EKStructuredLocation (); - Assert.IsNull (sl.GeoLocation, "GeoLocation"); - Assert.AreEqual (0, sl.Radius, "Radius"); - Assert.IsNull (sl.Title, "Title"); + Assert.That (sl.GeoLocation, Is.Null, "GeoLocation"); + Assert.That (sl.Radius, Is.EqualTo (0), "Radius"); + Assert.That (sl.Title, Is.Null, "Title"); } [Test] @@ -35,9 +35,9 @@ public void FromTitle () Assert.Inconclusive ("EKStructuredLocation is new in 6.0"); var sl = EKStructuredLocation.FromTitle ("my title"); - Assert.IsNull (sl.GeoLocation, "GeoLocation"); - Assert.AreEqual (0, sl.Radius, "Radius"); - Assert.AreEqual ("my title", sl.Title, "Title"); + Assert.That (sl.GeoLocation, Is.Null, "GeoLocation"); + Assert.That (sl.Radius, Is.EqualTo (0), "Radius"); + Assert.That (sl.Title, Is.EqualTo ("my title"), "Title"); } } } diff --git a/tests/monotouch-test/ExternalAccessory/AccessoryManagerTest.cs b/tests/monotouch-test/ExternalAccessory/AccessoryManagerTest.cs index c89c13b8d41f..99398b4d67dd 100644 --- a/tests/monotouch-test/ExternalAccessory/AccessoryManagerTest.cs +++ b/tests/monotouch-test/ExternalAccessory/AccessoryManagerTest.cs @@ -30,7 +30,7 @@ public void Shared () // reported to throw an InvalidCastException on http://stackoverflow.com/q/18884195/220643 var am = EAAccessoryManager.SharedAccessoryManager; // IsEmpty most of the time... unless you docked something, like a keyboard - Assert.IsNotNull (am.ConnectedAccessories, "ConnectedAccessories"); + Assert.That (am.ConnectedAccessories, Is.Not.Null, "ConnectedAccessories"); } #if !MONOMAC && !__MACCATALYST__ diff --git a/tests/monotouch-test/FileProvider/NSFileProviderPageTest.cs b/tests/monotouch-test/FileProvider/NSFileProviderPageTest.cs index c95e6e333639..170e5e20db91 100644 --- a/tests/monotouch-test/FileProvider/NSFileProviderPageTest.cs +++ b/tests/monotouch-test/FileProvider/NSFileProviderPageTest.cs @@ -25,8 +25,8 @@ public void CompressionSessionCreateTest () TestRuntime.AssertDevice (); TestRuntime.AssertXcodeVersion (9, 0); - Assert.IsNotNull (NSFileProviderPage.InitialPageSortedByDate, "InitialPageSortedByDate should not be null"); - Assert.IsNotNull (NSFileProviderPage.InitialPageSortedByName, "InitialPageSortedByName should not be null"); + Assert.That (NSFileProviderPage.InitialPageSortedByDate, Is.Not.Null, "InitialPageSortedByDate should not be null"); + Assert.That (NSFileProviderPage.InitialPageSortedByName, Is.Not.Null, "InitialPageSortedByName should not be null"); } } } diff --git a/tests/monotouch-test/Foundation/AppleScript.cs b/tests/monotouch-test/Foundation/AppleScript.cs index f65bf1bb5ca7..b7cbd42a66a9 100644 --- a/tests/monotouch-test/Foundation/AppleScript.cs +++ b/tests/monotouch-test/Foundation/AppleScript.cs @@ -16,12 +16,12 @@ public void AppleScript_BasicTest () NSDictionary errorInfo; bool success = s.CompileAndReturnError (out errorInfo); - Assert.IsTrue (success); - Assert.IsNull (errorInfo); - Assert.IsTrue (s.Compiled); + Assert.That (success, Is.True); + Assert.That (errorInfo, Is.Null); + Assert.That (s.Compiled, Is.True); NSAppleEventDescriptor descriptor = s.ExecuteAndReturnError (out errorInfo); - Assert.IsNull (errorInfo); + Assert.That (errorInfo, Is.Null); #pragma warning restore 0219 } } diff --git a/tests/monotouch-test/Foundation/ArrayTest.cs b/tests/monotouch-test/Foundation/ArrayTest.cs index eab92514480d..8965e909538c 100644 --- a/tests/monotouch-test/Foundation/ArrayTest.cs +++ b/tests/monotouch-test/Foundation/ArrayTest.cs @@ -26,7 +26,7 @@ public void FromStrings_Null () using (var a = NSArray.FromStrings (new string [1])) { Assert.That (a.Count, Is.EqualTo ((nuint) 1), "null item"); - Assert.IsNull (a.GetItem (0), "0"); + Assert.That (a.GetItem (0), Is.Null, "0"); } } @@ -35,9 +35,9 @@ public void FromStrings_WithNullItems () { using (var a = NSArray.FromStrings (new string? [] { "a", null, "b" })) { Assert.That (a.Count, Is.EqualTo ((nuint) 3), "Count"); - Assert.AreEqual ("a", a.GetItem (0)?.ToString (), "0"); - Assert.IsNull (a.GetItem (1), "1 - null item"); - Assert.AreEqual ("b", a.GetItem (2)?.ToString (), "2"); + Assert.That (a.GetItem (0)?.ToString (), Is.EqualTo ("a"), "0"); + Assert.That (a.GetItem (1), Is.Null, "1 - null item"); + Assert.That (a.GetItem (2)?.ToString (), Is.EqualTo ("b"), "2"); } } @@ -47,27 +47,27 @@ public void FromStrings_IReadOnlyList () IReadOnlyList list = new List { "x", null, "y" }; using (var a = NSArray.FromStrings (list)) { Assert.That (a.Count, Is.EqualTo ((nuint) 3), "Count"); - Assert.AreEqual ("x", a.GetItem (0)?.ToString (), "0"); - Assert.IsNull (a.GetItem (1), "1 - null item"); - Assert.AreEqual ("y", a.GetItem (2)?.ToString (), "2"); + Assert.That (a.GetItem (0)?.ToString (), Is.EqualTo ("x"), "0"); + Assert.That (a.GetItem (1), Is.Null, "1 - null item"); + Assert.That (a.GetItem (2)?.ToString (), Is.EqualTo ("y"), "2"); } } [Test] public void FromNullableStrings_Null () { - Assert.IsNull (NSArray.FromNullableStrings (null), "null returns null"); + Assert.That (NSArray.FromNullableStrings (null), Is.Null, "null returns null"); } [Test] public void FromNullableStrings_WithValues () { using (var a = NSArray.FromNullableStrings (new string? [] { "hello", null, "world" })) { - Assert.IsNotNull (a, "not null"); + Assert.That (a, Is.Not.Null, "not null"); Assert.That (a!.Count, Is.EqualTo ((nuint) 3), "Count"); - Assert.AreEqual ("hello", a.GetItem (0)?.ToString (), "0"); - Assert.IsNull (a.GetItem (1), "1 - null item"); - Assert.AreEqual ("world", a.GetItem (2)?.ToString (), "2"); + Assert.That (a.GetItem (0)?.ToString (), Is.EqualTo ("hello"), "0"); + Assert.That (a.GetItem (1), Is.Null, "1 - null item"); + Assert.That (a.GetItem (2)?.ToString (), Is.EqualTo ("world"), "2"); } } @@ -75,7 +75,7 @@ public void FromNullableStrings_WithValues () public void FromNullableStrings_Empty () { using (var a = NSArray.FromNullableStrings (Array.Empty ())) { - Assert.IsNotNull (a, "not null"); + Assert.That (a, Is.Not.Null, "not null"); Assert.That (a!.Count, Is.EqualTo ((nuint) 0), "Count"); } } @@ -85,7 +85,7 @@ public void Null () { using (var a = NSArray.FromNSObjects (NSNull.Null)) { Assert.That (a.Count, Is.EqualTo ((nuint) 1), "Count"); - Assert.IsNull (a.GetItem (0), "0"); + Assert.That (a.GetItem (0), Is.Null, "0"); } } @@ -152,7 +152,7 @@ public void INativeObjects () using (var policy = SecPolicy.CreateSslPolicy (true, "mail.xamarin.com")) { using (var a = NSArray.FromObjects (policy)) { var b = NSArray.ArrayFromHandle (a.Handle); - Assert.AreNotSame (a, b); + Assert.That (b, Is.Not.SameAs (a)); } } } @@ -173,8 +173,8 @@ public void ToArray () { using (var a = NSArray.FromStrings (new string [1] { "abc" })) { var arr = a.ToArray (); - Assert.AreEqual (1, arr.Length, "Length"); - Assert.AreEqual ("abc", arr [0].ToString (), "Value"); + Assert.That (arr.Length, Is.EqualTo (1), "Length"); + Assert.That (arr [0].ToString (), Is.EqualTo ("abc"), "Value"); } } @@ -183,8 +183,8 @@ public void ToArray_T () { using (var a = NSArray.FromStrings (new string [1] { "abc" })) { var arr = a.ToArray (); - Assert.AreEqual (1, arr.Length, "Length"); - Assert.AreEqual ("abc", arr [0].ToString (), "Value"); + Assert.That (arr.Length, Is.EqualTo (1), "Length"); + Assert.That (arr [0].ToString (), Is.EqualTo ("abc"), "Value"); } } @@ -193,10 +193,10 @@ public void Enumerator () { using (var a = NSArray.FromStrings (new string [1] { "abc" })) { foreach (var item in a) - Assert.AreEqual ("abc", item.ToString (), "Value"); + Assert.That (item.ToString (), Is.EqualTo ("abc"), "Value"); var list = a.ToList (); - Assert.AreEqual (1, list.Count (), "Length"); - Assert.AreEqual ("abc", list [0].ToString (), "Value"); + Assert.That (list.Count (), Is.EqualTo (1), "Length"); + Assert.That (list [0].ToString (), Is.EqualTo ("abc"), "Value"); } } } diff --git a/tests/monotouch-test/Foundation/AttributedStringTest.cs b/tests/monotouch-test/Foundation/AttributedStringTest.cs index 62ffbdbdd702..7b02247fa04b 100644 --- a/tests/monotouch-test/Foundation/AttributedStringTest.cs +++ b/tests/monotouch-test/Foundation/AttributedStringTest.cs @@ -28,11 +28,11 @@ public void Attributes () var j = new NSMutableAttributedString ("Hello", new CTStringAttributes () { ForegroundColor = red }); j.Append (new NSMutableAttributedString ("12345", new CTStringAttributes () { ForegroundColor = yellow })); j.EnumerateAttributes (new NSRange (0, 10), NSAttributedStringEnumeration.None, cb); - Assert.True (t1); - Assert.True (t2); - Assert.False (failEnum); - Assert.True (tFont1); - Assert.True (tFont2); + Assert.That (t1, Is.True); + Assert.That (t2, Is.True); + Assert.That (failEnum, Is.False); + Assert.That (tFont1, Is.True); + Assert.That (tFont2, Is.True); } void cb (NSDictionary attrs, NSRange range, ref bool stop) @@ -52,28 +52,6 @@ void cb (NSDictionary attrs, NSRange range, ref bool stop) failEnum = true; } - [Test] - public void Fields () - { - // fields are not available in iOS (at least up to 5.1.1) - // this test will fail if this ever change in the future - IntPtr lib = Dlfcn.dlopen (Constants.FoundationLibrary, 0); - try { - Assert.That (Dlfcn.dlsym (lib, "NSFontAttributeName"), Is.EqualTo (IntPtr.Zero), "NSFontAttributeName"); - Assert.That (Dlfcn.dlsym (lib, "NSLinkAttributeName"), Is.EqualTo (IntPtr.Zero), "NSLinkAttributeName"); - Assert.That (Dlfcn.dlsym (lib, "NSUnderlineStyleAttributeName"), Is.EqualTo (IntPtr.Zero), "NSUnderlineStyleAttributeName"); - Assert.That (Dlfcn.dlsym (lib, "NSStrikethroughStyleAttributeName"), Is.EqualTo (IntPtr.Zero), "NSStrikethroughStyleAttributeName"); - Assert.That (Dlfcn.dlsym (lib, "NSStrokeWidthAttributeName"), Is.EqualTo (IntPtr.Zero), "NSStrokeWidthAttributeName"); - Assert.That (Dlfcn.dlsym (lib, "NSParagraphStyleAttributeName"), Is.EqualTo (IntPtr.Zero), "NSParagraphStyleAttributeName"); - Assert.That (Dlfcn.dlsym (lib, "NSForegroundColorAttributeName"), Is.EqualTo (IntPtr.Zero), "NSForegroundColorAttributeName"); - Assert.That (Dlfcn.dlsym (lib, "NSBackgroundColorAttributeName"), Is.EqualTo (IntPtr.Zero), "NSBackgroundColorAttributeName"); - Assert.That (Dlfcn.dlsym (lib, "NSLigatureAttributeName"), Is.EqualTo (IntPtr.Zero), "NSLigatureAttributeName"); - Assert.That (Dlfcn.dlsym (lib, "NSObliquenessAttributeName"), Is.EqualTo (IntPtr.Zero), "NSObliquenessAttributeName"); - } finally { - Dlfcn.dlclose (lib); - } - } - [Test] public void UIKitAttachmentConveniences_New () { @@ -132,14 +110,14 @@ public void Create_Url_Error () { { using var obj = NSAttributedString.Create (new NSUrl (""), new NSAttributedStringDocumentAttributes (), out var rda, out var e); - Assert.IsNull (obj, "IsNull"); - Assert.IsNotNull (e, "Error"); + Assert.That (obj, Is.Null, "IsNull"); + Assert.That (e, Is.Not.Null, "Error"); } { using var obj = NSAttributedString.Create (new NSUrl (""), new NSAttributedStringDocumentAttributes (), out var e); - Assert.IsNull (obj, "IsNull 2"); - Assert.IsNotNull (e, "Error 2"); + Assert.That (obj, Is.Null, "IsNull 2"); + Assert.That (e, Is.Not.Null, "Error 2"); } } @@ -148,8 +126,8 @@ public void Create_Markdown_Url_Error () { using var markdownOptions = new NSAttributedStringMarkdownParsingOptions (); using var obj = NSAttributedString.Create (new NSUrl (""), markdownOptions, null, out var e); - Assert.IsNull (obj, "IsNull"); - Assert.IsNotNull (e, "Error"); + Assert.That (obj, Is.Null, "IsNull"); + Assert.That (e, Is.Not.Null, "Error"); } @@ -160,13 +138,13 @@ public void Create_Url () var textUrl = NSUrl.CreateFileUrl (textFile); { using var obj = NSAttributedString.Create (textUrl, new NSAttributedStringDocumentAttributes (), out var rda, out var e); - Assert.IsNull (e, "Error"); - Assert.IsNotNull (obj, "IsNull"); + Assert.That (e, Is.Null, "Error"); + Assert.That (obj, Is.Not.Null, "IsNull"); } { using var obj = NSAttributedString.Create (textUrl, new NSAttributedStringDocumentAttributes (), out var e); - Assert.IsNull (e, "Error 2"); - Assert.IsNotNull (obj, "IsNull 2"); + Assert.That (e, Is.Null, "Error 2"); + Assert.That (obj, Is.Not.Null, "IsNull 2"); } } @@ -177,8 +155,8 @@ public void Create_Markdown_Url () var textUrl = NSUrl.CreateFileUrl (textFile); using var markdownOptions = new NSAttributedStringMarkdownParsingOptions (); using var obj = NSAttributedString.Create (textUrl, markdownOptions, null, out var e); - Assert.IsNull (e, "Error"); - Assert.IsNotNull (obj, "IsNull"); + Assert.That (e, Is.Null, "Error"); + Assert.That (obj, Is.Not.Null, "IsNull"); } [Test] @@ -188,13 +166,13 @@ public void Create_Data_Error () attributes.DocumentType = NSDocumentType.RTF; { using var obj = NSAttributedString.Create (NSData.FromArray (new byte [42]), attributes, out var rda, out var e); - Assert.IsNull (obj, "IsNull"); - Assert.IsNotNull (e, "Error"); + Assert.That (obj, Is.Null, "IsNull"); + Assert.That (e, Is.Not.Null, "Error"); } { using var obj = NSAttributedString.Create (NSData.FromArray (new byte [42]), attributes, out var e); - Assert.IsNull (obj, "IsNull 2"); - Assert.IsNotNull (e, "Error 2"); + Assert.That (obj, Is.Null, "IsNull 2"); + Assert.That (e, Is.Not.Null, "Error 2"); } } @@ -203,8 +181,8 @@ public void Create_Markdown_Data_Error () { using var markdownOptions = new NSAttributedStringMarkdownParsingOptions (); using var obj = NSAttributedString.Create (NSData.FromArray (new byte [] { (byte) '[', (byte) '!', (byte) '"', (byte) '$', (byte) '%', (byte) '&', (byte) '/', (byte) '(', (byte) ')', (byte) '=', (byte) '?', (byte) '¿', (byte) '^', (byte) '*', (byte) '¨', (byte) '´', (byte) '}', (byte) '\\' }), markdownOptions, null, out var e); - Assert.IsNull (obj, "IsNull"); - Assert.IsNotNull (e, "Error"); + Assert.That (obj, Is.Null, "IsNull"); + Assert.That (e, Is.Not.Null, "Error"); } [Test] @@ -212,13 +190,13 @@ public void Create_Data () { { using var obj = NSAttributedString.Create (new NSData (), new NSAttributedStringDocumentAttributes (), out var rda, out var e); - Assert.IsNotNull (obj, "IsNull"); - Assert.IsNull (e, "Error"); + Assert.That (obj, Is.Not.Null, "IsNull"); + Assert.That (e, Is.Null, "Error"); } { using var obj = NSAttributedString.Create (new NSData (), new NSAttributedStringDocumentAttributes (), out var e); - Assert.IsNotNull (obj, "IsNull 2"); - Assert.IsNull (e, "Error 2"); + Assert.That (obj, Is.Not.Null, "IsNull 2"); + Assert.That (e, Is.Null, "Error 2"); } } @@ -227,8 +205,8 @@ public void Create_Markdown_Data () { using var markdownOptions = new NSAttributedStringMarkdownParsingOptions (); using var obj = NSAttributedString.Create (new NSData (), markdownOptions, null, out var e); - Assert.IsNotNull (obj, "IsNull"); - Assert.IsNull (e, "Error"); + Assert.That (obj, Is.Not.Null, "IsNull"); + Assert.That (e, Is.Null, "Error"); } @@ -237,8 +215,8 @@ public void Create_Markdown_String () { using var markdownOptions = new NSAttributedStringMarkdownParsingOptions (); using var obj = NSAttributedString.Create ("#markdown", markdownOptions, null, out var e); - Assert.IsNotNull (obj, "IsNull"); - Assert.IsNull (e, "Error"); + Assert.That (obj, Is.Not.Null, "IsNull"); + Assert.That (e, Is.Null, "Error"); } [Test] @@ -311,14 +289,14 @@ public void NullOnFailureTest () Assert.Multiple (() => { // I wasn't able to figure out any string that would make 'CreateWithHTML' fail :/ // var invalidHtml = NSData.FromArray ([(int) '?']); - Assert.IsNull (NSAttributedString.CreateWithRTF (NSData.FromArray ([0]), out var _), "CreateWithRTF"); - Assert.IsNull (NSAttributedString.CreateWithRTFD (NSData.FromArray ([0]), out var _), "CreateWithRTFD"); - // Assert.IsNull (NSAttributedString.CreateWithHTML (invalidHtml, out var _), "CreateWithHTML"); - // Assert.IsNull (NSAttributedString.CreateWithHTML (invalidHtml, NSUrl.CreateFileUrl ("/tmp"), out var _), "CreateWithHTML/NSUrl"); - // Assert.IsNull (NSAttributedString.CreateWithHTML (invalidHtml, new NSDictionary (), out var _), "CreateWithHTML/NSDictionary"); - // Assert.IsNull (NSAttributedString.CreateWithHTML (invalidHtml, new NSAttributedStringDocumentAttributes (), out var _), "CreateWithHTML/NSAttributedStringDocumentAttributes"); - Assert.IsNull (NSAttributedString.CreateWithDocFormat (NSData.FromArray ([0]), out var _), "CreateWithDocFormat"); - Assert.IsNull (NSAttributedString.Create (new NSFileWrapper (NSData.FromArray ([0])), out var _), "Create/NSFileWrapper"); + Assert.That (NSAttributedString.CreateWithRTF (NSData.FromArray ([0]), out var _), Is.Null, "CreateWithRTF"); + Assert.That (NSAttributedString.CreateWithRTFD (NSData.FromArray ([0]), out var _), Is.Null, "CreateWithRTFD"); + // Assert.That (NSAttributedString.CreateWithHTML (invalidHtml, out var _), Is.Null, "CreateWithHTML"); + // Assert.That (NSAttributedString.CreateWithHTML (invalidHtml, NSUrl.CreateFileUrl ("/tmp"), out var _), Is.Null, "CreateWithHTML/NSUrl"); + // Assert.That (NSAttributedString.CreateWithHTML (invalidHtml, new NSDictionary (), out var _), Is.Null, "CreateWithHTML/NSDictionary"); + // Assert.That (NSAttributedString.CreateWithHTML (invalidHtml, new NSAttributedStringDocumentAttributes (), out var _), Is.Null, "CreateWithHTML/NSAttributedStringDocumentAttributes"); + Assert.That (NSAttributedString.CreateWithDocFormat (NSData.FromArray ([0]), out var _), Is.Null, "CreateWithDocFormat"); + Assert.That (NSAttributedString.Create (new NSFileWrapper (NSData.FromArray ([0])), out var _), Is.Null, "Create/NSFileWrapper"); }); } #endif diff --git a/tests/monotouch-test/Foundation/BundleTest.cs b/tests/monotouch-test/Foundation/BundleTest.cs index 8e9dce9200c9..7eddae9c33db 100644 --- a/tests/monotouch-test/Foundation/BundleTest.cs +++ b/tests/monotouch-test/Foundation/BundleTest.cs @@ -59,9 +59,9 @@ public void LoadNibWithOptions () { #if MONOMAC NSArray objects; - Assert.NotNull (main.LoadNibNamed ("EmptyNib", main, out objects)); + Assert.That (main.LoadNibNamed ("EmptyNib", main, out objects), Is.Not.Null); #else - Assert.NotNull (main.LoadNib ("EmptyNib", main, null)); + Assert.That (main.LoadNib ("EmptyNib", main, null), Is.Not.Null); #endif } #endif diff --git a/tests/monotouch-test/Foundation/CachedUrlResponseTest.cs b/tests/monotouch-test/Foundation/CachedUrlResponseTest.cs index 9528ef63b6f8..f4dce75308dd 100644 --- a/tests/monotouch-test/Foundation/CachedUrlResponseTest.cs +++ b/tests/monotouch-test/Foundation/CachedUrlResponseTest.cs @@ -15,12 +15,12 @@ public void ConstructorTest () // Test that UserInfo is NullAllowed using (var res1 = new NSCachedUrlResponse (response, data, null, NSUrlCacheStoragePolicy.Allowed)) { Assert.That (res1.StoragePolicy, Is.EqualTo (NSUrlCacheStoragePolicy.Allowed), "StoragePolicy-1"); - Assert.Null (res1.UserInfo, "UserInfo-1"); + Assert.That (res1.UserInfo, Is.Null, "UserInfo-1"); } using (var res2 = new NSCachedUrlResponse (response, data)) { Assert.That (res2.StoragePolicy, Is.EqualTo (NSUrlCacheStoragePolicy.Allowed), "StoragePolicy-2"); - Assert.Null (res2.UserInfo, "UserInfo-2"); + Assert.That (res2.UserInfo, Is.Null, "UserInfo-2"); } } } diff --git a/tests/monotouch-test/Foundation/CalendarTest.cs b/tests/monotouch-test/Foundation/CalendarTest.cs index 2245987ca8e1..558e9d1ceb39 100644 --- a/tests/monotouch-test/Foundation/CalendarTest.cs +++ b/tests/monotouch-test/Foundation/CalendarTest.cs @@ -21,14 +21,14 @@ public void DateComponentsTest () cal.TimeZone = NSTimeZone.FromName ("UTC"); comps = cal.Components (NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, (NSDate) now); - Assert.AreEqual ((nint) now.Year, comps.Year, "a year"); - Assert.AreEqual ((nint) now.Month, comps.Month, "a month"); - Assert.AreEqual ((nint) now.Day, comps.Day, "a day"); + Assert.That (comps.Year, Is.EqualTo ((nint) now.Year), "a year"); + Assert.That (comps.Month, Is.EqualTo ((nint) now.Month), "a month"); + Assert.That (comps.Day, Is.EqualTo ((nint) now.Day), "a day"); var dayCompare = now; comps = cal.Components (NSCalendarUnit.Hour, (NSDate) dayCompare.AddHours (-1), (NSDate) dayCompare, NSCalendarOptions.None); - Assert.AreEqual ((nint) 1, comps.Hour, "c hour"); + Assert.That (comps.Hour, Is.EqualTo ((nint) 1), "c hour"); } [Test] @@ -44,7 +44,7 @@ public void DateByAddingComponentsTest () cal.TimeZone = comps.TimeZone; date = cal.DateByAddingComponents (comps, now, NSCalendarOptions.None); - Assert.AreEqual (now.SecondsSinceReferenceDate + 3600 * 24 * 2, date.SecondsSinceReferenceDate, "b"); + Assert.That (date.SecondsSinceReferenceDate, Is.EqualTo (now.SecondsSinceReferenceDate + 3600 * 24 * 2), "b"); } [Test] @@ -60,7 +60,7 @@ public void DateFromComponents () comps.Second = 0; comps.TimeZone = new NSTimeZone ("Europe/Madrid"); var date = cal.DateFromComponents (comps); - Assert.AreEqual (-1135594200d, date.SecondsSinceReferenceDate, "a"); + Assert.That (date.SecondsSinceReferenceDate, Is.EqualTo (-1135594200d), "a"); } static void RequiresIos8 () @@ -98,7 +98,7 @@ public void GetAllCalendarIdentifiers () break; } using var c = new NSCalendar (t); - Assert.IsNotNull (c.Identifier, "Can't find identifier: " + t.ToString ()); + Assert.That (c.Identifier, Is.Not.Null, "Can't find identifier: " + t.ToString ()); } } @@ -107,26 +107,26 @@ public void TestCalendarSymbols () { RequiresIos8 (); - Assert.IsTrue (NSCalendar.CurrentCalendar.EraSymbols.Length > 0, "EraSymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.LongEraSymbols.Length > 0, "LongEraSymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.MonthSymbols.Length > 0, "MonthSymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.ShortMonthSymbols.Length > 0, "ShortMonthSymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.VeryShortMonthSymbols.Length > 0, "VeryShortMonthSymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.StandaloneMonthSymbols.Length > 0, "StandaloneMonthSymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.ShortStandaloneMonthSymbols.Length > 0, "ShortStandaloneMonthSymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.VeryShortStandaloneMonthSymbols.Length > 0, "VeryShortStandaloneMonthSymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.WeekdaySymbols.Length > 0, "WeekdaySymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.ShortWeekdaySymbols.Length > 0, "ShortWeekdaySymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.VeryShortWeekdaySymbols.Length > 0, "VeryShortWeekdaySymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.StandaloneWeekdaySymbols.Length > 0, "StandaloneWeekdaySymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.ShortStandaloneWeekdaySymbols.Length > 0, "ShortStandaloneWeekdaySymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.VeryShortStandaloneWeekdaySymbols.Length > 0, "VeryShortStandaloneWeekdaySymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.QuarterSymbols.Length > 0, "QuarterSymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.ShortQuarterSymbols.Length > 0, "ShortQuarterSymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.StandaloneQuarterSymbols.Length > 0, "StandaloneQuarterSymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.ShortStandaloneQuarterSymbols.Length > 0, "ShortStandaloneQuarterSymbols not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.AMSymbol.Length > 0, "AMSymbol not found"); - Assert.IsTrue (NSCalendar.CurrentCalendar.PMSymbol.Length > 0, "PMSymbol not found"); + Assert.That (NSCalendar.CurrentCalendar.EraSymbols.Length > 0, Is.True, "EraSymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.LongEraSymbols.Length > 0, Is.True, "LongEraSymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.MonthSymbols.Length > 0, Is.True, "MonthSymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.ShortMonthSymbols.Length > 0, Is.True, "ShortMonthSymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.VeryShortMonthSymbols.Length > 0, Is.True, "VeryShortMonthSymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.StandaloneMonthSymbols.Length > 0, Is.True, "StandaloneMonthSymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.ShortStandaloneMonthSymbols.Length > 0, Is.True, "ShortStandaloneMonthSymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.VeryShortStandaloneMonthSymbols.Length > 0, Is.True, "VeryShortStandaloneMonthSymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.WeekdaySymbols.Length > 0, Is.True, "WeekdaySymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.ShortWeekdaySymbols.Length > 0, Is.True, "ShortWeekdaySymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.VeryShortWeekdaySymbols.Length > 0, Is.True, "VeryShortWeekdaySymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.StandaloneWeekdaySymbols.Length > 0, Is.True, "StandaloneWeekdaySymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.ShortStandaloneWeekdaySymbols.Length > 0, Is.True, "ShortStandaloneWeekdaySymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.VeryShortStandaloneWeekdaySymbols.Length > 0, Is.True, "VeryShortStandaloneWeekdaySymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.QuarterSymbols.Length > 0, Is.True, "QuarterSymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.ShortQuarterSymbols.Length > 0, Is.True, "ShortQuarterSymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.StandaloneQuarterSymbols.Length > 0, Is.True, "StandaloneQuarterSymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.ShortStandaloneQuarterSymbols.Length > 0, Is.True, "ShortStandaloneQuarterSymbols not found"); + Assert.That (NSCalendar.CurrentCalendar.AMSymbol.Length > 0, Is.True, "AMSymbol not found"); + Assert.That (NSCalendar.CurrentCalendar.PMSymbol.Length > 0, Is.True, "PMSymbol not found"); } [Test] @@ -138,7 +138,7 @@ public void TestCalendarComparision () NSDate todayPlusSeconds = NowPlusTenSeconds; if (NSCalendar.CurrentCalendar.CompareDate (today, todayPlusSeconds, NSCalendarUnit.Day) != NSComparisonResult.Same) Assert.Inconclusive ("Now plus 10 seconds isn't the same day, either a bug or run < 10 seconds before midnight"); - Assert.IsFalse (NSCalendar.CurrentCalendar.CompareDate (today, todayPlusSeconds, NSCalendarUnit.Second) == NSComparisonResult.Same, "Now plus 10 seconds shouldn't be the same second"); + Assert.That (NSCalendar.CurrentCalendar.CompareDate (today, todayPlusSeconds, NSCalendarUnit.Second) == NSComparisonResult.Same, Is.False, "Now plus 10 seconds shouldn't be the same second"); } [Test] @@ -148,30 +148,30 @@ public void TestCalendarComponents () nint era, year, month, day = -1; NSCalendar.CurrentCalendar.GetComponentsFromDate (out era, out year, out month, out day, NSDate.Now); - Assert.IsTrue (era >= 0, "GetComponentsFromDate - era"); - Assert.IsTrue (year >= 0, "GetComponentsFromDate - year"); - Assert.IsTrue (month >= 0, "GetComponentsFromDate - month"); - Assert.IsTrue (day >= 0, "GetComponentsFromDate - day"); + Assert.That (era >= 0, Is.True, "GetComponentsFromDate - era"); + Assert.That (year >= 0, Is.True, "GetComponentsFromDate - year"); + Assert.That (month >= 0, Is.True, "GetComponentsFromDate - month"); + Assert.That (day >= 0, Is.True, "GetComponentsFromDate - day"); nint weekOfYear, weekday = -1; era = year = -1; NSCalendar.CurrentCalendar.GetComponentsFromDateForWeekOfYear (out era, out year, out weekOfYear, out weekday, NSDate.Now); - Assert.IsTrue (era >= 0, "GetComponentsFromDateForWeekOfYear - era"); - Assert.IsTrue (year >= 0, "GetComponentsFromDateForWeekOfYear - year"); - Assert.IsTrue (weekOfYear >= 0, "GetComponentsFromDateForWeekOfYear - weekOfYear"); - Assert.IsTrue (weekday >= 0, "GetComponentsFromDateForWeekOfYear - weekday"); + Assert.That (era >= 0, Is.True, "GetComponentsFromDateForWeekOfYear - era"); + Assert.That (year >= 0, Is.True, "GetComponentsFromDateForWeekOfYear - year"); + Assert.That (weekOfYear >= 0, Is.True, "GetComponentsFromDateForWeekOfYear - weekOfYear"); + Assert.That (weekday >= 0, Is.True, "GetComponentsFromDateForWeekOfYear - weekday"); nint hour, minute, second, nanosecond = -1; NSCalendar.CurrentCalendar.GetHourComponentsFromDate (out hour, out minute, out second, out nanosecond, NSDate.Now); - Assert.IsTrue (hour >= 0, "GetHourComponentsFromDate - hour"); - Assert.IsTrue (minute >= 0, "GetHourComponentsFromDate - minute"); - Assert.IsTrue (second >= 0, "GetHourComponentsFromDate - second"); - Assert.IsTrue (nanosecond >= 0, "GetHourComponentsFromDate - nanosecond"); - - Assert.IsTrue (NSCalendar.CurrentCalendar.GetComponentFromDate (NSCalendarUnit.Day, NSDate.Now) > 0, "GetComponentFromDate - day"); - Assert.IsTrue (NSCalendar.CurrentCalendar.GetComponentFromDate (NSCalendarUnit.Week, NSDate.Now) > 0, "GetComponentFromDate - week"); - Assert.IsTrue (NSCalendar.CurrentCalendar.GetComponentFromDate (NSCalendarUnit.Month, NSDate.Now) > 0, "GetComponentFromDate - month"); - Assert.IsTrue (NSCalendar.CurrentCalendar.GetComponentFromDate (NSCalendarUnit.Year, NSDate.Now) > 0, "GetComponentFromDate - year"); + Assert.That (hour >= 0, Is.True, "GetHourComponentsFromDate - hour"); + Assert.That (minute >= 0, Is.True, "GetHourComponentsFromDate - minute"); + Assert.That (second >= 0, Is.True, "GetHourComponentsFromDate - second"); + Assert.That (nanosecond >= 0, Is.True, "GetHourComponentsFromDate - nanosecond"); + + Assert.That (NSCalendar.CurrentCalendar.GetComponentFromDate (NSCalendarUnit.Day, NSDate.Now) > 0, Is.True, "GetComponentFromDate - day"); + Assert.That (NSCalendar.CurrentCalendar.GetComponentFromDate (NSCalendarUnit.Week, NSDate.Now) > 0, Is.True, "GetComponentFromDate - week"); + Assert.That (NSCalendar.CurrentCalendar.GetComponentFromDate (NSCalendarUnit.Month, NSDate.Now) > 0, Is.True, "GetComponentFromDate - month"); + Assert.That (NSCalendar.CurrentCalendar.GetComponentFromDate (NSCalendarUnit.Year, NSDate.Now) > 0, Is.True, "GetComponentFromDate - year"); } [Test] @@ -183,7 +183,7 @@ public void TestComponentsFromDateToDate () NSDateComponents tomorrowComponents = NSCalendar.CurrentCalendar.Components (NSCalendarUnit.Day | NSCalendarUnit.Month | NSCalendarUnit.Year, Tomorrow); NSDateComponents components = NSCalendar.CurrentCalendar.ComponentsFromDateToDate (NSCalendarUnit.Day | NSCalendarUnit.Month, todayComponents, tomorrowComponents, NSCalendarOptions.None); - Assert.AreEqual ((nint) 1, components.Day, "One day passed between today and tomorrow"); + Assert.That (components.Day, Is.EqualTo ((nint) 1), "One day passed between today and tomorrow"); } [Test] @@ -198,7 +198,7 @@ public void TestComponentsInTimeZone () Assert.Inconclusive ("Same time zone, change Asia/Bangkok"); NSDateComponents components = NSCalendar.CurrentCalendar.ComponentsInTimeZone (otherZone, NSDate.Now); - Assert.IsTrue (components.Hour != NSCalendar.CurrentCalendar.Components (NSCalendarUnit.Hour, NSDate.Now).Hour, "Different time zones should have different hours"); + Assert.That (components.Hour != NSCalendar.CurrentCalendar.Components (NSCalendarUnit.Hour, NSDate.Now).Hour, Is.True, "Different time zones should have different hours"); } [Test] @@ -212,7 +212,7 @@ public void TestMatchesComponents () if (futureMatch ^ pastMatch) // While unlikley, if you run it within 10 seconds of a day boundry, we can get inconclusive results. Better this than a random failure Assert.Inconclusive ("Test was run with 10 seconds of a day switchover (unlikely) or malfunctioned."); - Assert.IsTrue (futureMatch && pastMatch, "10 seconds on both side of us should both be on same day or Inconclusive"); + Assert.That (futureMatch && pastMatch, Is.True, "10 seconds on both side of us should both be on same day or Inconclusive"); } [Test] @@ -223,7 +223,7 @@ public void TestAddingByComponents () NSDate now = NSDate.Now; NSDate oneDayFromNow = NSCalendar.CurrentCalendar.DateByAddingUnit (NSCalendarUnit.Day, 1, now, NSCalendarOptions.None); - Assert.IsTrue (NSCalendar.CurrentCalendar.IsEqualToUnitGranularity (Tomorrow, oneDayFromNow, NSCalendarUnit.Day), $"oneDayFromNow: DateByAddingUnit - One day from now should be tomorrow {Tomorrow} != {oneDayFromNow}"); + Assert.That (NSCalendar.CurrentCalendar.IsEqualToUnitGranularity (Tomorrow, oneDayFromNow, NSCalendarUnit.Day), Is.True, $"oneDayFromNow: DateByAddingUnit - One day from now should be tomorrow {Tomorrow} != {oneDayFromNow}"); var todayDayNumber = NSCalendar.CurrentCalendar.GetComponentFromDate (NSCalendarUnit.Day, NSDate.Now); NSDate todayPlusADay = NSCalendar.CurrentCalendar.DateBySettingUnit (NSCalendarUnit.Day, todayDayNumber + 1, now, NSCalendarOptions.None); @@ -235,7 +235,7 @@ public void TestAddingByComponents () var todayYearNumber = NSCalendar.CurrentCalendar.GetComponentFromDate (NSCalendarUnit.Year, now); todayPlusADay = NSCalendar.CurrentCalendar.DateBySettingUnit (NSCalendarUnit.Year, todayYearNumber + 1, now, NSCalendarOptions.None); } - Assert.IsTrue (NSCalendar.CurrentCalendar.IsEqualToUnitGranularity (Tomorrow, todayPlusADay, NSCalendarUnit.Day), $"todayPlusADay: lDateBySettingUnit - One day from now should be tomorrow {Tomorrow} != {todayPlusADay}"); + Assert.That (NSCalendar.CurrentCalendar.IsEqualToUnitGranularity (Tomorrow, todayPlusADay, NSCalendarUnit.Day), Is.True, $"todayPlusADay: lDateBySettingUnit - One day from now should be tomorrow {Tomorrow} != {todayPlusADay}"); } [Test] @@ -247,7 +247,7 @@ public void TestSettingHourComponent () NSDate oneHourFromNow = NSCalendar.CurrentCalendar.DateBySettingsHour (currentHour + 1, 0, 0, NSDate.Now, NSCalendarOptions.None); if (oneHourFromNow is null) Assert.Inconclusive ("Test does not handle day change"); - Assert.IsTrue ((currentHour + 1) == NSCalendar.CurrentCalendar.GetComponentFromDate (NSCalendarUnit.Hour, oneHourFromNow), "DateBySettingsHour - One hour from now should be one hour"); + Assert.That ((currentHour + 1) == NSCalendar.CurrentCalendar.GetComponentFromDate (NSCalendarUnit.Hour, oneHourFromNow), Is.True, "DateBySettingsHour - One hour from now should be one hour"); } [Test] @@ -267,9 +267,9 @@ public void TestNSCalendarConstructors () RequiresIos8 (); NSDate date1 = NSCalendar.CurrentCalendar.Date (1, 2, 3, 4, 5, 6, 7, 8); - Assert.IsNotNull (date1, "Date constructor 1"); + Assert.That (date1, Is.Not.Null, "Date constructor 1"); NSDate date2 = NSCalendar.CurrentCalendar.DateForWeekOfYear (1, 2, 3, 4, 5, 6, 7, 8); - Assert.IsNotNull (date2, "Date constructor 2"); + Assert.That (date2, Is.Not.Null, "Date constructor 2"); } [Test] @@ -277,21 +277,21 @@ public void TestIsDateMethods () { RequiresIos8 (); - Assert.IsTrue (NSCalendar.CurrentCalendar.IsDateInToday (NSDate.Now), "IsDateInToday positive"); - Assert.IsFalse (NSCalendar.CurrentCalendar.IsDateInToday (Tomorrow), "IsDateInToday negative"); + Assert.That (NSCalendar.CurrentCalendar.IsDateInToday (NSDate.Now), Is.True, "IsDateInToday positive"); + Assert.That (NSCalendar.CurrentCalendar.IsDateInToday (Tomorrow), Is.False, "IsDateInToday negative"); - Assert.IsFalse (NSCalendar.CurrentCalendar.IsDateInTomorrow (NSDate.Now), "IsDateInTomorrow negative"); - Assert.IsTrue (NSCalendar.CurrentCalendar.IsDateInTomorrow (Tomorrow), "IsDateInTomorrow positive"); + Assert.That (NSCalendar.CurrentCalendar.IsDateInTomorrow (NSDate.Now), Is.False, "IsDateInTomorrow negative"); + Assert.That (NSCalendar.CurrentCalendar.IsDateInTomorrow (Tomorrow), Is.True, "IsDateInTomorrow positive"); - Assert.IsFalse (NSCalendar.CurrentCalendar.IsDateInYesterday (NSDate.Now), "IsDateInYesterday negative"); - Assert.IsTrue (NSCalendar.CurrentCalendar.IsDateInYesterday (Yesterday), "IsDateInYesterday positive"); + Assert.That (NSCalendar.CurrentCalendar.IsDateInYesterday (NSDate.Now), Is.False, "IsDateInYesterday negative"); + Assert.That (NSCalendar.CurrentCalendar.IsDateInYesterday (Yesterday), Is.True, "IsDateInYesterday positive"); - Assert.IsFalse (NSCalendar.CurrentCalendar.IsInSameDay (NSDate.Now, Tomorrow), "IsInSameDay negative"); + Assert.That (NSCalendar.CurrentCalendar.IsInSameDay (NSDate.Now, Tomorrow), Is.False, "IsInSameDay negative"); NSDate weekend; double length; NSCalendar.CurrentCalendar.FindNextWeekend (out weekend, out length, NSCalendarOptions.None, NSDate.Now); - Assert.IsTrue (NSCalendar.CurrentCalendar.IsDateInWeekend (weekend), "IsDateInWeekend positive"); + Assert.That (NSCalendar.CurrentCalendar.IsDateInWeekend (weekend), Is.True, "IsDateInWeekend positive"); } [Test] @@ -307,7 +307,7 @@ public void TestRangeOfWeekendContainingDate () double length2; NSCalendar.CurrentCalendar.RangeOfWeekendContainingDate (out weekend2, out length2, weekend); - Assert.IsTrue (NSCalendar.CurrentCalendar.CompareDate (weekend, weekend2, NSCalendarUnit.Day) == NSComparisonResult.Same, "Weekend test"); + Assert.That (NSCalendar.CurrentCalendar.CompareDate (weekend, weekend2, NSCalendarUnit.Day) == NSComparisonResult.Same, Is.True, "Weekend test"); } [Test] @@ -316,7 +316,7 @@ public void TestStartOfDay () RequiresIos8 (); NSDate firstMomentOfToday = NSCalendar.CurrentCalendar.StartOfDayForDate (NSDate.Now); - Assert.IsTrue (NSCalendar.CurrentCalendar.CompareDate (firstMomentOfToday, NSDate.Now, NSCalendarUnit.Day) == NSComparisonResult.Same, "StartOfDayForDate"); + Assert.That (NSCalendar.CurrentCalendar.CompareDate (firstMomentOfToday, NSDate.Now, NSCalendarUnit.Day) == NSComparisonResult.Same, Is.True, "StartOfDayForDate"); } [Test] @@ -328,13 +328,13 @@ public void TestFindNextDate () nextYearComponent.Year++; NSDate nextYear = NSCalendar.CurrentCalendar.FindNextDateAfterDateMatching (NSDate.Now, nextYearComponent, NSCalendarOptions.MatchNextTime); - Assert.IsNotNull (nextYear, "FindNextDateAfterDateMatching"); + Assert.That (nextYear, Is.Not.Null, "FindNextDateAfterDateMatching"); NSDate nextNoon = NSCalendar.CurrentCalendar.FindNextDateAfterDateMatching (NSDate.Now, 12, 0, 0, NSCalendarOptions.MatchNextTime); - Assert.IsNotNull (nextNoon, "FindNextDateAfterDateMatching 2"); + Assert.That (nextNoon, Is.Not.Null, "FindNextDateAfterDateMatching 2"); NSDate nextNoonAgain = NSCalendar.CurrentCalendar.FindNextDateAfterDateMatching (NSDate.Now, NSCalendarUnit.Hour, 12, NSCalendarOptions.MatchNextTime); - Assert.IsNotNull (nextNoonAgain, "FindNextDateAfterDateMatching 3"); + Assert.That (nextNoonAgain, Is.Not.Null, "FindNextDateAfterDateMatching 3"); } [Test] @@ -349,7 +349,7 @@ public void TestEnumerateDates () delegateHit = true; stop = true; }); - Assert.IsTrue (delegateHit, "EnumerateDatesStartingAfterDate delegate called"); + Assert.That (delegateHit, Is.True, "EnumerateDatesStartingAfterDate delegate called"); } [Test] @@ -359,11 +359,11 @@ public void TestNSDateComponentNewAPIs () NSDateComponents todayComponents = NSCalendar.CurrentCalendar.Components (NSCalendarUnit.Day | NSCalendarUnit.Month | NSCalendarUnit.Year | NSCalendarUnit.Era | NSCalendarUnit.Calendar, NSDate.Now); var nano = todayComponents.Nanosecond; - Assert.IsTrue (todayComponents.IsValidDate, "IsValidDate"); - Assert.IsTrue (todayComponents.IsValidDateInCalendar (NSCalendar.CurrentCalendar), "IsValidDateInCalendar"); + Assert.That (todayComponents.IsValidDate, Is.True, "IsValidDate"); + Assert.That (todayComponents.IsValidDateInCalendar (NSCalendar.CurrentCalendar), Is.True, "IsValidDateInCalendar"); todayComponents.SetValueForComponent (12, NSCalendarUnit.Day); - Assert.AreEqual ((nint) 12, todayComponents.GetValueForComponent (NSCalendarUnit.Day), "GetValueForComponent\\SetValueForComponent"); + Assert.That (todayComponents.GetValueForComponent (NSCalendarUnit.Day), Is.EqualTo ((nint) 12), "GetValueForComponent\\SetValueForComponent"); } [Test] @@ -373,11 +373,11 @@ public void TestFindNextDateAfterDateMatching () NSDateComponents nextYearComponent = new NSDateComponents (); if (TestRuntime.CheckXcodeVersion (15, 0)) { - Assert.IsNull (NSCalendar.CurrentCalendar.FindNextDateAfterDateMatching (NSDate.Now, nextYearComponent, NSCalendarOptions.None), "nextYearComponent"); + Assert.That (NSCalendar.CurrentCalendar.FindNextDateAfterDateMatching (NSDate.Now, nextYearComponent, NSCalendarOptions.None), Is.Null, "nextYearComponent"); - Assert.NotNull (NSCalendar.CurrentCalendar.FindNextDateAfterDateMatching (NSDate.Now, NSCalendarUnit.Day, 8, NSCalendarOptions.None), "Unit"); + Assert.That (NSCalendar.CurrentCalendar.FindNextDateAfterDateMatching (NSDate.Now, NSCalendarUnit.Day, 8, NSCalendarOptions.None), Is.Not.Null, "Unit"); - Assert.NotNull (NSCalendar.CurrentCalendar.FindNextDateAfterDateMatching (NSDate.Now, 1, 2, 3, NSCalendarOptions.None), "components"); + Assert.That (NSCalendar.CurrentCalendar.FindNextDateAfterDateMatching (NSDate.Now, 1, 2, 3, NSCalendarOptions.None), Is.Not.Null, "components"); } else { Assert.Throws (() => NSCalendar.CurrentCalendar.FindNextDateAfterDateMatching (NSDate.Now, nextYearComponent, NSCalendarOptions.None), "nextYearComponent"); @@ -397,8 +397,8 @@ public void TestMinimumRange (int location, int length, NSCalendarUnit unit) { var cal = new NSCalendar (NSCalendarType.Gregorian); var range = cal.MinimumRange (unit); - Assert.AreEqual ((nint) location, range.Location); - Assert.AreEqual ((nint) length, range.Length); + Assert.That (range.Location, Is.EqualTo ((nint) location)); + Assert.That (range.Length, Is.EqualTo ((nint) length)); } [TestCase (1, 12, NSCalendarUnit.Month)] @@ -408,8 +408,8 @@ public void TestMaximumRange (int location, int length, NSCalendarUnit unit) { var cal = new NSCalendar (NSCalendarType.Gregorian); var range = cal.MaximumRange (unit); - Assert.AreEqual ((nint) length, range.Length); - Assert.AreEqual ((nint) location, range.Location); + Assert.That (range.Length, Is.EqualTo ((nint) length)); + Assert.That (range.Location, Is.EqualTo ((nint) location)); } [TestCase (2010, 1, 11, 1, 31, NSCalendarUnit.Day, NSCalendarUnit.Month)] @@ -422,8 +422,8 @@ public void TestRange (int year, int month, int day, int location, int length, N var date = new DateTime (year, month, day); date = DateTime.SpecifyKind (date, DateTimeKind.Utc); var range = cal.Range (smaller, larger, (NSDate) date); - Assert.AreEqual ((nint) location, range.Location); - Assert.AreEqual ((nint) length, range.Length); + Assert.That (range.Location, Is.EqualTo ((nint) location)); + Assert.That (range.Length, Is.EqualTo ((nint) length)); } [TestCase (2010, 1, 11, NSCalendarUnit.Day, NSCalendarUnit.Month, 11)] @@ -434,7 +434,7 @@ public void TestOrdinality (int year, int month, int day, NSCalendarUnit smaller var date = new DateTime (year, month, day, 0, 0, 0, DateTimeKind.Utc); var dt = (NSDate) date; cal.TimeZone = NSTimeZone.FromName ("Europe/Madrid"); - Assert.AreEqual ((nuint) expected, cal.Ordinality (smaller, larger, dt), $"Ordinality"); + Assert.That (cal.Ordinality (smaller, larger, dt), Is.EqualTo ((nuint) expected), $"Ordinality"); } [TestCase (2010, 1, 11, NSCalendarUnit.Day, 86400.0)] @@ -448,7 +448,7 @@ public void TestRangeOrUnitInterval (int year, int month, int day, NSCalendarUni NSDate outDate = null; double outInterval; var success = cal.Range (unit, out outDate, out outInterval, (NSDate) date); - Assert.AreEqual (expectedInterval, outInterval); + Assert.That (outInterval, Is.EqualTo (expectedInterval)); } [TestCase (2010, 1, 11, NSCalendarUnit.Day, 86400.0)] @@ -462,7 +462,7 @@ public void TestRangeOrUnitIntervalNotNull (int year, int month, int day, NSCale var outDate = (NSDate) DateTime.Now; double outInterval; var success = cal.Range (unit, out outDate, out outInterval, (NSDate) date); - Assert.AreEqual (expectedInterval, outInterval); + Assert.That (outInterval, Is.EqualTo (expectedInterval)); } } diff --git a/tests/monotouch-test/Foundation/CoderTest.cs b/tests/monotouch-test/Foundation/CoderTest.cs index 8a1306998dc2..624e0b12c227 100644 --- a/tests/monotouch-test/Foundation/CoderTest.cs +++ b/tests/monotouch-test/Foundation/CoderTest.cs @@ -38,25 +38,25 @@ public void EncodeDecodeTest () } using (var decoder = new NSKeyedUnarchiver (mutableData)) { - Assert.IsNotNull (decoder.DecodeObject ("obj")); + Assert.That (decoder.DecodeObject ("obj"), Is.Not.Null); var buf = decoder.DecodeBytes ("buffer"); - Assert.AreEqual (buf.Length, buffer.Length, "buffer.length"); + Assert.That (buffer.Length, Is.EqualTo (buf.Length), "buffer.length"); for (int i = 0; i < buf.Length; i++) - Assert.AreEqual (buf [i], buffer [i], "buffer [" + i.ToString () + "]"); - Assert.AreEqual (Int32.MaxValue, decoder.DecodeInt ("int32")); - Assert.AreEqual (float.MaxValue, decoder.DecodeFloat ("float")); - Assert.AreEqual (true, decoder.DecodeBool ("bool")); - Assert.AreEqual (long.MaxValue, decoder.DecodeLong ("long")); + Assert.That (buffer [i], Is.EqualTo (buf [i]), "buffer [" + i.ToString () + "]"); + Assert.That (decoder.DecodeInt ("int32"), Is.EqualTo (Int32.MaxValue)); + Assert.That (decoder.DecodeFloat ("float"), Is.EqualTo (float.MaxValue)); + Assert.That (decoder.DecodeBool ("bool"), Is.EqualTo (true)); + Assert.That (decoder.DecodeLong ("long"), Is.EqualTo (long.MaxValue)); buf = decoder.DecodeBytes ("buffer2"); - Assert.AreEqual (buf.Length, buffer.Length, "buffer2.length"); + Assert.That (buffer.Length, Is.EqualTo (buf.Length), "buffer2.length"); for (int i = 0; i < buf.Length; i++) - Assert.AreEqual (buf [i], buffer [i], "buffer2 [" + i.ToString () + "]"); - Assert.AreEqual (nint.MaxValue, decoder.DecodeNInt ("nint")); + Assert.That (buffer [i], Is.EqualTo (buf [i]), "buffer2 [" + i.ToString () + "]"); + Assert.That (decoder.DecodeNInt ("nint"), Is.EqualTo (nint.MaxValue)); buf = decoder.DecodeBytes ("block"); - Assert.AreEqual (buf.Length, buffer.Length, "block.length"); + Assert.That (buffer.Length, Is.EqualTo (buf.Length), "block.length"); for (int i = 0; i < buf.Length; i++) - Assert.AreEqual (buf [i], buffer [i], "block [" + i.ToString () + "]"); + Assert.That (buffer [i], Is.EqualTo (buf [i]), "block [" + i.ToString () + "]"); } } diff --git a/tests/monotouch-test/Foundation/CookieTest.cs b/tests/monotouch-test/Foundation/CookieTest.cs index cf77e20104d3..c9b62821a218 100644 --- a/tests/monotouch-test/Foundation/CookieTest.cs +++ b/tests/monotouch-test/Foundation/CookieTest.cs @@ -49,11 +49,11 @@ public void CookieFromProperties () props.Add (NSHttpCookie.KeyValue, new NSString ("ulikecookies")); var cookie = NSHttpCookie.CookieFromProperties (props); - Assert.Null (cookie, "missing path"); + Assert.That (cookie, Is.Null, "missing path"); props.Add (NSHttpCookie.KeyPath, new NSString ("/")); using (cookie = NSHttpCookie.CookieFromProperties (props)) { - Assert.NotNull (cookie, "w/path"); + Assert.That (cookie, Is.Not.Null, "w/path"); Assert.That (cookie.Domain, Is.EqualTo ("yodawg.com"), "Domain"); Assert.That (cookie.Name, Is.EqualTo ("iherd"), "Name"); @@ -120,14 +120,14 @@ public void DotNetInteropCommon () Assert.That (cookie.Path, Is.EqualTo ("path"), "Path"); Assert.That (cookie.Domain, Is.EqualTo ("domain"), "Domain"); // defaults - Assert.Null (cookie.Comment, "Comment"); - Assert.Null (cookie.CommentUrl, "CommentUrl"); - Assert.Null (cookie.ExpiresDate, "ExpiresDate"); - Assert.False (cookie.IsHttpOnly, "IsHttpOnly"); - Assert.False (cookie.IsSecure, "IsSecure"); - Assert.True (cookie.IsSessionOnly, "IsSessionOnly"); // discard + Assert.That (cookie.Comment, Is.Null, "Comment"); + Assert.That (cookie.CommentUrl, Is.Null, "CommentUrl"); + Assert.That (cookie.ExpiresDate, Is.Null, "ExpiresDate"); + Assert.That (cookie.IsHttpOnly, Is.False, "IsHttpOnly"); + Assert.That (cookie.IsSecure, Is.False, "IsSecure"); + Assert.That (cookie.IsSessionOnly, Is.True, "IsSessionOnly"); // discard Assert.That (cookie.PortList.Length, Is.EqualTo (0), "PortList"); - Assert.NotNull (cookie.Properties, "Properties"); + Assert.That (cookie.Properties, Is.Not.Null, "Properties"); Assert.That (cookie.Version, Is.EqualTo ((nuint) 0), "Version"); } } @@ -152,12 +152,12 @@ public void DotNetInteropMax () // custom values Assert.That (cookie.Comment, Is.EqualTo ("comment"), "Comment"); Assert.That (cookie.CommentUrl.ToString (), Is.EqualTo ("http://comment.uri/"), "CommentUrl"); - Assert.Null (cookie.ExpiresDate, "ExpiresDate"); // session-only always returns null - Assert.False (cookie.IsHttpOnly, "IsHttpOnly"); - Assert.True (cookie.IsSecure, "IsSecure"); - Assert.True (cookie.IsSessionOnly, "IsSessionOnly"); + Assert.That (cookie.ExpiresDate, Is.Null, "ExpiresDate"); // session-only always returns null + Assert.That (cookie.IsHttpOnly, Is.False, "IsHttpOnly"); + Assert.That (cookie.IsSecure, Is.True, "IsSecure"); + Assert.That (cookie.IsSessionOnly, Is.True, "IsSessionOnly"); Assert.That ((int) cookie.PortList [0], Is.EqualTo (80), "PortList"); - Assert.NotNull (cookie.Properties, "Properties"); + Assert.That (cookie.Properties, Is.Not.Null, "Properties"); Assert.That (cookie.Version, Is.EqualTo ((nuint) 1), "Version"); } } @@ -190,11 +190,11 @@ public void DotNetInterop_NonSession () // can be rounded up. This means that these two dates might be a second off. // So assert that they're no more than a second apart. Assert.That (Math.Abs ((dt1 - dt2).TotalSeconds), Is.LessThan (1.0), $"ExpiresDate"); - Assert.False (cookie.IsHttpOnly, "IsHttpOnly"); - Assert.True (cookie.IsSecure, "IsSecure"); - Assert.IsFalse (cookie.IsSessionOnly, "IsSessionOnly"); + Assert.That (cookie.IsHttpOnly, Is.False, "IsHttpOnly"); + Assert.That (cookie.IsSecure, Is.True, "IsSecure"); + Assert.That (cookie.IsSessionOnly, Is.False, "IsSessionOnly"); Assert.That ((int) cookie.PortList [0], Is.EqualTo (80), "PortList"); - Assert.NotNull (cookie.Properties, "Properties"); + Assert.That (cookie.Properties, Is.Not.Null, "Properties"); Assert.That (cookie.Version, Is.EqualTo ((nuint) 1), "Version"); } } diff --git a/tests/monotouch-test/Foundation/DateFormatterTest.cs b/tests/monotouch-test/Foundation/DateFormatterTest.cs index 0ca8d6388d43..938dc532293c 100644 --- a/tests/monotouch-test/Foundation/DateFormatterTest.cs +++ b/tests/monotouch-test/Foundation/DateFormatterTest.cs @@ -17,7 +17,7 @@ public class DateFormatterTest { public void ToLocalizedStringTest () { var str = NSDateFormatter.ToLocalizedString (NSDate.Now, NSDateFormatterStyle.Full, NSDateFormatterStyle.Full); - Assert.IsNotNull (str); + Assert.That (str, Is.Not.Null); } [Test] @@ -28,10 +28,10 @@ public void GetDateFormatFromTemplateTest () const string dateComponents = "yMMMMd"; var dateFormat = NSDateFormatter.GetDateFormatFromTemplate (dateComponents, 0, us_locale); - Assert.AreEqual ("MMMM d, y", dateFormat, "#US"); + Assert.That (dateFormat, Is.EqualTo ("MMMM d, y"), "#US"); dateFormat = NSDateFormatter.GetDateFormatFromTemplate (dateComponents, 0, gb_locale); - Assert.AreEqual ("d MMMM y", dateFormat, "GB"); + Assert.That (dateFormat, Is.EqualTo ("d MMMM y"), "GB"); } } } diff --git a/tests/monotouch-test/Foundation/DateTest.cs b/tests/monotouch-test/Foundation/DateTest.cs index 054ee792346d..54d23d37b6c3 100644 --- a/tests/monotouch-test/Foundation/DateTest.cs +++ b/tests/monotouch-test/Foundation/DateTest.cs @@ -22,18 +22,18 @@ public class DateTest { public void InLimits () { // .NET can represent this date just fine - Assert.AreEqual (new DateTime (4001, 01, 01), (DateTime) NSDate.DistantFuture, "distant future"); + Assert.That ((DateTime) NSDate.DistantFuture, Is.EqualTo (new DateTime (4001, 01, 01)), "distant future"); - Assert.AreEqual (DateTime.MinValue, (DateTime) NSDate.DistantPast, "distant past"); - Assert.AreEqual (DateTime.MinValue.AddSeconds (1), (DateTime) NSDate.FromTimeIntervalSinceReferenceDate (-63114076799), "-63114076799"); - Assert.AreEqual (DateTime.MinValue, (DateTime) NSDate.FromTimeIntervalSinceReferenceDate (-63114076800), "-63114076800"); + Assert.That ((DateTime) NSDate.DistantPast, Is.EqualTo (DateTime.MinValue), "distant past"); + Assert.That ((DateTime) NSDate.FromTimeIntervalSinceReferenceDate (-63114076799), Is.EqualTo (DateTime.MinValue.AddSeconds (1)), "-63114076799"); + Assert.That ((DateTime) NSDate.FromTimeIntervalSinceReferenceDate (-63114076800), Is.EqualTo (DateTime.MinValue), "-63114076800"); Asserts.AreEqual (DateTime.MaxValue, (DateTime) NSDate.FromTimeIntervalSinceReferenceDate (252423993599.9999), tolerance, "DateTime.MaxValue"); Asserts.AreEqual (DateTime.MaxValue, (DateTime) NSDate.FromTimeIntervalSinceReferenceDate (252423993599.9999999), tolerance, "DateTime.MaxValue"); Asserts.AreEqual (DateTime.MaxValue, (DateTime) NSDate.FromTimeIntervalSinceReferenceDate (252423993600), tolerance, "DateTime.MaxValue"); - Assert.AreEqual (new DateTime (9999, 12, 31, 23, 59, 58), (DateTime) NSDate.FromTimeIntervalSinceReferenceDate (252423993598), "252423993598"); - Assert.AreEqual (new DateTime (9999, 12, 31, 23, 59, 59), (DateTime) NSDate.FromTimeIntervalSinceReferenceDate (252423993599), "252423993599"); + Assert.That ((DateTime) NSDate.FromTimeIntervalSinceReferenceDate (252423993598), Is.EqualTo (new DateTime (9999, 12, 31, 23, 59, 58)), "252423993598"); + Assert.That ((DateTime) NSDate.FromTimeIntervalSinceReferenceDate (252423993599), Is.EqualTo (new DateTime (9999, 12, 31, 23, 59, 59)), "252423993599"); } static IEnumerable GetArgumentOutOfRangeExceptionValues () @@ -105,13 +105,13 @@ public void RoundTripFromNSDate (NSDate start, string message) { var date = (DateTime) start; var backAgain = (NSDate) date; - Assert.AreEqual (start, backAgain, message); + Assert.That (backAgain, Is.EqualTo (start), message); } [Test] public void DescriptionWithLocale () { - Assert.IsNotNull (NSDate.Now.DescriptionWithLocale (NSLocale.CurrentLocale), "1"); + Assert.That (NSDate.Now.DescriptionWithLocale (NSLocale.CurrentLocale), Is.Not.Null, "1"); } [TestCase (1, 1, 1, 1, 1, 1, 1)] diff --git a/tests/monotouch-test/Foundation/DecimalNumberTest.cs b/tests/monotouch-test/Foundation/DecimalNumberTest.cs index 0fa2bbf7636d..6dd89394dba6 100644 --- a/tests/monotouch-test/Foundation/DecimalNumberTest.cs +++ b/tests/monotouch-test/Foundation/DecimalNumberTest.cs @@ -16,7 +16,7 @@ public class DecimalNumberTest { [Test] public void One () { - Assert.NotNull (NSDecimalNumber.One, "One"); + Assert.That (NSDecimalNumber.One, Is.Not.Null, "One"); } } } diff --git a/tests/monotouch-test/Foundation/DictionaryContainerTest.cs b/tests/monotouch-test/Foundation/DictionaryContainerTest.cs index e07ebca50d71..018dae26f51b 100644 --- a/tests/monotouch-test/Foundation/DictionaryContainerTest.cs +++ b/tests/monotouch-test/Foundation/DictionaryContainerTest.cs @@ -272,377 +272,377 @@ public void WrappedNSDictionary () var wrapped = new WrappedNSDictionary (); Assert.Multiple (() => { - Assert.IsNull (wrapped.SByteField, "SByteField"); + Assert.That (wrapped.SByteField, Is.Null, "SByteField"); var valueSByteField = SByte.MaxValue; wrapped.SByteField = valueSByteField; - Assert.AreEqual (valueSByteField, wrapped.SByteField, "SByteField - set"); + Assert.That (wrapped.SByteField, Is.EqualTo (valueSByteField), "SByteField - set"); wrapped.SByteField = null; - Assert.IsNull (wrapped.SByteField, "SByteField - final"); + Assert.That (wrapped.SByteField, Is.Null, "SByteField - final"); - Assert.IsNull (wrapped.Int16Field, "Int16Field"); + Assert.That (wrapped.Int16Field, Is.Null, "Int16Field"); var valueInt16Field = Int16.MaxValue; wrapped.Int16Field = valueInt16Field; - Assert.AreEqual (valueInt16Field, wrapped.Int16Field, "Int16Field - set"); + Assert.That (wrapped.Int16Field, Is.EqualTo (valueInt16Field), "Int16Field - set"); wrapped.Int16Field = null; - Assert.IsNull (wrapped.Int16Field, "Int16Field - final"); + Assert.That (wrapped.Int16Field, Is.Null, "Int16Field - final"); - Assert.IsNull (wrapped.Int32Field, "Int32Field"); + Assert.That (wrapped.Int32Field, Is.Null, "Int32Field"); var valueInt32Field = Int32.MaxValue; wrapped.Int32Field = valueInt32Field; - Assert.AreEqual (valueInt32Field, wrapped.Int32Field, "Int32Field - set"); + Assert.That (wrapped.Int32Field, Is.EqualTo (valueInt32Field), "Int32Field - set"); wrapped.Int32Field = null; - Assert.IsNull (wrapped.Int32Field, "Int32Field - final"); + Assert.That (wrapped.Int32Field, Is.Null, "Int32Field - final"); - Assert.IsNull (wrapped.Int64Field, "Int64Field"); + Assert.That (wrapped.Int64Field, Is.Null, "Int64Field"); var valueInt64Field = Int64.MaxValue; wrapped.Int64Field = valueInt64Field; - Assert.AreEqual (valueInt64Field, wrapped.Int64Field, "Int64Field - set"); + Assert.That (wrapped.Int64Field, Is.EqualTo (valueInt64Field), "Int64Field - set"); wrapped.Int64Field = null; - Assert.IsNull (wrapped.Int64Field, "Int64Field - final"); + Assert.That (wrapped.Int64Field, Is.Null, "Int64Field - final"); - Assert.IsNull (wrapped.ByteField, "ByteField"); + Assert.That (wrapped.ByteField, Is.Null, "ByteField"); var valueByteField = Byte.MaxValue; wrapped.ByteField = valueByteField; - Assert.AreEqual (valueByteField, wrapped.ByteField, "ByteField - set"); + Assert.That (wrapped.ByteField, Is.EqualTo (valueByteField), "ByteField - set"); wrapped.ByteField = null; - Assert.IsNull (wrapped.ByteField, "ByteField - final"); + Assert.That (wrapped.ByteField, Is.Null, "ByteField - final"); - Assert.IsNull (wrapped.UInt16Field, "UInt16Field"); + Assert.That (wrapped.UInt16Field, Is.Null, "UInt16Field"); var valueUInt16Field = UInt16.MaxValue; wrapped.UInt16Field = valueUInt16Field; - Assert.AreEqual (valueUInt16Field, wrapped.UInt16Field, "UInt16Field - set"); + Assert.That (wrapped.UInt16Field, Is.EqualTo (valueUInt16Field), "UInt16Field - set"); wrapped.UInt16Field = null; - Assert.IsNull (wrapped.UInt16Field, "UInt16Field - final"); + Assert.That (wrapped.UInt16Field, Is.Null, "UInt16Field - final"); - Assert.IsNull (wrapped.UInt32Field, "UInt32Field"); + Assert.That (wrapped.UInt32Field, Is.Null, "UInt32Field"); var valueUInt32Field = UInt32.MaxValue; wrapped.UInt32Field = valueUInt32Field; - Assert.AreEqual (valueUInt32Field, wrapped.UInt32Field, "UInt32Field - set"); + Assert.That (wrapped.UInt32Field, Is.EqualTo (valueUInt32Field), "UInt32Field - set"); wrapped.UInt32Field = null; - Assert.IsNull (wrapped.UInt32Field, "UInt32Field - final"); + Assert.That (wrapped.UInt32Field, Is.Null, "UInt32Field - final"); - Assert.IsNull (wrapped.UInt64Field, "UInt64Field"); + Assert.That (wrapped.UInt64Field, Is.Null, "UInt64Field"); var valueUInt64Field = UInt64.MaxValue; wrapped.UInt64Field = valueUInt64Field; - Assert.AreEqual (valueUInt64Field, wrapped.UInt64Field, "UInt64Field - set"); + Assert.That (wrapped.UInt64Field, Is.EqualTo (valueUInt64Field), "UInt64Field - set"); wrapped.UInt64Field = null; - Assert.IsNull (wrapped.UInt64Field, "UInt64Field - final"); + Assert.That (wrapped.UInt64Field, Is.Null, "UInt64Field - final"); - Assert.IsNull (wrapped.NIntField, "NIntField"); + Assert.That (wrapped.NIntField, Is.Null, "NIntField"); var valueNIntField = nint.MaxValue; wrapped.NIntField = valueNIntField; - Assert.AreEqual (valueNIntField, wrapped.NIntField, "NIntField - set"); + Assert.That (wrapped.NIntField, Is.EqualTo (valueNIntField), "NIntField - set"); wrapped.NIntField = null; - Assert.IsNull (wrapped.NIntField, "NIntField - final"); + Assert.That (wrapped.NIntField, Is.Null, "NIntField - final"); - Assert.IsNull (wrapped.NUIntField, "NUIntField"); + Assert.That (wrapped.NUIntField, Is.Null, "NUIntField"); var valueNUIntField = nuint.MaxValue; wrapped.NUIntField = valueNUIntField; - Assert.AreEqual (valueNUIntField, wrapped.NUIntField, "NUIntField - set"); + Assert.That (wrapped.NUIntField, Is.EqualTo (valueNUIntField), "NUIntField - set"); wrapped.NUIntField = null; - Assert.IsNull (wrapped.NUIntField, "NUIntField - final"); + Assert.That (wrapped.NUIntField, Is.Null, "NUIntField - final"); - Assert.IsNull (wrapped.SingleField, "SingleField"); + Assert.That (wrapped.SingleField, Is.Null, "SingleField"); var valueSingleField = Single.MaxValue; wrapped.SingleField = valueSingleField; - Assert.AreEqual (valueSingleField, wrapped.SingleField, "SingleField - set"); + Assert.That (wrapped.SingleField, Is.EqualTo (valueSingleField), "SingleField - set"); wrapped.SingleField = null; - Assert.IsNull (wrapped.SingleField, "SingleField - final"); + Assert.That (wrapped.SingleField, Is.Null, "SingleField - final"); - Assert.IsNull (wrapped.DoubleField, "DoubleField"); + Assert.That (wrapped.DoubleField, Is.Null, "DoubleField"); var valueDoubleField = Double.MaxValue; wrapped.DoubleField = valueDoubleField; - Assert.AreEqual (valueDoubleField, wrapped.DoubleField, "DoubleField - set"); + Assert.That (wrapped.DoubleField, Is.EqualTo (valueDoubleField), "DoubleField - set"); wrapped.DoubleField = null; - Assert.IsNull (wrapped.DoubleField, "DoubleField - final"); + Assert.That (wrapped.DoubleField, Is.Null, "DoubleField - final"); - Assert.IsNull (wrapped.NFloatField, "NFloatField"); + Assert.That (wrapped.NFloatField, Is.Null, "NFloatField"); var valueNFloatField = nfloat.MaxValue; wrapped.NFloatField = valueNFloatField; - Assert.AreEqual (valueNFloatField, wrapped.NFloatField, "NFloatField - set"); + Assert.That (wrapped.NFloatField, Is.EqualTo (valueNFloatField), "NFloatField - set"); wrapped.NFloatField = null; - Assert.IsNull (wrapped.NFloatField, "NFloatField - final"); + Assert.That (wrapped.NFloatField, Is.Null, "NFloatField - final"); - Assert.IsNull (wrapped.NSObjectField, "NSObjectField"); + Assert.That (wrapped.NSObjectField, Is.Null, "NSObjectField"); var valueNSObjectField = (NSString) "NSObjectValue"; wrapped.NSObjectField = valueNSObjectField; - Assert.AreEqual (valueNSObjectField, wrapped.NSObjectField, "NSObjectField - set"); + Assert.That (wrapped.NSObjectField, Is.EqualTo (valueNSObjectField), "NSObjectField - set"); wrapped.NSObjectField = null; - Assert.IsNull (wrapped.NSObjectField, "NSObjectField - final"); + Assert.That (wrapped.NSObjectField, Is.Null, "NSObjectField - final"); - Assert.IsNull (wrapped.BooleanField, "BooleanField"); + Assert.That (wrapped.BooleanField, Is.Null, "BooleanField"); var valueBooleanField = true; wrapped.BooleanField = valueBooleanField; - Assert.AreEqual (valueBooleanField, wrapped.BooleanField, "BooleanField - set"); + Assert.That (wrapped.BooleanField, Is.EqualTo (valueBooleanField), "BooleanField - set"); wrapped.BooleanField = null; - Assert.IsNull (wrapped.BooleanField, "BooleanField - final"); + Assert.That (wrapped.BooleanField, Is.Null, "BooleanField - final"); - Assert.IsNull (wrapped.NSStringField, "NSStringField"); + Assert.That (wrapped.NSStringField, Is.Null, "NSStringField"); var valueNSStringField = (NSString) "NSStringValue"; wrapped.NSStringField = valueNSStringField; - Assert.AreEqual (valueNSStringField, wrapped.NSStringField, "NSStringField - set"); + Assert.That (wrapped.NSStringField, Is.EqualTo (valueNSStringField), "NSStringField - set"); wrapped.NSStringField = null; - Assert.IsNull (wrapped.NSStringField, "NSStringField - final"); + Assert.That (wrapped.NSStringField, Is.Null, "NSStringField - final"); - Assert.IsNull (wrapped.NSDateField, "NSDateField"); + Assert.That (wrapped.NSDateField, Is.Null, "NSDateField"); var valueNSDateField = (NSDate) new DateTime (2025, 09, 01, 12, 45, 55, 23).ToUniversalTime (); wrapped.NSDateField = valueNSDateField; - Assert.AreEqual (valueNSDateField, wrapped.NSDateField, "NSDateField - set"); + Assert.That (wrapped.NSDateField, Is.EqualTo (valueNSDateField), "NSDateField - set"); wrapped.NSDateField = null; - Assert.IsNull (wrapped.NSDateField, "NSDateField - final"); + Assert.That (wrapped.NSDateField, Is.Null, "NSDateField - final"); - Assert.IsNull (wrapped.NSDictionaryField, "NSDictionaryField"); + Assert.That (wrapped.NSDictionaryField, Is.Null, "NSDictionaryField"); var valueNSDictionaryField = new NSDictionary (); wrapped.NSDictionaryField = valueNSDictionaryField; - Assert.AreEqual (valueNSDictionaryField, wrapped.NSDictionaryField, "NSDictionaryField - set"); + Assert.That (wrapped.NSDictionaryField, Is.EqualTo (valueNSDictionaryField), "NSDictionaryField - set"); wrapped.NSDictionaryField = null; - Assert.IsNull (wrapped.NSDictionaryField, "NSDictionaryField - final"); + Assert.That (wrapped.NSDictionaryField, Is.Null, "NSDictionaryField - final"); - Assert.IsNull (wrapped.NSStrongDictionaryField, "NSStrongDictionaryField"); + Assert.That (wrapped.NSStrongDictionaryField, Is.Null, "NSStrongDictionaryField"); var valueNSStrongDictionaryField = new WrappedNSDictionary (); wrapped.NSStrongDictionaryField = valueNSStrongDictionaryField; - Assert.AreEqual (valueNSStrongDictionaryField?.Dictionary?.ToString (), wrapped.NSStrongDictionaryField?.Dictionary?.ToString (), "NSStrongDictionaryField - set"); + Assert.That (wrapped.NSStrongDictionaryField?.Dictionary?.ToString (), Is.EqualTo (valueNSStrongDictionaryField?.Dictionary?.ToString ()), "NSStrongDictionaryField - set"); wrapped.NSStrongDictionaryField = null; - Assert.IsNull (wrapped.NSStrongDictionaryField, "NSStrongDictionaryField - final"); + Assert.That (wrapped.NSStrongDictionaryField, Is.Null, "NSStrongDictionaryField - final"); - Assert.IsNull (wrapped.StrongEnumField, "StrongEnumField"); + Assert.That (wrapped.StrongEnumField, Is.Null, "StrongEnumField"); var valueStrongEnumField = StrongEnum.C; wrapped.StrongEnumField = valueStrongEnumField; - Assert.AreEqual (valueStrongEnumField, wrapped.StrongEnumField, "StrongEnumField - set"); + Assert.That (wrapped.StrongEnumField, Is.EqualTo (valueStrongEnumField), "StrongEnumField - set"); wrapped.StrongEnumField = null; - Assert.IsNull (wrapped.StrongEnumField, "StrongEnumField - final"); + Assert.That (wrapped.StrongEnumField, Is.Null, "StrongEnumField - final"); - Assert.IsNull (wrapped.NormalEnumField, "NormalEnumField"); + Assert.That (wrapped.NormalEnumField, Is.Null, "NormalEnumField"); var valueNormalEnumField = NormalEnum.Z; wrapped.NormalEnumField = valueNormalEnumField; - Assert.AreEqual (valueNormalEnumField, wrapped.NormalEnumField, "NormalEnumField - set"); + Assert.That (wrapped.NormalEnumField, Is.EqualTo (valueNormalEnumField), "NormalEnumField - set"); wrapped.NormalEnumField = null; - Assert.IsNull (wrapped.NormalEnumField, "NormalEnumField - final"); + Assert.That (wrapped.NormalEnumField, Is.Null, "NormalEnumField - final"); - Assert.IsNull (wrapped.ArrayOfSByteField, "ArrayOfSByteField"); + Assert.That (wrapped.ArrayOfSByteField, Is.Null, "ArrayOfSByteField"); var valueArrayOfSByteField = new sbyte [] { 1, 2, 3 }; wrapped.ArrayOfSByteField = valueArrayOfSByteField; - Assert.AreEqual (valueArrayOfSByteField, wrapped.ArrayOfSByteField, "ArrayOfSByteField - set"); + Assert.That (wrapped.ArrayOfSByteField, Is.EqualTo (valueArrayOfSByteField), "ArrayOfSByteField - set"); wrapped.ArrayOfSByteField = null; - Assert.IsNull (wrapped.ArrayOfSByteField, "ArrayOfSByteField - final"); + Assert.That (wrapped.ArrayOfSByteField, Is.Null, "ArrayOfSByteField - final"); - Assert.IsNull (wrapped.ArrayOfInt16Field, "ArrayOfInt16Field"); + Assert.That (wrapped.ArrayOfInt16Field, Is.Null, "ArrayOfInt16Field"); var valueArrayOfInt16Field = new short [] { 1, 2, 3 }; wrapped.ArrayOfInt16Field = valueArrayOfInt16Field; - Assert.AreEqual (valueArrayOfInt16Field, wrapped.ArrayOfInt16Field, "ArrayOfInt16Field - set"); + Assert.That (wrapped.ArrayOfInt16Field, Is.EqualTo (valueArrayOfInt16Field), "ArrayOfInt16Field - set"); wrapped.ArrayOfInt16Field = null; - Assert.IsNull (wrapped.ArrayOfInt16Field, "ArrayOfInt16Field - final"); + Assert.That (wrapped.ArrayOfInt16Field, Is.Null, "ArrayOfInt16Field - final"); - Assert.IsNull (wrapped.ArrayOfInt32Field, "ArrayOfInt32Field"); + Assert.That (wrapped.ArrayOfInt32Field, Is.Null, "ArrayOfInt32Field"); var valueArrayOfInt32Field = new int [] { 1, 2, 3 }; ; wrapped.ArrayOfInt32Field = valueArrayOfInt32Field; - Assert.AreEqual (valueArrayOfInt32Field, wrapped.ArrayOfInt32Field, "ArrayOfInt32Field - set"); + Assert.That (wrapped.ArrayOfInt32Field, Is.EqualTo (valueArrayOfInt32Field), "ArrayOfInt32Field - set"); wrapped.ArrayOfInt32Field = null; - Assert.IsNull (wrapped.ArrayOfInt32Field, "ArrayOfInt32Field - final"); + Assert.That (wrapped.ArrayOfInt32Field, Is.Null, "ArrayOfInt32Field - final"); - Assert.IsNull (wrapped.ArrayOfInt64Field, "ArrayOfInt64Field"); + Assert.That (wrapped.ArrayOfInt64Field, Is.Null, "ArrayOfInt64Field"); var valueArrayOfInt64Field = new long [] { 1, 2, 3 }; ; wrapped.ArrayOfInt64Field = valueArrayOfInt64Field; - Assert.AreEqual (valueArrayOfInt64Field, wrapped.ArrayOfInt64Field, "ArrayOfInt64Field - set"); + Assert.That (wrapped.ArrayOfInt64Field, Is.EqualTo (valueArrayOfInt64Field), "ArrayOfInt64Field - set"); wrapped.ArrayOfInt64Field = null; - Assert.IsNull (wrapped.ArrayOfInt64Field, "ArrayOfInt64Field - final"); + Assert.That (wrapped.ArrayOfInt64Field, Is.Null, "ArrayOfInt64Field - final"); - Assert.IsNull (wrapped.ArrayOfByteField, "ArrayOfByteField"); + Assert.That (wrapped.ArrayOfByteField, Is.Null, "ArrayOfByteField"); var valueArrayOfByteField = new byte [] { 1, 2, 3 }; ; wrapped.ArrayOfByteField = valueArrayOfByteField; - Assert.AreEqual (valueArrayOfByteField, wrapped.ArrayOfByteField, "ArrayOfByteField - set"); + Assert.That (wrapped.ArrayOfByteField, Is.EqualTo (valueArrayOfByteField), "ArrayOfByteField - set"); wrapped.ArrayOfByteField = null; - Assert.IsNull (wrapped.ArrayOfByteField, "ArrayOfByteField - final"); + Assert.That (wrapped.ArrayOfByteField, Is.Null, "ArrayOfByteField - final"); - Assert.IsNull (wrapped.ArrayOfUInt16Field, "ArrayOfUInt16Field"); + Assert.That (wrapped.ArrayOfUInt16Field, Is.Null, "ArrayOfUInt16Field"); var valueArrayOfUInt16Field = new ushort [] { 1, 2, 3 }; ; wrapped.ArrayOfUInt16Field = valueArrayOfUInt16Field; - Assert.AreEqual (valueArrayOfUInt16Field, wrapped.ArrayOfUInt16Field, "ArrayOfUInt16Field - set"); + Assert.That (wrapped.ArrayOfUInt16Field, Is.EqualTo (valueArrayOfUInt16Field), "ArrayOfUInt16Field - set"); wrapped.ArrayOfUInt16Field = null; - Assert.IsNull (wrapped.ArrayOfUInt16Field, "ArrayOfUInt16Field - final"); + Assert.That (wrapped.ArrayOfUInt16Field, Is.Null, "ArrayOfUInt16Field - final"); - Assert.IsNull (wrapped.ArrayOfUInt32Field, "ArrayOfUInt32Field"); + Assert.That (wrapped.ArrayOfUInt32Field, Is.Null, "ArrayOfUInt32Field"); var valueArrayOfUInt32Field = new uint [] { 1, 2, 3 }; ; wrapped.ArrayOfUInt32Field = valueArrayOfUInt32Field; - Assert.AreEqual (valueArrayOfUInt32Field, wrapped.ArrayOfUInt32Field, "ArrayOfUInt32Field - set"); + Assert.That (wrapped.ArrayOfUInt32Field, Is.EqualTo (valueArrayOfUInt32Field), "ArrayOfUInt32Field - set"); wrapped.ArrayOfUInt32Field = null; - Assert.IsNull (wrapped.ArrayOfUInt32Field, "ArrayOfUInt32Field - final"); + Assert.That (wrapped.ArrayOfUInt32Field, Is.Null, "ArrayOfUInt32Field - final"); - Assert.IsNull (wrapped.ArrayOfUInt64Field, "ArrayOfUInt64Field"); + Assert.That (wrapped.ArrayOfUInt64Field, Is.Null, "ArrayOfUInt64Field"); var valueArrayOfUInt64Field = new ulong [] { 1, 2, 3 }; ; wrapped.ArrayOfUInt64Field = valueArrayOfUInt64Field; - Assert.AreEqual (valueArrayOfUInt64Field, wrapped.ArrayOfUInt64Field, "ArrayOfUInt64Field - set"); + Assert.That (wrapped.ArrayOfUInt64Field, Is.EqualTo (valueArrayOfUInt64Field), "ArrayOfUInt64Field - set"); wrapped.ArrayOfUInt64Field = null; - Assert.IsNull (wrapped.ArrayOfUInt64Field, "ArrayOfUInt64Field - final"); + Assert.That (wrapped.ArrayOfUInt64Field, Is.Null, "ArrayOfUInt64Field - final"); - Assert.IsNull (wrapped.ArrayOfNIntField, "ArrayOfNIntField"); + Assert.That (wrapped.ArrayOfNIntField, Is.Null, "ArrayOfNIntField"); var valueArrayOfNIntField = new nint [] { 1, 2, 3 }; ; wrapped.ArrayOfNIntField = valueArrayOfNIntField; - Assert.AreEqual (valueArrayOfNIntField, wrapped.ArrayOfNIntField, "ArrayOfNIntField - set"); + Assert.That (wrapped.ArrayOfNIntField, Is.EqualTo (valueArrayOfNIntField), "ArrayOfNIntField - set"); wrapped.ArrayOfNIntField = null; - Assert.IsNull (wrapped.ArrayOfNIntField, "ArrayOfNIntField - final"); + Assert.That (wrapped.ArrayOfNIntField, Is.Null, "ArrayOfNIntField - final"); - Assert.IsNull (wrapped.ArrayOfNUIntField, "ArrayOfNUIntField"); + Assert.That (wrapped.ArrayOfNUIntField, Is.Null, "ArrayOfNUIntField"); var valueArrayOfNUIntField = new nuint [] { 1, 2, 3 }; ; wrapped.ArrayOfNUIntField = valueArrayOfNUIntField; - Assert.AreEqual (valueArrayOfNUIntField, wrapped.ArrayOfNUIntField, "ArrayOfNUIntField - set"); + Assert.That (wrapped.ArrayOfNUIntField, Is.EqualTo (valueArrayOfNUIntField), "ArrayOfNUIntField - set"); wrapped.ArrayOfNUIntField = null; - Assert.IsNull (wrapped.ArrayOfNUIntField, "ArrayOfNUIntField - final"); + Assert.That (wrapped.ArrayOfNUIntField, Is.Null, "ArrayOfNUIntField - final"); - Assert.IsNull (wrapped.ArrayOfSingleField, "ArrayOfSingleField"); + Assert.That (wrapped.ArrayOfSingleField, Is.Null, "ArrayOfSingleField"); var valueArrayOfSingleField = new float [] { 1, 2, 3 }; ; wrapped.ArrayOfSingleField = valueArrayOfSingleField; - Assert.AreEqual (valueArrayOfSingleField, wrapped.ArrayOfSingleField, "ArrayOfSingleField - set"); + Assert.That (wrapped.ArrayOfSingleField, Is.EqualTo (valueArrayOfSingleField), "ArrayOfSingleField - set"); wrapped.ArrayOfSingleField = null; - Assert.IsNull (wrapped.ArrayOfSingleField, "ArrayOfSingleField - final"); + Assert.That (wrapped.ArrayOfSingleField, Is.Null, "ArrayOfSingleField - final"); - Assert.IsNull (wrapped.ArrayOfDoubleField, "ArrayOfDoubleField"); + Assert.That (wrapped.ArrayOfDoubleField, Is.Null, "ArrayOfDoubleField"); var valueArrayOfDoubleField = new double [] { 1, 2, 3 }; ; wrapped.ArrayOfDoubleField = valueArrayOfDoubleField; - Assert.AreEqual (valueArrayOfDoubleField, wrapped.ArrayOfDoubleField, "ArrayOfDoubleField - set"); + Assert.That (wrapped.ArrayOfDoubleField, Is.EqualTo (valueArrayOfDoubleField), "ArrayOfDoubleField - set"); wrapped.ArrayOfDoubleField = null; - Assert.IsNull (wrapped.ArrayOfDoubleField, "ArrayOfDoubleField - final"); + Assert.That (wrapped.ArrayOfDoubleField, Is.Null, "ArrayOfDoubleField - final"); - Assert.IsNull (wrapped.ArrayOfNFloatField, "ArrayOfNFloatField"); + Assert.That (wrapped.ArrayOfNFloatField, Is.Null, "ArrayOfNFloatField"); var valueArrayOfNFloatField = new nfloat [] { 1, 2, 3 }; ; wrapped.ArrayOfNFloatField = valueArrayOfNFloatField; - Assert.AreEqual (valueArrayOfNFloatField, wrapped.ArrayOfNFloatField, "ArrayOfNFloatField - set"); + Assert.That (wrapped.ArrayOfNFloatField, Is.EqualTo (valueArrayOfNFloatField), "ArrayOfNFloatField - set"); wrapped.ArrayOfNFloatField = null; - Assert.IsNull (wrapped.ArrayOfNFloatField, "ArrayOfNFloatField - final"); + Assert.That (wrapped.ArrayOfNFloatField, Is.Null, "ArrayOfNFloatField - final"); - Assert.IsNull (wrapped.ArrayOfNSObjectField, "ArrayOfNSObjectField"); + Assert.That (wrapped.ArrayOfNSObjectField, Is.Null, "ArrayOfNSObjectField"); var valueArrayOfNSObjectField = new NSObject [] { (NSString) "Array1", NSDate.Now }; wrapped.ArrayOfNSObjectField = valueArrayOfNSObjectField; - Assert.AreEqual (valueArrayOfNSObjectField, wrapped.ArrayOfNSObjectField, "ArrayOfNSObjectField - set"); + Assert.That (wrapped.ArrayOfNSObjectField, Is.EqualTo (valueArrayOfNSObjectField), "ArrayOfNSObjectField - set"); wrapped.ArrayOfNSObjectField = null; - Assert.IsNull (wrapped.ArrayOfNSObjectField, "ArrayOfNSObjectField - final"); + Assert.That (wrapped.ArrayOfNSObjectField, Is.Null, "ArrayOfNSObjectField - final"); - Assert.IsNull (wrapped.ArrayOfBooleanField, "ArrayOfBooleanField"); + Assert.That (wrapped.ArrayOfBooleanField, Is.Null, "ArrayOfBooleanField"); var valueArrayOfBooleanField = new bool [] { true, false, true }; wrapped.ArrayOfBooleanField = valueArrayOfBooleanField; - Assert.AreEqual (valueArrayOfBooleanField, wrapped.ArrayOfBooleanField, "ArrayOfBooleanField - set"); + Assert.That (wrapped.ArrayOfBooleanField, Is.EqualTo (valueArrayOfBooleanField), "ArrayOfBooleanField - set"); wrapped.ArrayOfBooleanField = null; - Assert.IsNull (wrapped.ArrayOfBooleanField, "ArrayOfBooleanField - final"); + Assert.That (wrapped.ArrayOfBooleanField, Is.Null, "ArrayOfBooleanField - final"); - Assert.IsNull (wrapped.ArrayOfNSStringField, "ArrayOfNSStringField"); + Assert.That (wrapped.ArrayOfNSStringField, Is.Null, "ArrayOfNSStringField"); var valueArrayOfNSStringField = new NSString [] { (NSString) "a", (NSString) "b", (NSString) "c" }; wrapped.ArrayOfNSStringField = valueArrayOfNSStringField; - Assert.AreEqual (valueArrayOfNSStringField, wrapped.ArrayOfNSStringField, "ArrayOfNSStringField - set"); + Assert.That (wrapped.ArrayOfNSStringField, Is.EqualTo (valueArrayOfNSStringField), "ArrayOfNSStringField - set"); wrapped.ArrayOfNSStringField = null; - Assert.IsNull (wrapped.ArrayOfNSStringField, "ArrayOfNSStringField - final"); + Assert.That (wrapped.ArrayOfNSStringField, Is.Null, "ArrayOfNSStringField - final"); - Assert.IsNull (wrapped.ArrayOfNSDateField, "ArrayOfNSDateField"); + Assert.That (wrapped.ArrayOfNSDateField, Is.Null, "ArrayOfNSDateField"); var valueArrayOfNSDateField = new NSDate [] { NSDate.Now, NSDate.Now }; wrapped.ArrayOfNSDateField = valueArrayOfNSDateField; - Assert.AreEqual (valueArrayOfNSDateField, wrapped.ArrayOfNSDateField, "ArrayOfNSDateField - set"); + Assert.That (wrapped.ArrayOfNSDateField, Is.EqualTo (valueArrayOfNSDateField), "ArrayOfNSDateField - set"); wrapped.ArrayOfNSDateField = null; - Assert.IsNull (wrapped.ArrayOfNSDateField, "ArrayOfNSDateField - final"); + Assert.That (wrapped.ArrayOfNSDateField, Is.Null, "ArrayOfNSDateField - final"); - Assert.IsNull (wrapped.ArrayOfNSDictionaryField, "ArrayOfNSDictionaryField"); + Assert.That (wrapped.ArrayOfNSDictionaryField, Is.Null, "ArrayOfNSDictionaryField"); var valueArrayOfNSDictionaryField = new NSDictionary [] { new NSDictionary (), new NSDictionary () }; wrapped.ArrayOfNSDictionaryField = valueArrayOfNSDictionaryField; - Assert.AreEqual (valueArrayOfNSDictionaryField, wrapped.ArrayOfNSDictionaryField, "ArrayOfNSDictionaryField - set"); + Assert.That (wrapped.ArrayOfNSDictionaryField, Is.EqualTo (valueArrayOfNSDictionaryField), "ArrayOfNSDictionaryField - set"); wrapped.ArrayOfNSDictionaryField = null; - Assert.IsNull (wrapped.ArrayOfNSDictionaryField, "ArrayOfNSDictionaryField - final"); + Assert.That (wrapped.ArrayOfNSDictionaryField, Is.Null, "ArrayOfNSDictionaryField - final"); - Assert.IsNull (wrapped.ArrayOfStrongDictionaryField, "ArrayOfStrongDictionaryField"); + Assert.That (wrapped.ArrayOfStrongDictionaryField, Is.Null, "ArrayOfStrongDictionaryField"); var valueArrayOfStrongDictionaryField = new WrappedNSDictionary [] { new WrappedNSDictionary (), new WrappedNSDictionary () }; wrapped.ArrayOfStrongDictionaryField = valueArrayOfStrongDictionaryField; - Assert.AreEqual (string.Join (";", valueArrayOfStrongDictionaryField.Select (v => v?.Dictionary?.ToString ())), string.Join (";", wrapped.ArrayOfStrongDictionaryField.Select (v => v?.Dictionary?.ToString ())), "ArrayOfStrongDictionaryField - set"); + Assert.That (string.Join (";", wrapped.ArrayOfStrongDictionaryField.Select (v => v?.Dictionary?.ToString ())), Is.EqualTo (string.Join (";", valueArrayOfStrongDictionaryField.Select (v => v?.Dictionary?.ToString ()))), "ArrayOfStrongDictionaryField - set"); wrapped.ArrayOfStrongDictionaryField = null; - Assert.IsNull (wrapped.ArrayOfStrongDictionaryField, "ArrayOfStrongDictionaryField - final"); + Assert.That (wrapped.ArrayOfStrongDictionaryField, Is.Null, "ArrayOfStrongDictionaryField - final"); - Assert.IsNull (wrapped.ArrayOfStrongEnumField, "ArrayOfStrongEnumField"); + Assert.That (wrapped.ArrayOfStrongEnumField, Is.Null, "ArrayOfStrongEnumField"); var valueArrayOfStrongEnumField = new StrongEnum [] { StrongEnum.A, StrongEnum.B }; wrapped.ArrayOfStrongEnumField = valueArrayOfStrongEnumField; - Assert.AreEqual (valueArrayOfStrongEnumField, wrapped.ArrayOfStrongEnumField, "ArrayOfStrongEnumField - set"); + Assert.That (wrapped.ArrayOfStrongEnumField, Is.EqualTo (valueArrayOfStrongEnumField), "ArrayOfStrongEnumField - set"); wrapped.ArrayOfStrongEnumField = null; - Assert.IsNull (wrapped.ArrayOfStrongEnumField, "ArrayOfStrongEnumField - final"); + Assert.That (wrapped.ArrayOfStrongEnumField, Is.Null, "ArrayOfStrongEnumField - final"); - Assert.IsNull (wrapped.ArrayOfNormalEnumField, "ArrayOfNormalEnumField"); + Assert.That (wrapped.ArrayOfNormalEnumField, Is.Null, "ArrayOfNormalEnumField"); var valueArrayOfNormalEnumField = new NormalEnum [] { NormalEnum.X, NormalEnum.Y }; wrapped.ArrayOfNormalEnumField = valueArrayOfNormalEnumField; - Assert.AreEqual (valueArrayOfNormalEnumField, wrapped.ArrayOfNormalEnumField, "ArrayOfNormalEnumField - set"); + Assert.That (wrapped.ArrayOfNormalEnumField, Is.EqualTo (valueArrayOfNormalEnumField), "ArrayOfNormalEnumField - set"); wrapped.ArrayOfNormalEnumField = null; - Assert.IsNull (wrapped.ArrayOfNormalEnumField, "ArrayOfNormalEnumField - final"); + Assert.That (wrapped.ArrayOfNormalEnumField, Is.Null, "ArrayOfNormalEnumField - final"); - Assert.IsNull (wrapped.StringField, "StringField"); + Assert.That (wrapped.StringField, Is.Null, "StringField"); var valueStringField = "managed string"; wrapped.StringField = valueStringField; - Assert.AreEqual (valueStringField, wrapped.StringField, "StringField - set"); + Assert.That (wrapped.StringField, Is.EqualTo (valueStringField), "StringField - set"); wrapped.StringField = null; - Assert.IsNull (wrapped.StringField, "StringField - final"); + Assert.That (wrapped.StringField, Is.Null, "StringField - final"); - Assert.IsNull (wrapped.DateTimeField, "DateTimeField"); + Assert.That (wrapped.DateTimeField, Is.Null, "DateTimeField"); var valueDateTimeField = new DateTime (2025, 09, 01, 12, 45, 55, 23).ToUniversalTime (); wrapped.DateTimeField = valueDateTimeField; - Assert.AreEqual (valueDateTimeField, wrapped.DateTimeField, "DateTimeField - set"); + Assert.That (wrapped.DateTimeField, Is.EqualTo (valueDateTimeField), "DateTimeField - set"); wrapped.DateTimeField = null; - Assert.IsNull (wrapped.DateTimeField, "DateTimeField - final"); + Assert.That (wrapped.DateTimeField, Is.Null, "DateTimeField - final"); - Assert.IsNull (wrapped.GenericNSDictionaryField, "GenericNSDictionaryField"); + Assert.That (wrapped.GenericNSDictionaryField, Is.Null, "GenericNSDictionaryField"); var valueGenericNSDictionaryField = new NSDictionary (); wrapped.GenericNSDictionaryField = valueGenericNSDictionaryField; - Assert.AreEqual (valueGenericNSDictionaryField, wrapped.GenericNSDictionaryField, "GenericNSDictionaryField - set"); + Assert.That (wrapped.GenericNSDictionaryField, Is.EqualTo (valueGenericNSDictionaryField), "GenericNSDictionaryField - set"); wrapped.GenericNSDictionaryField = null; - Assert.IsNull (wrapped.GenericNSDictionaryField, "GenericNSDictionaryField - final"); + Assert.That (wrapped.GenericNSDictionaryField, Is.Null, "GenericNSDictionaryField - final"); - Assert.IsNull (wrapped.ArrayOfStringField, "ArrayOfStringField"); + Assert.That (wrapped.ArrayOfStringField, Is.Null, "ArrayOfStringField"); var valueArrayOfStringField = new string [] { "abc", "def", "ghi" }; wrapped.ArrayOfStringField = valueArrayOfStringField; - Assert.AreEqual (valueArrayOfStringField, wrapped.ArrayOfStringField, "ArrayOfStringField - set"); + Assert.That (wrapped.ArrayOfStringField, Is.EqualTo (valueArrayOfStringField), "ArrayOfStringField - set"); wrapped.ArrayOfStringField = null; - Assert.IsNull (wrapped.ArrayOfStringField, "ArrayOfStringField - final"); + Assert.That (wrapped.ArrayOfStringField, Is.Null, "ArrayOfStringField - final"); - Assert.IsNull (wrapped.NSDataField, "NSDataField"); + Assert.That (wrapped.NSDataField, Is.Null, "NSDataField"); var valueNSDataField = NSData.FromArray (new byte [] { 1, 2, 3 }); wrapped.NSDataField = valueNSDataField; - Assert.AreEqual (valueNSDataField, wrapped.NSDataField, "NSDataField - set"); + Assert.That (wrapped.NSDataField, Is.EqualTo (valueNSDataField), "NSDataField - set"); wrapped.NSDataField = null; - Assert.IsNull (wrapped.NSDataField, "NSDataField - final"); + Assert.That (wrapped.NSDataField, Is.Null, "NSDataField - final"); - Assert.IsNull (wrapped.NSDataAsMatrix3Field, "NSDataAsMatrix3Field"); + Assert.That (wrapped.NSDataAsMatrix3Field, Is.Null, "NSDataAsMatrix3Field"); var valueNSDataAsMatrix3Field = new NMatrix3 (1, 2, 3, 4, 5, 6, 7, 8, 9); wrapped.NSDataAsMatrix3Field = valueNSDataAsMatrix3Field; - Assert.AreEqual (valueNSDataAsMatrix3Field, wrapped.NSDataAsMatrix3Field, "NSDataAsMatrix3Field - set"); + Assert.That (wrapped.NSDataAsMatrix3Field, Is.EqualTo (valueNSDataAsMatrix3Field), "NSDataAsMatrix3Field - set"); wrapped.NSDataAsMatrix3Field = null; - Assert.IsNull (wrapped.NSDataAsMatrix3Field, "NSDataAsMatrix3Field - final"); + Assert.That (wrapped.NSDataAsMatrix3Field, Is.Null, "NSDataAsMatrix3Field - final"); - Assert.IsNull (wrapped.CGRectField, "CGRectField"); + Assert.That (wrapped.CGRectField, Is.Null, "CGRectField"); var valueCGRectField = new CGRect (1, 2, 3, 4); wrapped.CGRectField = valueCGRectField; - Assert.AreEqual (valueCGRectField, wrapped.CGRectField, "CGRectField - set"); + Assert.That (wrapped.CGRectField, Is.EqualTo (valueCGRectField), "CGRectField - set"); wrapped.CGRectField = null; - Assert.IsNull (wrapped.CGRectField, "CGRectField - final"); + Assert.That (wrapped.CGRectField, Is.Null, "CGRectField - final"); - Assert.IsNull (wrapped.CGSizeField, "CGSizeField"); + Assert.That (wrapped.CGSizeField, Is.Null, "CGSizeField"); var valueCGSizeField = new CGSize (5, 6); wrapped.CGSizeField = valueCGSizeField; - Assert.AreEqual (valueCGSizeField, wrapped.CGSizeField, "CGSizeField - set"); + Assert.That (wrapped.CGSizeField, Is.EqualTo (valueCGSizeField), "CGSizeField - set"); wrapped.CGSizeField = null; - Assert.IsNull (wrapped.CGSizeField, "CGSizeField - final"); + Assert.That (wrapped.CGSizeField, Is.Null, "CGSizeField - final"); - Assert.IsNull (wrapped.CGPointField, "CGPointField"); + Assert.That (wrapped.CGPointField, Is.Null, "CGPointField"); var valueCGPointField = new CGPoint (7, 8); wrapped.CGPointField = valueCGPointField; - Assert.AreEqual (valueCGPointField, wrapped.CGPointField, "CGPointField - set"); + Assert.That (wrapped.CGPointField, Is.EqualTo (valueCGPointField), "CGPointField - set"); wrapped.CGPointField = null; - Assert.IsNull (wrapped.CGPointField, "CGPointField - final"); + Assert.That (wrapped.CGPointField, Is.Null, "CGPointField - final"); - Assert.IsNull (wrapped.CMTimeField, "CMTimeField"); + Assert.That (wrapped.CMTimeField, Is.Null, "CMTimeField"); var valueCMTimeField = new CMTime (123, 2); wrapped.CMTimeField = valueCMTimeField; - Assert.AreEqual (valueCMTimeField, wrapped.CMTimeField, "CMTimeField - set"); + Assert.That (wrapped.CMTimeField, Is.EqualTo (valueCMTimeField), "CMTimeField - set"); wrapped.CMTimeField = null; - Assert.IsNull (wrapped.CMTimeField, "CMTimeField - final"); + Assert.That (wrapped.CMTimeField, Is.Null, "CMTimeField - final"); #if HAS_UIKIT - Assert.IsNull (wrapped.UIEdgeInsetsField, "UIEdgeInsetsField"); + Assert.That (wrapped.UIEdgeInsetsField, Is.Null, "UIEdgeInsetsField"); var valueUIEdgeInsetsField = new UIEdgeInsets (9, 8, 7, 6); wrapped.UIEdgeInsetsField = valueUIEdgeInsetsField; - Assert.AreEqual (valueUIEdgeInsetsField, wrapped.UIEdgeInsetsField, "UIEdgeInsetsField - set"); + Assert.That (wrapped.UIEdgeInsetsField, Is.EqualTo (valueUIEdgeInsetsField), "UIEdgeInsetsField - set"); wrapped.UIEdgeInsetsField = null; - Assert.IsNull (wrapped.UIEdgeInsetsField, "UIEdgeInsetsField - final"); + Assert.That (wrapped.UIEdgeInsetsField, Is.Null, "UIEdgeInsetsField - final"); #endif // HAS_UIKIT }); } @@ -655,14 +655,14 @@ public void Matrix () Assert.Multiple (() => { var dict = new VTCompressionPropertyCameraCalibration (); - Assert.IsNull (dict.IntrinsicMatrix, "IntrinsicMatrix"); + Assert.That (dict.IntrinsicMatrix, Is.Null, "IntrinsicMatrix"); var matrix = new NMatrix3 (1, 2, 3, 4, 5, 6, 7, 8, 9); dict.IntrinsicMatrix = matrix; - Assert.AreEqual (matrix, dict.IntrinsicMatrix, "IntrinsicMatrix 2"); + Assert.That (dict.IntrinsicMatrix, Is.EqualTo (matrix), "IntrinsicMatrix 2"); dict.IntrinsicMatrix = null; - Assert.IsNull (dict.IntrinsicMatrix, "IntrinsicMatrix 3"); + Assert.That (dict.IntrinsicMatrix, Is.Null, "IntrinsicMatrix 3"); }); } @@ -674,14 +674,14 @@ public void FloatArray () Assert.Multiple (() => { var dict = new VTCompressionPropertyCameraCalibration (); - Assert.IsNull (dict.LensDistortions, "LensDistortions"); + Assert.That (dict.LensDistortions, Is.Null, "LensDistortions"); var array = new float [] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; dict.LensDistortions = array; - Assert.AreEqual (array, dict.LensDistortions, "LensDistortions 2"); + Assert.That (dict.LensDistortions, Is.EqualTo (array), "LensDistortions 2"); dict.LensDistortions = null; - Assert.IsNull (dict.LensDistortions, "LensDistortions 3"); + Assert.That (dict.LensDistortions, Is.Null, "LensDistortions 3"); }); } } diff --git a/tests/monotouch-test/Foundation/DimensionTest.cs b/tests/monotouch-test/Foundation/DimensionTest.cs index 65ea5d44b648..111b02a46781 100644 --- a/tests/monotouch-test/Foundation/DimensionTest.cs +++ b/tests/monotouch-test/Foundation/DimensionTest.cs @@ -35,8 +35,8 @@ public void BaseUnit () public void NSUnitAcceleration_BaseUnit () { using (var bu = NSUnitAcceleration.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitAcceleration), bu, "type"); - Assert.That ("m/s²", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitAcceleration)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("m/s²"), "Symbol"); } } @@ -44,8 +44,8 @@ public void NSUnitAcceleration_BaseUnit () public void NSUnitAngle_BaseUnit () { using (var bu = NSUnitAngle.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitAngle), bu, "type"); - Assert.That ("°", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitAngle)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("°"), "Symbol"); } } @@ -53,8 +53,8 @@ public void NSUnitAngle_BaseUnit () public void NSUnitArea_BaseUnit () { using (var bu = NSUnitArea.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitArea), bu, "type"); - Assert.That ("m²", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitArea)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("m²"), "Symbol"); } } @@ -62,8 +62,8 @@ public void NSUnitArea_BaseUnit () public void NSUnitConcentrationMass_BaseUnit () { using (var bu = NSUnitConcentrationMass.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitConcentrationMass), bu, "type"); - Assert.That ("g/L", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitConcentrationMass)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("g/L"), "Symbol"); } } @@ -71,8 +71,8 @@ public void NSUnitConcentrationMass_BaseUnit () public void NSUnitDispersion_BaseUnit () { using (var bu = NSUnitDispersion.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitDispersion), bu, "type"); - Assert.That ("ppm", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitDispersion)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("ppm"), "Symbol"); } } @@ -80,8 +80,8 @@ public void NSUnitDispersion_BaseUnit () public void NSUnitDuration_BaseUnit () { using (var bu = NSUnitDuration.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitDuration), bu, "type"); - Assert.That ("s", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitDuration)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("s"), "Symbol"); } } @@ -89,8 +89,8 @@ public void NSUnitDuration_BaseUnit () public void NSUnitElectricCharge_BaseUnit () { using (var bu = NSUnitElectricCharge.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitElectricCharge), bu, "type"); - Assert.That ("C", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitElectricCharge)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("C"), "Symbol"); } } @@ -98,8 +98,8 @@ public void NSUnitElectricCharge_BaseUnit () public void NSUnitElectricCurrent_BaseUnit () { using (var bu = NSUnitElectricCurrent.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitElectricCurrent), bu, "type"); - Assert.That ("A", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitElectricCurrent)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("A"), "Symbol"); } } @@ -107,8 +107,8 @@ public void NSUnitElectricCurrent_BaseUnit () public void NSUnitElectricPotentialDifference_BaseUnit () { using (var bu = NSUnitElectricPotentialDifference.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitElectricPotentialDifference), bu, "type"); - Assert.That ("V", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitElectricPotentialDifference)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("V"), "Symbol"); } } @@ -116,8 +116,8 @@ public void NSUnitElectricPotentialDifference_BaseUnit () public void NSUnitElectricResistance_BaseUnit () { using (var bu = NSUnitElectricResistance.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitElectricResistance), bu, "type"); - Assert.That ("Ω", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitElectricResistance)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("Ω"), "Symbol"); } } @@ -125,8 +125,8 @@ public void NSUnitElectricResistance_BaseUnit () public void NSUnitEnergy_BaseUnit () { using (var bu = NSUnitEnergy.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitEnergy), bu, "type"); - Assert.That ("J", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitEnergy)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("J"), "Symbol"); } } @@ -134,8 +134,8 @@ public void NSUnitEnergy_BaseUnit () public void NSUnitFrequency_BaseUnit () { using (var bu = NSUnitFrequency.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitFrequency), bu, "type"); - Assert.That ("Hz", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitFrequency)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("Hz"), "Symbol"); } } @@ -143,8 +143,8 @@ public void NSUnitFrequency_BaseUnit () public void NSUnitFuelEfficiency_BaseUnit () { using (var bu = NSUnitFuelEfficiency.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitFuelEfficiency), bu, "type"); - Assert.That ("L/100km", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitFuelEfficiency)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("L/100km"), "Symbol"); } } @@ -152,8 +152,8 @@ public void NSUnitFuelEfficiency_BaseUnit () public void NSUnitIlluminance_BaseUnit () { using (var bu = NSUnitIlluminance.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitIlluminance), bu, "type"); - Assert.That ("lx", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitIlluminance)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("lx"), "Symbol"); } } @@ -161,8 +161,8 @@ public void NSUnitIlluminance_BaseUnit () public void NSUnitLength_BaseUnit () { using (var bu = NSUnitLength.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitLength), bu, "type"); - Assert.That ("m", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitLength)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("m"), "Symbol"); } } @@ -170,8 +170,8 @@ public void NSUnitLength_BaseUnit () public void NSUnitMass_BaseUnit () { using (var bu = NSUnitMass.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitMass), bu, "type"); - Assert.That ("kg", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitMass)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("kg"), "Symbol"); } } @@ -179,8 +179,8 @@ public void NSUnitMass_BaseUnit () public void NSUnitPower_BaseUnit () { using (var bu = NSUnitPower.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitPower), bu, "type"); - Assert.That ("W", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitPower)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("W"), "Symbol"); } } @@ -188,8 +188,8 @@ public void NSUnitPower_BaseUnit () public void NSUnitPressure_BaseUnit () { using (var bu = NSUnitPressure.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitPressure), bu, "type"); - Assert.That ("N/m²", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitPressure)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("N/m²"), "Symbol"); } } @@ -197,8 +197,8 @@ public void NSUnitPressure_BaseUnit () public void NSUnitSpeed_BaseUnit () { using (var bu = NSUnitSpeed.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitSpeed), bu, "type"); - Assert.That ("m/s", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitSpeed)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("m/s"), "Symbol"); } } @@ -206,8 +206,8 @@ public void NSUnitSpeed_BaseUnit () public void NSUnitTemperature_BaseUnit () { using (var bu = NSUnitTemperature.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitTemperature), bu, "type"); - Assert.That ("K", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitTemperature)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("K"), "Symbol"); } } @@ -215,8 +215,8 @@ public void NSUnitTemperature_BaseUnit () public void NSUnitVolume_BaseUnit () { using (var bu = NSUnitVolume.BaseUnit) { - Assert.IsInstanceOf (typeof (NSUnitVolume), bu, "type"); - Assert.That ("L", Is.EqualTo (bu.Symbol), "Symbol"); + Assert.That (bu, Is.InstanceOf (typeof (NSUnitVolume)), "type"); + Assert.That (bu.Symbol, Is.EqualTo ("L"), "Symbol"); } } } diff --git a/tests/monotouch-test/Foundation/FileCoordinatorTest.cs b/tests/monotouch-test/Foundation/FileCoordinatorTest.cs index 87f671deb951..bee89cfa88c7 100644 --- a/tests/monotouch-test/Foundation/FileCoordinatorTest.cs +++ b/tests/monotouch-test/Foundation/FileCoordinatorTest.cs @@ -35,8 +35,8 @@ public void CoordinateRead () NSError err; fileop = false; fc.CoordinateRead (url, NSFileCoordinatorReadingOptions.WithoutChanges, out err, FileOp); - Assert.True (fileop, "fileop/sync"); - Assert.Null (err, "NSError"); + Assert.That (fileop, Is.True, "fileop/sync"); + Assert.That (err, Is.Null, "NSError"); } } @@ -60,8 +60,8 @@ public void CoordinateWrite () NSError err; fileop = false; fc.CoordinateWrite (url, NSFileCoordinatorWritingOptions.ForDeleting, out err, FileOp); - Assert.True (fileop, "fileop/sync"); - Assert.Null (err, "NSError"); + Assert.That (fileop, Is.True, "fileop/sync"); + Assert.That (err, Is.Null, "NSError"); } } @@ -90,8 +90,8 @@ public void CoordinateReadWrite () NSError err; fileop = false; fc.CoordinateReadWrite (url, NSFileCoordinatorReadingOptions.WithoutChanges, url, NSFileCoordinatorWritingOptions.ForDeleting, out err, FileOp); - Assert.True (fileop, "fileop/sync"); - Assert.Null (err, "NSError"); + Assert.That (fileop, Is.True, "fileop/sync"); + Assert.That (err, Is.Null, "NSError"); } } @@ -115,8 +115,8 @@ public void CoordinateWriteWrite () NSError err; fileop = false; fc.CoordinateWriteWrite (url, NSFileCoordinatorWritingOptions.ForMoving, url, NSFileCoordinatorWritingOptions.ForDeleting, out err, FileOp); - Assert.True (fileop, "fileop/sync"); - Assert.Null (err, "NSError"); + Assert.That (fileop, Is.True, "fileop/sync"); + Assert.That (err, Is.Null, "NSError"); } } @@ -145,8 +145,8 @@ public void CoordinateBatch_Action () NSError err; fileop = false; fc.CoordinateBatch (new NSUrl [] { url }, NSFileCoordinatorReadingOptions.WithoutChanges, new NSUrl [] { url }, NSFileCoordinatorWritingOptions.ForDeleting, out err, Action); - Assert.True (fileop, "fileop/sync"); - Assert.Null (err, "NSError"); + Assert.That (fileop, Is.True, "fileop/sync"); + Assert.That (err, Is.Null, "NSError"); } } diff --git a/tests/monotouch-test/Foundation/FileManagerTest.cs b/tests/monotouch-test/Foundation/FileManagerTest.cs index ea907069ddd7..0e0ee64c04eb 100644 --- a/tests/monotouch-test/Foundation/FileManagerTest.cs +++ b/tests/monotouch-test/Foundation/FileManagerTest.cs @@ -24,19 +24,19 @@ public class NSFileManagerTest { // we might believe that Envioment.UserName os the same as NSFileManager.UserName, but it is not. On the simulator for // example, NSFileManager.UserName is an empty string while mono returns 'somebody' [Test] - public void GetUserNameTest () => Assert.IsNotNull (NSFileManager.UserName); + public void GetUserNameTest () => Assert.That (NSFileManager.UserName, Is.Not.Null); [Test] - public void GetUserFullNameTest () => Assert.IsNotNull (NSFileManager.FullUserName); // cannot check the value since it depends on the enviroment + public void GetUserFullNameTest () => Assert.That (NSFileManager.FullUserName, Is.Not.Null); // cannot check the value since it depends on the enviroment [Test] - public void GetHomeDirectoryTest () => Assert.IsNotNull (NSFileManager.HomeDirectory); // cannot check the value since it depends on the enviroment + public void GetHomeDirectoryTest () => Assert.That (NSFileManager.HomeDirectory, Is.Not.Null); // cannot check the value since it depends on the enviroment [Test] - public void GetHomeDirectoryForUserTest () => Assert.AreEqual (NSFileManager.HomeDirectory, NSFileManager.GetHomeDirectory (NSFileManager.UserName)); + public void GetHomeDirectoryForUserTest () => Assert.That (NSFileManager.GetHomeDirectory (NSFileManager.UserName), Is.EqualTo (NSFileManager.HomeDirectory)); [Test] - public void TemporaryDirectoryTest () => Assert.IsNotNull (NSFileManager.TemporaryDirectory); // cannot check the value since it depends on the enviroment + public void TemporaryDirectoryTest () => Assert.That (NSFileManager.TemporaryDirectory, Is.Not.Null); // cannot check the value since it depends on the enviroment [Test] public void GetUrlForUbiquityContainer () @@ -85,24 +85,24 @@ public void GetUrlForUbiquityContainer () [Test] public void GetSkipBackupAttribute () { - Assert.False (NSFileManager.GetSkipBackupAttribute (NSBundle.MainBundle.ExecutableUrl.ToString ()), "MainBundle"); + Assert.That (NSFileManager.GetSkipBackupAttribute (NSBundle.MainBundle.ExecutableUrl.ToString ()), Is.False, "MainBundle"); var paths = NSSearchPath.GetDirectories (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User); var filename = Path.Combine (paths [0], $"DoNotBackupMe-NSFileManager-{Process.GetCurrentProcess ().Id}"); try { File.WriteAllText (filename, "not worth a bit"); - Assert.False (NSFileManager.GetSkipBackupAttribute (filename), "DoNotBackupMe-0"); + Assert.That (NSFileManager.GetSkipBackupAttribute (filename), Is.False, "DoNotBackupMe-0"); NSFileManager.SetSkipBackupAttribute (filename, true); NSError error; - Assert.True (NSFileManager.GetSkipBackupAttribute (filename, out error), "DoNotBackupMe-1"); - Assert.Null (error, "error-1"); + Assert.That (NSFileManager.GetSkipBackupAttribute (filename, out error), Is.True, "DoNotBackupMe-1"); + Assert.That (error, Is.Null, "error-1"); error = NSFileManager.SetSkipBackupAttribute (filename, false); - Assert.False (NSFileManager.GetSkipBackupAttribute (filename), "DoNotBackupMe-2"); - Assert.Null (error, "error-2"); + Assert.That (NSFileManager.GetSkipBackupAttribute (filename), Is.False, "DoNotBackupMe-2"); + Assert.That (error, Is.Null, "error-2"); } finally { // otherwise the attribute won't reset even if the file is overwritten File.Delete (filename); @@ -113,7 +113,7 @@ public void GetSkipBackupAttribute () public void DefaultManager () { // ICE on devices ? ref: http://forums.xamarin.com/discussion/6807/system-invalidcastexception-while-trying-to-get-nsfilemanager-defaultmanager - Assert.NotNull (NSFileManager.DefaultManager, "DefaultManager"); + Assert.That (NSFileManager.DefaultManager, Is.Not.Null, "DefaultManager"); } #if !MONOMAC // DocumentsDirectory and MyDocuments point to different locations on mac diff --git a/tests/monotouch-test/Foundation/FormatterTests.cs b/tests/monotouch-test/Foundation/FormatterTests.cs index 8138d28e9405..97fae97f7d0e 100644 --- a/tests/monotouch-test/Foundation/FormatterTests.cs +++ b/tests/monotouch-test/Foundation/FormatterTests.cs @@ -27,8 +27,8 @@ void RequiresIos8 () static void TestFormattedString (string formattedString, string testName) { - Assert.IsNotNull (formattedString, testName); - Assert.IsTrue (formattedString.Length > 0, testName + " length"); + Assert.That (formattedString, Is.Not.Null, testName); + Assert.That (formattedString.Length > 0, Is.True, testName + " length"); } public NSDateComponents NowComponents { @@ -45,35 +45,35 @@ public void DateTestProperties () RequiresIos8 (); dateComponentsFormatter.UnitsStyle = NSDateComponentsFormatterUnitsStyle.Full; - Assert.AreEqual (NSDateComponentsFormatterUnitsStyle.Full, dateComponentsFormatter.UnitsStyle, "UnitsStyle"); + Assert.That (dateComponentsFormatter.UnitsStyle, Is.EqualTo (NSDateComponentsFormatterUnitsStyle.Full), "UnitsStyle"); dateComponentsFormatter.AllowedUnits = NSCalendarUnit.Month | NSCalendarUnit.Day; - Assert.AreEqual (NSCalendarUnit.Month | NSCalendarUnit.Day, dateComponentsFormatter.AllowedUnits, "AllowedUnits"); + Assert.That (dateComponentsFormatter.AllowedUnits, Is.EqualTo (NSCalendarUnit.Month | NSCalendarUnit.Day), "AllowedUnits"); dateComponentsFormatter.ZeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehavior.Pad; - Assert.AreEqual (NSDateComponentsFormatterZeroFormattingBehavior.Pad, dateComponentsFormatter.ZeroFormattingBehavior, "ZeroFormattingBehavior"); + Assert.That (dateComponentsFormatter.ZeroFormattingBehavior, Is.EqualTo (NSDateComponentsFormatterZeroFormattingBehavior.Pad), "ZeroFormattingBehavior"); NSCalendar c = new NSCalendar (NSCalendarType.Buddhist); - Assert.IsNotNull (dateComponentsFormatter.Calendar); + Assert.That (dateComponentsFormatter.Calendar, Is.Not.Null); dateComponentsFormatter.Calendar = c; - Assert.AreEqual (c.Identifier, dateComponentsFormatter.Calendar.Identifier, "Calendar"); + Assert.That (dateComponentsFormatter.Calendar.Identifier, Is.EqualTo (c.Identifier), "Calendar"); dateComponentsFormatter.AllowsFractionalUnits = true; - Assert.IsTrue (dateComponentsFormatter.AllowsFractionalUnits, "AllowsFractionalUnits"); + Assert.That (dateComponentsFormatter.AllowsFractionalUnits, Is.True, "AllowsFractionalUnits"); dateComponentsFormatter.MaximumUnitCount = 50; - Assert.AreEqual ((nint) 50, dateComponentsFormatter.MaximumUnitCount, "MaximumUnitCount"); + Assert.That (dateComponentsFormatter.MaximumUnitCount, Is.EqualTo ((nint) 50), "MaximumUnitCount"); dateComponentsFormatter.CollapsesLargestUnit = true; - Assert.IsTrue (dateComponentsFormatter.CollapsesLargestUnit, "CollapsesLargestUnit"); + Assert.That (dateComponentsFormatter.CollapsesLargestUnit, Is.True, "CollapsesLargestUnit"); dateComponentsFormatter.IncludesApproximationPhrase = true; - Assert.IsTrue (dateComponentsFormatter.IncludesApproximationPhrase, "IncludesApproximationPhrase"); + Assert.That (dateComponentsFormatter.IncludesApproximationPhrase, Is.True, "IncludesApproximationPhrase"); dateComponentsFormatter.IncludesTimeRemainingPhrase = true; - Assert.IsTrue (dateComponentsFormatter.IncludesTimeRemainingPhrase, "IncludesTimeRemainingPhrase"); + Assert.That (dateComponentsFormatter.IncludesTimeRemainingPhrase, Is.True, "IncludesTimeRemainingPhrase"); - Assert.IsNotNull (dateComponentsFormatter.FormattingContext); + Assert.That (dateComponentsFormatter.FormattingContext, Is.Not.Null); dateComponentsFormatter.FormattingContext = new NSFormattingContext (); } @@ -133,7 +133,7 @@ public void DateGetObjectValueTest () NSObject o; string e; bool value = dateComponentsFormatter.GetObjectValue (out o, string.Empty, out e); - Assert.IsFalse (value, "DateGetObjectValueTest"); // If this ever returns true, we need to write a better test + Assert.That (value, Is.False, "DateGetObjectValueTest"); // If this ever returns true, we need to write a better test } #endregion @@ -175,7 +175,7 @@ public void EnergyUnitStringFromJoules () NSEnergyFormatterUnit unit; string formattedString = energyFormatter.UnitStringFromJoules (2.0, out unit); TestFormattedString (formattedString, "UnitStringFromJoules"); - Assert.IsTrue ((int) unit > 0); // We got some value from the API + Assert.That ((int) unit > 0, Is.True); // We got some value from the API } [Test] @@ -187,7 +187,7 @@ public void EnergyGetObjectValue () NSObject o; string e; bool value = energyFormatter.GetObjectValue (out o, string.Empty, out e); - Assert.IsFalse (value, "EnergyGetObjectValue"); // If this ever returns true, we need to write a better test + Assert.That (value, Is.False, "EnergyGetObjectValue"); // If this ever returns true, we need to write a better test } #endregion diff --git a/tests/monotouch-test/Foundation/IndexPathTest.cs b/tests/monotouch-test/Foundation/IndexPathTest.cs index 943c53391a91..3fd08af6d5f8 100644 --- a/tests/monotouch-test/Foundation/IndexPathTest.cs +++ b/tests/monotouch-test/Foundation/IndexPathTest.cs @@ -16,10 +16,10 @@ public class IndexPathTest { public void FromIndex () { using (var ip = NSIndexPath.FromIndex (314159)) { - Assert.AreEqual ((nint) 1, ip.Length, "Length"); + Assert.That (ip.Length, Is.EqualTo ((nint) 1), "Length"); var rv = ip.GetIndexes (); - Assert.AreEqual (1, rv.Length, "GetIndexes ().Length"); - Assert.AreEqual ((nuint) 314159, rv [0], "GetIndexes ()[0]"); + Assert.That (rv.Length, Is.EqualTo (1), "GetIndexes ().Length"); + Assert.That (rv [0], Is.EqualTo ((nuint) 314159), "GetIndexes ()[0]"); } } @@ -28,10 +28,10 @@ public void IndexPathByAddingIndexTest () { using (var ip1 = new NSIndexPath ()) { using (var ip2 = ip1.IndexPathByAddingIndex (3141592)) { - Assert.AreEqual ((nint) 1, ip2.Length, "Length"); + Assert.That (ip2.Length, Is.EqualTo ((nint) 1), "Length"); var rv = ip2.GetIndexes (); - Assert.AreEqual (1, rv.Length, "GetIndexes ().Length"); - Assert.AreEqual ((nuint) 3141592, rv [0], "GetIndexes ()[0]"); + Assert.That (rv.Length, Is.EqualTo (1), "GetIndexes ().Length"); + Assert.That (rv [0], Is.EqualTo ((nuint) 3141592), "GetIndexes ()[0]"); } } } @@ -41,9 +41,9 @@ public void IndexPathByRemovingLastIndexTest () { using (var ip1 = NSIndexPath.FromIndex (3)) { using (var ip2 = ip1.IndexPathByRemovingLastIndex ()) { - Assert.AreEqual ((nint) 0, ip2.Length, "Length"); + Assert.That (ip2.Length, Is.EqualTo ((nint) 0), "Length"); var rv = ip2.GetIndexes (); - Assert.AreEqual (0, rv.Length, "GetIndexes ().Length"); + Assert.That (rv.Length, Is.EqualTo (0), "GetIndexes ().Length"); } } } @@ -52,10 +52,10 @@ public void IndexPathByRemovingLastIndexTest () public void IndexAtPositionTest () { using (var ip = NSIndexPath.Create (3, 14, 15)) { - Assert.AreEqual ((nint) 3, ip.Length, "Length"); - Assert.AreEqual ((nuint) 3, ip.IndexAtPosition (0), "[0]"); - Assert.AreEqual ((nuint) 14, ip.IndexAtPosition (1), "[0]"); - Assert.AreEqual ((nuint) 15, ip.IndexAtPosition (2), "[0]"); + Assert.That (ip.Length, Is.EqualTo ((nint) 3), "Length"); + Assert.That (ip.IndexAtPosition (0), Is.EqualTo ((nuint) 3), "[0]"); + Assert.That (ip.IndexAtPosition (1), Is.EqualTo ((nuint) 14), "[0]"); + Assert.That (ip.IndexAtPosition (2), Is.EqualTo ((nuint) 15), "[0]"); } } @@ -65,12 +65,12 @@ public void CompareTest () using (var ip1 = NSIndexPath.Create (3, 14, 15)) { using (var ip2 = NSIndexPath.Create (3, 14, 15)) { using (var ip3 = NSIndexPath.Create (3, 14)) { - Assert.AreEqual ((nint) 0, ip1.Compare (ip2), "ip1.Compare (ip2)"); - Assert.True (ip1.Equals (ip2), "ip1.Equals (ip2)"); + Assert.That (ip1.Compare (ip2), Is.EqualTo ((nint) 0), "ip1.Compare (ip2)"); + Assert.That (ip1.Equals (ip2), Is.True, "ip1.Equals (ip2)"); // "Two objects that are equal return hash codes that are equal." Assert.That (ip1.GetHashCode (), Is.EqualTo (ip2.GetHashCode ()), "GetHashCode"); - Assert.AreNotEqual ((nint) 0, ip1.Compare (ip3), "ip1.Compare (ip3)"); - Assert.False (ip1.Equals (ip3), "ip1.Equals (ip3)"); + Assert.That (ip1.Compare (ip3), Is.Not.EqualTo ((nint) 0), "ip1.Compare (ip3)"); + Assert.That (ip1.Equals (ip3), Is.False, "ip1.Equals (ip3)"); } } } @@ -85,21 +85,21 @@ public void CreateTest () Assert.Throws (() => NSIndexPath.Create ((nuint []) null), "ANE 4"); using (var ip = NSIndexPath.Create (1, 2, 3, 4)) { - Assert.AreEqual ((nint) 4, ip.Length, "Length"); + Assert.That (ip.Length, Is.EqualTo ((nint) 4), "Length"); var rv = ip.GetIndexes (); - Assert.AreEqual (4, rv.Length, "GetIndexes ().Length"); - Assert.AreEqual ((nuint) 1, rv [0], "GetIndexes ()[0]"); - Assert.AreEqual ((nuint) 2, rv [1], "GetIndexes ()[1]"); - Assert.AreEqual ((nuint) 3, rv [2], "GetIndexes ()[2]"); - Assert.AreEqual ((nuint) 4, rv [3], "GetIndexes ()[3]"); + Assert.That (rv.Length, Is.EqualTo (4), "GetIndexes ().Length"); + Assert.That (rv [0], Is.EqualTo ((nuint) 1), "GetIndexes ()[0]"); + Assert.That (rv [1], Is.EqualTo ((nuint) 2), "GetIndexes ()[1]"); + Assert.That (rv [2], Is.EqualTo ((nuint) 3), "GetIndexes ()[2]"); + Assert.That (rv [3], Is.EqualTo ((nuint) 4), "GetIndexes ()[3]"); } using (var ip = NSIndexPath.Create ((uint) 1, (uint) 2)) { - Assert.AreEqual ((nint) 2, ip.Length, "Length"); + Assert.That (ip.Length, Is.EqualTo ((nint) 2), "Length"); var rv = ip.GetIndexes (); - Assert.AreEqual (2, rv.Length, "GetIndexes ().Length"); - Assert.AreEqual ((nuint) 1, rv [0], "GetIndexes ()[0]"); - Assert.AreEqual ((nuint) 2, rv [1], "GetIndexes ()[1]"); + Assert.That (rv.Length, Is.EqualTo (2), "GetIndexes ().Length"); + Assert.That (rv [0], Is.EqualTo ((nuint) 1), "GetIndexes ()[0]"); + Assert.That (rv [1], Is.EqualTo ((nuint) 2), "GetIndexes ()[1]"); } } } diff --git a/tests/monotouch-test/Foundation/KeyedUnarchiverTest.cs b/tests/monotouch-test/Foundation/KeyedUnarchiverTest.cs index d0131a5ef0f5..5114e9a789ac 100644 --- a/tests/monotouch-test/Foundation/KeyedUnarchiverTest.cs +++ b/tests/monotouch-test/Foundation/KeyedUnarchiverTest.cs @@ -30,8 +30,8 @@ public void Exceptions () var data = NSData.FromString ("dummy string"); if (TestRuntime.CheckXcodeVersion (7, 0)) { // iOS9 does not throw if it cannot get correct data, it simply returns null (much better) - Assert.Null (NSKeyedUnarchiver.UnarchiveFile (Path.Combine (NSBundle.MainBundle.ResourcePath, "basn3p08.png")), "UnarchiveFile"); - Assert.Null (NSKeyedUnarchiver.UnarchiveObject (data), "UnarchiveObject"); + Assert.That (NSKeyedUnarchiver.UnarchiveFile (Path.Combine (NSBundle.MainBundle.ResourcePath, "basn3p08.png")), Is.Null, "UnarchiveFile"); + Assert.That (NSKeyedUnarchiver.UnarchiveObject (data), Is.Null, "UnarchiveObject"); } else { Assert.Throws (() => NSKeyedUnarchiver.UnarchiveFile (Path.Combine (NSBundle.MainBundle.ResourcePath, "basn3p08.png")), "UnarchiveFile"); Assert.Throws (() => NSKeyedUnarchiver.UnarchiveObject (data), "UnarchiveObject"); diff --git a/tests/monotouch-test/Foundation/LocaleTest.cs b/tests/monotouch-test/Foundation/LocaleTest.cs index 6f8395a45d42..236cd5a5e163 100644 --- a/tests/monotouch-test/Foundation/LocaleTest.cs +++ b/tests/monotouch-test/Foundation/LocaleTest.cs @@ -23,7 +23,7 @@ public class LocaleTest { [Test] public void CurrentLocale () { - Assert.NotNull (NSLocale.CurrentLocale, "CurrentLocale"); + Assert.That (NSLocale.CurrentLocale, Is.Not.Null, "CurrentLocale"); } [Test] @@ -56,7 +56,7 @@ public void CountryLessLocale () { string name = "zh-Hans"; // there's no country data from the supplied name - ref bug #18520 using (NSLocale locale = new NSLocale (name)) { - Assert.Null (locale.CountryCode, "CountryCode"); + Assert.That (locale.CountryCode, Is.Null, "CountryCode"); } } @@ -69,7 +69,7 @@ public void Properties () if (TestRuntime.CheckXcodeVersion (15, 0)) { Assert.That (en.CollationIdentifier, Is.EqualTo ("standard"), "CollationIdentifier"); } else { - Assert.Null (en.CollationIdentifier, "CollationIdentifier"); + Assert.That (en.CollationIdentifier, Is.Null, "CollationIdentifier"); } Assert.That (en.CollatorIdentifier, Is.EqualTo ("en-US"), "CollatorIdentifier"); Assert.That (en.CountryCode, Is.EqualTo ("US"), "CountryCode"); diff --git a/tests/monotouch-test/Foundation/MutableDataTest.cs b/tests/monotouch-test/Foundation/MutableDataTest.cs index 21789e057cc7..84d1ff822301 100644 --- a/tests/monotouch-test/Foundation/MutableDataTest.cs +++ b/tests/monotouch-test/Foundation/MutableDataTest.cs @@ -63,7 +63,7 @@ public void Constructor () // It worked, that's fine. } catch (Exception ex) { // Verify that the exception is an OOM (i.e. native code failed to init the object). - Assert.AreSame (typeof (Exception), ex.GetType (), "exception type"); + Assert.That (ex.GetType (), Is.SameAs (typeof (Exception)), "exception type"); Assert.That (ex.Message, Does.StartWith ("Could not initialize an instance of the type 'Foundation.NSMutableData': the native 'initWithCapacity:' method returned nil."), "OOM"); } } diff --git a/tests/monotouch-test/Foundation/NSArray1Test.cs b/tests/monotouch-test/Foundation/NSArray1Test.cs index 88d4d01e0eb0..3d3678f1d8f9 100644 --- a/tests/monotouch-test/Foundation/NSArray1Test.cs +++ b/tests/monotouch-test/Foundation/NSArray1Test.cs @@ -21,7 +21,7 @@ public void Ctor () { var arr = new NSArray (); - Assert.AreEqual ((nuint) 0, arr.Count, "NSArray Count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "NSArray Count"); } [Test] @@ -32,10 +32,10 @@ public void FromNSObjectsTest () var str3 = (NSString) "3"; using (var arr = NSArray.FromNSObjects (str1, str2, str3)) { - Assert.AreEqual ((nuint) 3, arr.Count, "NSArray Count"); - Assert.AreSame (str1, arr [0], "NSArray indexer"); - Assert.AreSame (str2, arr [1], "NSArray indexer"); - Assert.AreSame (str3, arr [2], "NSArray indexer"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 3), "NSArray Count"); + Assert.That (arr [0], Is.SameAs (str1), "NSArray indexer"); + Assert.That (arr [1], Is.SameAs (str2), "NSArray indexer"); + Assert.That (arr [2], Is.SameAs (str3), "NSArray indexer"); } } @@ -47,10 +47,10 @@ public void FromNSObjectsCountTest () var str3 = (NSString) "3"; using (var arr = NSArray.FromNSObjects (3, str1, str2, str3)) { - Assert.AreEqual ((nuint) 3, arr.Count, "NSArray Count"); - Assert.AreSame (str1, arr [0], "NSArray indexer"); - Assert.AreSame (str2, arr [1], "NSArray indexer"); - Assert.AreSame (str3, arr [2], "NSArray indexer"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 3), "NSArray Count"); + Assert.That (arr [0], Is.SameAs (str1), "NSArray indexer"); + Assert.That (arr [1], Is.SameAs (str2), "NSArray indexer"); + Assert.That (arr [2], Is.SameAs (str3), "NSArray indexer"); } } @@ -63,16 +63,16 @@ public void IEnumerableTest () values [i] = (NSString) i.ToString (); var st = NSArray.FromNSObjects (values); - Assert.AreEqual ((nuint) C, st.Count, "Count 1"); + Assert.That (st.Count, Is.EqualTo ((nuint) C), "Count 1"); var lst = new List (); foreach (NSString a in (IEnumerable) st) { - Assert.IsNotNull (a, "null item iterator"); - Assert.IsFalse (lst.Contains (a), "duplicated item iterator"); + Assert.That (a, Is.Not.Null, "null item iterator"); + Assert.That (lst.Contains (a), Is.False, "duplicated item iterator"); lst.Add (a); - Assert.IsTrue (Array.IndexOf (values, a) >= 0, "different object"); + Assert.That (Array.IndexOf (values, a) >= 0, Is.True, "different object"); } - Assert.AreEqual (C, lst.Count, "iterator count"); + Assert.That (lst.Count, Is.EqualTo (C), "iterator count"); } [Test] @@ -94,10 +94,10 @@ public void FromNSObjectsNullTest () var str3 = (NSString) "3"; using (var arr = NSArray.FromNSObjects (str1, str2, str3)) { - Assert.AreEqual ((nuint) 3, arr.Count, "NSArray Count"); - Assert.AreSame (str1, arr [0], "NSArray indexer"); - Assert.IsNull (arr [1], "NSArray null indexer"); - Assert.AreSame (str3, arr [2], "NSArray indexer"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 3), "NSArray Count"); + Assert.That (arr [0], Is.SameAs (str1), "NSArray indexer"); + Assert.That (arr [1], Is.Null, "NSArray null indexer"); + Assert.That (arr [2], Is.SameAs (str3), "NSArray indexer"); } } @@ -107,9 +107,9 @@ public void ToArray () using (var a = NSArray.FromNSObjects ((NSString) "abc")) { var arr = a.ToArray (); NSString element = arr [0]; - Assert.AreEqual (1, arr.Length, "Length"); - Assert.AreEqual ("abc", arr [0].ToString (), "Value"); - Assert.AreEqual ("abc", (string) element, "Value element"); + Assert.That (arr.Length, Is.EqualTo (1), "Length"); + Assert.That (arr [0].ToString (), Is.EqualTo ("abc"), "Value"); + Assert.That ((string) element, Is.EqualTo ("abc"), "Value element"); } } @@ -119,9 +119,9 @@ public void ToArray_T () using (var a = NSArray.FromNSObjects ((NSString) "abc")) { var arr = a.ToArray (); NSString element = arr [0]; - Assert.AreEqual (1, arr.Length, "Length"); - Assert.AreEqual ("abc", arr [0].ToString (), "Value"); - Assert.AreEqual ("abc", (string) element, "Value element"); + Assert.That (arr.Length, Is.EqualTo (1), "Length"); + Assert.That (arr [0].ToString (), Is.EqualTo ("abc"), "Value"); + Assert.That ((string) element, Is.EqualTo ("abc"), "Value element"); } } @@ -134,10 +134,10 @@ public void FromIntPtrs_NativeHandle () var handles = new NativeHandle [] { str1.Handle, str2.Handle, str3.Handle }; using (var arr = NSArray.FromIntPtrs (handles)) { - Assert.AreEqual ((nuint) 3, arr.Count, "NSArray Count"); - Assert.AreEqual ("1", arr.GetItem (0).ToString (), "NSArray item 0"); - Assert.AreEqual ("2", arr.GetItem (1).ToString (), "NSArray item 1"); - Assert.AreEqual ("3", arr.GetItem (2).ToString (), "NSArray item 2"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 3), "NSArray Count"); + Assert.That (arr.GetItem (0).ToString (), Is.EqualTo ("1"), "NSArray item 0"); + Assert.That (arr.GetItem (1).ToString (), Is.EqualTo ("2"), "NSArray item 1"); + Assert.That (arr.GetItem (2).ToString (), Is.EqualTo ("3"), "NSArray item 2"); } } @@ -153,7 +153,7 @@ public void FromIntPtrs_NativeHandle_Empty () { var handles = new NativeHandle [0]; using (var arr = NSArray.FromIntPtrs (handles)) { - Assert.AreEqual ((nuint) 0, arr.Count, "NSArray Count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "NSArray Count"); } } @@ -171,15 +171,15 @@ public void FromNSObjects_JaggedArray () }; using (var arr = NSArray.FromNSObjects (jaggedArray)) { - Assert.AreEqual ((nuint) 2, arr.Count, "Outer array count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "Outer array count"); var row0 = arr.GetItem (0); var row1 = arr.GetItem (1); - Assert.AreEqual ((nuint) 2, row0.Count, "Row 0 count"); - Assert.AreEqual ((nuint) 2, row1.Count, "Row 1 count"); - Assert.AreEqual ("1", row0.GetItem (0).ToString (), "Row 0, Item 0"); - Assert.AreEqual ("2", row0.GetItem (1).ToString (), "Row 0, Item 1"); - Assert.AreEqual ("3", row1.GetItem (0).ToString (), "Row 1, Item 0"); - Assert.AreEqual ("4", row1.GetItem (1).ToString (), "Row 1, Item 1"); + Assert.That (row0.Count, Is.EqualTo ((nuint) 2), "Row 0 count"); + Assert.That (row1.Count, Is.EqualTo ((nuint) 2), "Row 1 count"); + Assert.That (row0.GetItem (0).ToString (), Is.EqualTo ("1"), "Row 0, Item 0"); + Assert.That (row0.GetItem (1).ToString (), Is.EqualTo ("2"), "Row 0, Item 1"); + Assert.That (row1.GetItem (0).ToString (), Is.EqualTo ("3"), "Row 1, Item 0"); + Assert.That (row1.GetItem (1).ToString (), Is.EqualTo ("4"), "Row 1, Item 1"); } } @@ -188,7 +188,7 @@ public void FromNSObjects_JaggedArray_Null () { NSString [] []? jaggedArray = null; var arr = NSArray.FromNSObjects (jaggedArray); - Assert.IsNull (arr, "Should return null for null input"); + Assert.That (arr, Is.Null, "Should return null for null input"); } [Test] @@ -228,11 +228,11 @@ public void FromNSObjects_2DArray () }; using (var arr = NSArray.FromNSObjects (array2D)) { - Assert.AreEqual ((nuint) 2, arr.Count, "Outer array count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "Outer array count"); var row0 = arr.GetItem (0); var row1 = arr.GetItem (1); - Assert.AreEqual ((nuint) 2, row0.Count, "Row 0 count"); - Assert.AreEqual ((nuint) 2, row1.Count, "Row 1 count"); + Assert.That (row0.Count, Is.EqualTo ((nuint) 2), "Row 0 count"); + Assert.That (row1.Count, Is.EqualTo ((nuint) 2), "Row 1 count"); } } @@ -241,7 +241,7 @@ public void FromNSObjects_2DArray_Null () { NSString [,]? array2D = null; var arr = NSArray.FromNSObjects (array2D); - Assert.IsNull (arr, "Should return null for null input"); + Assert.That (arr, Is.Null, "Should return null for null input"); } [Test] @@ -249,10 +249,10 @@ public void FromNSObjects_WithConverter () { var numbers = new int [] { 1, 2, 3 }; using (var arr = NSArray.FromNSObjects (x => NSNumber.FromInt32 (x), numbers)) { - Assert.AreEqual ((nuint) 3, arr.Count, "Count"); - Assert.AreEqual (1, arr.GetItem (0).Int32Value, "Item 0"); - Assert.AreEqual (2, arr.GetItem (1).Int32Value, "Item 1"); - Assert.AreEqual (3, arr.GetItem (2).Int32Value, "Item 2"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 3), "Count"); + Assert.That (arr.GetItem (0).Int32Value, Is.EqualTo (1), "Item 0"); + Assert.That (arr.GetItem (1).Int32Value, Is.EqualTo (2), "Item 1"); + Assert.That (arr.GetItem (2).Int32Value, Is.EqualTo (3), "Item 2"); } } @@ -261,7 +261,7 @@ public void FromNSObjects_WithConverter_Null () { int []? numbers = null; var arr = NSArray.FromNSObjects (x => NSNumber.FromInt32 (x), numbers); - Assert.IsNull (arr, "Should return null for null input"); + Assert.That (arr, Is.Null, "Should return null for null input"); } [Test] @@ -276,15 +276,15 @@ public void FromNSObjects_WithConverter_ReturnsNull () { var numbers = new int? [] { 1, null, 3 }; var arr = NSArray.FromNSObjects (x => x.HasValue ? NSNumber.FromInt32 (x.Value) : null, numbers); - Assert.IsNotNull (arr, "Array should not be null"); - Assert.AreEqual ((nuint) 3, arr!.Count, "Count"); + Assert.That (arr, Is.Not.Null, "Array should not be null"); + Assert.That (arr!.Count, Is.EqualTo ((nuint) 3), "Count"); // Check if the array actually contains NSNull at index 1 // Use reflection or try-catch to see what's there try { var item0 = arr.GetItem (0); - Assert.IsNotNull (item0, "Item 0 should not be null"); - Assert.AreEqual (1, item0.Int32Value, "Item 0"); + Assert.That (item0, Is.Not.Null, "Item 0 should not be null"); + Assert.That (item0.Int32Value, Is.EqualTo (1), "Item 0"); } catch (Exception ex) { Assert.Fail ($"Item 0 failed: {ex.Message}"); } @@ -292,12 +292,12 @@ public void FromNSObjects_WithConverter_ReturnsNull () // The converter returns null, so we expect NSNull in the array // But GetItem might skip null items or return null var count = arr.Count; - Assert.AreEqual ((nuint) 3, count, "Should have 3 items including null"); + Assert.That (count, Is.EqualTo ((nuint) 3), "Should have 3 items including null"); try { var item2 = arr.GetItem (2); - Assert.IsNotNull (item2, "Item 2 should not be null"); - Assert.AreEqual (3, item2.Int32Value, "Item 2"); + Assert.That (item2, Is.Not.Null, "Item 2 should not be null"); + Assert.That (item2.Int32Value, Is.EqualTo (3), "Item 2"); } catch (Exception ex) { Assert.Fail ($"Item 2 failed: {ex.Message}"); } @@ -312,7 +312,7 @@ public void FromObjects_WithCount_ConvertsOnlyCount () using (var arr = NSArray.FromObjects (2, items)) { // This should only convert the first 2 items - Assert.AreEqual ((nuint) 2, arr.Count, "Count should be 2"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "Count should be 2"); } } @@ -340,11 +340,11 @@ public void FromNSObjects_CountFirst_WithNull () var items = new NSString? [] { str1, null, str3, str1 }; using (var arr = NSArray.FromNSObjects (3, items)) { - Assert.AreEqual ((nuint) 3, arr.Count, "Count should include null"); - Assert.AreEqual (str1, arr.GetItem (0), "Item 0"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 3), "Count should include null"); + Assert.That (arr.GetItem (0), Is.EqualTo (str1), "Item 0"); // Item 1 is null, but GetItem may not retrieve it properly // Just verify count is correct (3 items including the null) - Assert.AreEqual (str3, arr.GetItem (2), "Item 2"); + Assert.That (arr.GetItem (2), Is.EqualTo (str3), "Item 2"); } } @@ -358,9 +358,9 @@ public void FromNSObjects_CountFirst_Basic () var items = new NSString [] { str1, str2, str3, str4 }; using (var arr = NSArray.FromNSObjects (2, items)) { - Assert.AreEqual ((nuint) 2, arr.Count, "Count"); - Assert.AreEqual (str1, arr.GetItem (0), "Item 0"); - Assert.AreEqual (str2, arr.GetItem (1), "Item 1"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (arr.GetItem (0), Is.EqualTo (str1), "Item 0"); + Assert.That (arr.GetItem (1), Is.EqualTo (str2), "Item 1"); } } @@ -369,7 +369,7 @@ public void FromNSObjects_CountFirst_NullArray () { NSString []? items = null; using (var arr = NSArray.FromNSObjects (0, items)) { - Assert.AreEqual ((nuint) 0, arr.Count, "Null array should create empty array"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "Null array should create empty array"); } } @@ -378,11 +378,11 @@ public void FromObjects_BasicTypes () { var items = new object [] { 1, "hello", 3.14, true }; using (var arr = NSArray.FromObjects (items)) { - Assert.AreEqual ((nuint) 4, arr.Count, "Count"); - Assert.AreEqual (1, arr.GetItem (0).Int32Value, "Item 0"); - Assert.AreEqual ("hello", arr.GetItem (1).ToString (), "Item 1"); - Assert.AreEqual (3.14, arr.GetItem (2).DoubleValue, 0.01, "Item 2"); - Assert.AreEqual (true, arr.GetItem (3).BoolValue, "Item 3"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 4), "Count"); + Assert.That (arr.GetItem (0).Int32Value, Is.EqualTo (1), "Item 0"); + Assert.That (arr.GetItem (1).ToString (), Is.EqualTo ("hello"), "Item 1"); + Assert.That (arr.GetItem (2).DoubleValue, Is.EqualTo (3.14).Within (0.01), "Item 2"); + Assert.That (arr.GetItem (3).BoolValue, Is.EqualTo (true), "Item 3"); } } @@ -391,7 +391,7 @@ public void FromObjects_Null () { object []? items = null; using (var arr = NSArray.FromObjects (items)) { - Assert.AreEqual ((nuint) 0, arr.Count, "Should return empty array for null input"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "Should return empty array for null input"); } } @@ -400,10 +400,10 @@ public void FromObjects_WithCount () { var items = new object [] { 1, 2, 3, 4, 5 }; using (var arr = NSArray.FromObjects (3, items)) { - Assert.AreEqual ((nuint) 3, arr.Count, "Count"); - Assert.AreEqual (1, arr.GetItem (0).Int32Value, "Item 0"); - Assert.AreEqual (2, arr.GetItem (1).Int32Value, "Item 1"); - Assert.AreEqual (3, arr.GetItem (2).Int32Value, "Item 2"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 3), "Count"); + Assert.That (arr.GetItem (0).Int32Value, Is.EqualTo (1), "Item 0"); + Assert.That (arr.GetItem (1).Int32Value, Is.EqualTo (2), "Item 1"); + Assert.That (arr.GetItem (2).Int32Value, Is.EqualTo (3), "Item 2"); } } @@ -412,7 +412,7 @@ public void FromObjects_WithCountZero () { var items = new object [] { 1, 2, 3 }; using (var arr = NSArray.FromObjects (0, items)) { - Assert.AreEqual ((nuint) 0, arr.Count, "Count should be 0"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "Count should be 0"); } } @@ -427,7 +427,7 @@ public void FromObjects_WithNegativeCount () public void FromObjects_WithCount_Null () { using (var arr = NSArray.FromObjects (0, null)) { - Assert.AreEqual ((nuint) 0, arr.Count, "Should return empty array"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "Should return empty array"); } } @@ -435,7 +435,7 @@ public void FromObjects_WithCount_Null () public void EnumsFromHandle_ReturnsNullForZeroHandle () { var result = NSArray.EnumsFromHandle (NativeHandle.Zero); - Assert.IsNull (result, "null for zero handle"); + Assert.That (result, Is.Null, "null for zero handle"); } [Test] @@ -451,7 +451,7 @@ public void EnumsFromHandle_Roundtrip () using var n2 = NSNumber.FromNInt ((nint) (long) expected [2]); using var array = NSArray.FromNSObjects (n0, n1, n2); var actual = NSArray.EnumsFromHandle (array.Handle); - Assert.IsNotNull (actual, "not null"); + Assert.That (actual, Is.Not.Null, "not null"); Assert.That (actual!.Length, Is.EqualTo (3), "Length"); Assert.That (actual, Is.EqualTo (expected), "values"); } @@ -485,7 +485,7 @@ public void GetDifferenceFromArrayTest () }, "Not throws"); // https://github.com/dotnet/macios/issues/15577 - Did not rewrite tests that were disabled // Maybe assert that we get a specific diff result as well? - Assert.NotNull (diff, "Not null"); + Assert.That (diff, Is.Not.Null, "Not null"); } #endif @@ -498,20 +498,20 @@ public void FromArrayOfArray () var result = NSArray.FromArrayOfArray (outer); - Assert.IsNotNull (result, "result"); - Assert.AreEqual (2, result!.Length, "outer length"); - Assert.AreEqual (2, result [0].Length, "inner1 length"); - Assert.AreEqual (1, result [1].Length, "inner2 length"); - Assert.AreEqual ("a", result [0] [0].ToString (), "inner1[0]"); - Assert.AreEqual ("b", result [0] [1].ToString (), "inner1[1]"); - Assert.AreEqual ("c", result [1] [0].ToString (), "inner2[0]"); + Assert.That (result, Is.Not.Null, "result"); + Assert.That (result!.Length, Is.EqualTo (2), "outer length"); + Assert.That (result [0].Length, Is.EqualTo (2), "inner1 length"); + Assert.That (result [1].Length, Is.EqualTo (1), "inner2 length"); + Assert.That (result [0] [0].ToString (), Is.EqualTo ("a"), "inner1[0]"); + Assert.That (result [0] [1].ToString (), Is.EqualTo ("b"), "inner1[1]"); + Assert.That (result [1] [0].ToString (), Is.EqualTo ("c"), "inner2[0]"); } [Test] public void FromArrayOfArray_Null () { var result = NSArray.FromArrayOfArray (null); - Assert.IsNull (result, "result"); + Assert.That (result, Is.Null, "result"); } [Test] @@ -524,19 +524,19 @@ public void From_JaggedArray () using var arr = NSArray.From (items); - Assert.IsNotNull (arr, "arr"); - Assert.AreEqual ((nuint) 2, arr!.Count, "outer count"); + Assert.That (arr, Is.Not.Null, "arr"); + Assert.That (arr!.Count, Is.EqualTo ((nuint) 2), "outer count"); var row0 = arr.GetItem (0)!; var row1 = arr.GetItem (1)!; - Assert.AreEqual ((nuint) 2, row0.Count, "row0 count"); - Assert.AreEqual ((nuint) 1, row1.Count, "row1 count"); + Assert.That (row0.Count, Is.EqualTo ((nuint) 2), "row0 count"); + Assert.That (row1.Count, Is.EqualTo ((nuint) 1), "row1 count"); } [Test] public void From_JaggedArray_Null () { var result = NSArray.From ((NSObject [] []?) null); - Assert.IsNull (result, "result"); + Assert.That (result, Is.Null, "result"); } [Test] @@ -548,16 +548,16 @@ public void FromArrayOfArray_Roundtrip () }; using var native = NSArray.From (original); - Assert.IsNotNull (native, "native"); + Assert.That (native, Is.Not.Null, "native"); var roundtripped = NSArray.FromArrayOfArray (native); - Assert.IsNotNull (roundtripped, "roundtripped"); - Assert.AreEqual (original.Length, roundtripped!.Length, "outer length"); - Assert.AreEqual (original [0].Length, roundtripped [0].Length, "inner0 length"); - Assert.AreEqual (original [1].Length, roundtripped [1].Length, "inner1 length"); - Assert.AreEqual ("1", roundtripped [0] [0].ToString (), "[0][0]"); - Assert.AreEqual ("2", roundtripped [0] [1].ToString (), "[0][1]"); - Assert.AreEqual ("3", roundtripped [1] [0].ToString (), "[1][0]"); + Assert.That (roundtripped, Is.Not.Null, "roundtripped"); + Assert.That (roundtripped!.Length, Is.EqualTo (original.Length), "outer length"); + Assert.That (roundtripped [0].Length, Is.EqualTo (original [0].Length), "inner0 length"); + Assert.That (roundtripped [1].Length, Is.EqualTo (original [1].Length), "inner1 length"); + Assert.That (roundtripped [0] [0].ToString (), Is.EqualTo ("1"), "[0][0]"); + Assert.That (roundtripped [0] [1].ToString (), Is.EqualTo ("2"), "[0][1]"); + Assert.That (roundtripped [1] [0].ToString (), Is.EqualTo ("3"), "[1][0]"); } } } diff --git a/tests/monotouch-test/Foundation/NSAttributedStringDocumentAttributesTest.cs b/tests/monotouch-test/Foundation/NSAttributedStringDocumentAttributesTest.cs index 05514a343b87..5dadc5c160b3 100644 --- a/tests/monotouch-test/Foundation/NSAttributedStringDocumentAttributesTest.cs +++ b/tests/monotouch-test/Foundation/NSAttributedStringDocumentAttributesTest.cs @@ -20,20 +20,20 @@ public void DefaultTabInterval () Exception ex; var attribs = new NSAttributedStringDocumentAttributes (); - Assert.IsNull (attribs.DefaultTabInterval, "Initial"); + Assert.That (attribs.DefaultTabInterval, Is.Null, "Initial"); attribs.DefaultTabInterval = 0.5f; - Assert.AreEqual (0.5f, attribs.DefaultTabInterval.Value, "Half"); + Assert.That (attribs.DefaultTabInterval.Value, Is.EqualTo (0.5f), "Half"); ex = Assert.Throws (() => { attribs.DefaultTabInterval = -1; }, "Negative 1"); Assert.That (ex.Message, Does.StartWith ("Value must be between 0 and 1"), "Negative 1 - Message"); ex = Assert.Throws (() => { attribs.DefaultTabInterval = 2; }, "Positive 2"); Assert.That (ex.Message, Does.StartWith ("Value must be between 0 and 1"), "Positive 1 - Message"); attribs.DefaultTabInterval = 0f; - Assert.AreEqual (0f, attribs.DefaultTabInterval.Value, "Zero"); + Assert.That (attribs.DefaultTabInterval.Value, Is.EqualTo (0f), "Zero"); attribs.DefaultTabInterval = 1f; - Assert.AreEqual (1f, attribs.DefaultTabInterval.Value, "One"); + Assert.That (attribs.DefaultTabInterval.Value, Is.EqualTo (1f), "One"); attribs.DefaultTabInterval = null; - Assert.IsNull (attribs.DefaultTabInterval, "Null End"); + Assert.That (attribs.DefaultTabInterval, Is.Null, "Null End"); } [Test] @@ -42,20 +42,20 @@ public void HyphenationFactor () Exception ex; var attribs = new NSAttributedStringDocumentAttributes (); - Assert.IsNull (attribs.HyphenationFactor, "Initial"); + Assert.That (attribs.HyphenationFactor, Is.Null, "Initial"); attribs.HyphenationFactor = 0.5f; - Assert.AreEqual (0.5f, attribs.HyphenationFactor.Value, "Half"); + Assert.That (attribs.HyphenationFactor.Value, Is.EqualTo (0.5f), "Half"); ex = Assert.Throws (() => { attribs.HyphenationFactor = -1; }, "Negative 1"); Assert.That (ex.Message, Does.StartWith ("Value must be between 0 and 1"), "Negative 1 - Message"); ex = Assert.Throws (() => { attribs.HyphenationFactor = 2; }, "Positive 2"); Assert.That (ex.Message, Does.StartWith ("Value must be between 0 and 1"), "Positive 1 - Message"); attribs.HyphenationFactor = 0f; - Assert.AreEqual (0f, attribs.HyphenationFactor.Value, "Zero"); + Assert.That (attribs.HyphenationFactor.Value, Is.EqualTo (0f), "Zero"); attribs.HyphenationFactor = 1f; - Assert.AreEqual (1f, attribs.HyphenationFactor.Value, "One"); + Assert.That (attribs.HyphenationFactor.Value, Is.EqualTo (1f), "One"); attribs.HyphenationFactor = null; - Assert.IsNull (attribs.HyphenationFactor, "Null End"); + Assert.That (attribs.HyphenationFactor, Is.Null, "Null End"); } } } diff --git a/tests/monotouch-test/Foundation/NSCharacterSetTest.cs b/tests/monotouch-test/Foundation/NSCharacterSetTest.cs index 7bed98f529ca..2ba764ae1990 100644 --- a/tests/monotouch-test/Foundation/NSCharacterSetTest.cs +++ b/tests/monotouch-test/Foundation/NSCharacterSetTest.cs @@ -39,8 +39,8 @@ void TestSet (NSCharacterSet s, string setName, char characterThatShouldBeInSet) { RequiresIos8 (); - Assert.IsNotNull (s, setName + " was null"); - Assert.IsTrue (s.Contains (characterThatShouldBeInSet), setName + " did not contain: " + characterThatShouldBeInSet); + Assert.That (s, Is.Not.Null, setName + " was null"); + Assert.That (s.Contains (characterThatShouldBeInSet), Is.True, setName + " did not contain: " + characterThatShouldBeInSet); } } } diff --git a/tests/monotouch-test/Foundation/NSDataTest.cs b/tests/monotouch-test/Foundation/NSDataTest.cs index 259d56f9cf53..026478018ed2 100644 --- a/tests/monotouch-test/Foundation/NSDataTest.cs +++ b/tests/monotouch-test/Foundation/NSDataTest.cs @@ -42,21 +42,21 @@ public void ConstructorTest () using (var data = new NSData (bytes, 1, (a, b) => { deallocated = true; Marshal.FreeHGlobal (a); - Assert.AreEqual (1, (int) b, "length in deallocator"); + Assert.That ((int) b, Is.EqualTo (1), "length in deallocator"); })) { NSError error; var file = Path.GetTempFileName (); var url = NSUrl.FromFilename (file + ".url"); - Assert.IsTrue (data.Save (file, false, out error), "save 1"); - Assert.IsTrue (data.Save (file, true, out error), "save 2"); - Assert.IsTrue (data.Save (file, NSDataWritingOptions.Atomic, out error), "save 3"); - Assert.IsTrue (data.Save (url, false, out error), "save url 1"); - Assert.IsTrue (data.Save (url, true, out error), "save url 2"); - Assert.IsTrue (data.Save (url, NSDataWritingOptions.Atomic, out error), "save url 3"); + Assert.That (data.Save (file, false, out error), Is.True, "save 1"); + Assert.That (data.Save (file, true, out error), Is.True, "save 2"); + Assert.That (data.Save (file, NSDataWritingOptions.Atomic, out error), Is.True, "save 3"); + Assert.That (data.Save (url, false, out error), Is.True, "save url 1"); + Assert.That (data.Save (url, true, out error), Is.True, "save url 2"); + Assert.That (data.Save (url, NSDataWritingOptions.Atomic, out error), Is.True, "save url 3"); } - Assert.IsTrue (deallocated, "deallocated"); + Assert.That (deallocated, Is.True, "deallocated"); } [Test] @@ -68,14 +68,14 @@ public void FromEmptyArrayTest () [Test] public void FromFile () { - Assert.Null (NSData.FromFile ("does not exists"), "unexisting"); + Assert.That (NSData.FromFile ("does not exists"), Is.Null, "unexisting"); #if MONOMAC || __MACCATALYST__ // Info.Plist isn't there to load from the same location on mac var plistPath = Path.Combine (NSBundle.MainBundle.BundlePath, "Contents", "Info.plist"); #else var plistPath = Path.Combine (NSBundle.MainBundle.BundlePath, "Info.plist"); #endif - Assert.NotNull (NSData.FromFile (plistPath), "Info.plist"); + Assert.That (NSData.FromFile (plistPath), Is.Not.Null, "Info.plist"); } [Test] @@ -83,7 +83,7 @@ public void FromFile_Options () { NSError err; var n = NSData.FromFile ("does not exists", NSDataReadingOptions.Uncached, out err); - Assert.Null (n, "unexisting"); + Assert.That (n, Is.Null, "unexisting"); Assert.That (err.Code, Is.EqualTo ((nint) 260), "err"); } @@ -105,9 +105,9 @@ public void ToArray () { using (var data = NSData.FromArray (new byte [] { 1, 2, 3 })) { var arr = data.ToArray (); - Assert.AreEqual (3, arr.Length, "Length"); + Assert.That (arr.Length, Is.EqualTo (3), "Length"); for (int i = 0; i < arr.Length; i++) - Assert.AreEqual (i + 1, arr [i], "idx " + i.ToString ()); + Assert.That (arr [i], Is.EqualTo (i + 1), "idx " + i.ToString ()); } } @@ -116,7 +116,7 @@ public void ToEmptyArray () { using (var data = NSData.FromArray (new byte [0])) { var arr = data.ToArray (); - Assert.AreEqual (0, arr.Length, "Length"); + Assert.That (arr.Length, Is.EqualTo (0), "Length"); } } @@ -220,7 +220,7 @@ public override bool CanRead { public void FromStream_CanNotRead () { using (var s = new CanNotReadStream ()) { - Assert.Null (NSData.FromStream (s), "!CanRead"); + Assert.That (NSData.FromStream (s), Is.Null, "!CanRead"); } } @@ -385,7 +385,7 @@ public void ToFromValueType () using var emptyData = NSData.FromArray (new byte [0]); var emptyVT = data.ToValueType (); - Assert.AreEqual (default (EmptyValueType), emptyVT, "Empty Value Type"); + Assert.That (emptyVT, Is.EqualTo (default (EmptyValueType)), "Empty Value Type"); emptyVT = new EmptyValueType (); using var emptyData2 = NSData.CreateFromValueType (emptyVT); @@ -393,7 +393,7 @@ public void ToFromValueType () unsafe { emptyValueTypeSize = sizeof (EmptyValueType); } - Assert.AreEqual (emptyValueTypeSize, (int) emptyData2.Length, "Empty Value Type 2"); + Assert.That ((int) emptyData2.Length, Is.EqualTo (emptyValueTypeSize), "Empty Value Type 2"); }); } diff --git a/tests/monotouch-test/Foundation/NSDateComponentsTest.cs b/tests/monotouch-test/Foundation/NSDateComponentsTest.cs index b11a331f3e6e..4dbd44f98202 100644 --- a/tests/monotouch-test/Foundation/NSDateComponentsTest.cs +++ b/tests/monotouch-test/Foundation/NSDateComponentsTest.cs @@ -14,12 +14,12 @@ public void TestUndefinedComponent () // NSDateComponentUndefined." // we simply test that the values are undefined var components = new NSDateComponents (); - Assert.AreEqual (NSDateComponents.Undefined, components.Year, $"Year"); - Assert.AreEqual (NSDateComponents.Undefined, components.Month, "Month"); - Assert.AreEqual (NSDateComponents.Undefined, components.Day, "Day"); - Assert.AreEqual (NSDateComponents.Undefined, components.Hour, "Hour"); - Assert.AreEqual (NSDateComponents.Undefined, components.Minute, "Minute"); - Assert.AreEqual (NSDateComponents.Undefined, components.Second, "Second"); + Assert.That (components.Year, Is.EqualTo (NSDateComponents.Undefined), $"Year"); + Assert.That (components.Month, Is.EqualTo (NSDateComponents.Undefined), "Month"); + Assert.That (components.Day, Is.EqualTo (NSDateComponents.Undefined), "Day"); + Assert.That (components.Hour, Is.EqualTo (NSDateComponents.Undefined), "Hour"); + Assert.That (components.Minute, Is.EqualTo (NSDateComponents.Undefined), "Minute"); + Assert.That (components.Second, Is.EqualTo (NSDateComponents.Undefined), "Second"); } } } diff --git a/tests/monotouch-test/Foundation/NSDictionary2Test.cs b/tests/monotouch-test/Foundation/NSDictionary2Test.cs index e4c00e3fdea6..d5f75109a707 100644 --- a/tests/monotouch-test/Foundation/NSDictionary2Test.cs +++ b/tests/monotouch-test/Foundation/NSDictionary2Test.cs @@ -11,7 +11,7 @@ public class NSDictionary2Test { public void Ctor () { var dict = new NSDictionary (); - Assert.AreEqual ((nuint) 0, dict.Count, "Count"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 0), "Count"); } // @@ -24,8 +24,8 @@ public void DictionaryCtorKeyValues () var value = new NSString ("value"); var j = new NSDictionary (key, value); - Assert.AreEqual (j.Count, (nuint) 1, "count"); - Assert.AreEqual (j [key], value, "key lookup"); + Assert.That (j.Count, Is.EqualTo ((nuint) 1), "count"); + Assert.That (value, Is.EqualTo (j [key]), "key lookup"); } [Test] @@ -35,9 +35,9 @@ public void Ctor_Arrays () new NSString [] { new NSString ("first-k"), new NSString ("second-k") }, new NSString [] { new NSString ("first"), new NSString ("second") } ); - Assert.AreEqual (j.Count, (nuint) 2, "count"); - Assert.AreEqual ((string) (j [(NSString) "first-k"]), "first", "lookup1"); - Assert.AreEqual ((string) (j [(NSString) "second-k"]), "second", "lookup2"); + Assert.That (j.Count, Is.EqualTo ((nuint) 2), "count"); + Assert.That ((string) (j [(NSString) "first-k"]), Is.EqualTo ("first"), "lookup1"); + Assert.That ((string) (j [(NSString) "second-k"]), Is.EqualTo ("second"), "lookup2"); } [Test] @@ -45,10 +45,10 @@ public void Ctor_WithNullValue () { var key = (NSString) "key"; var dict = new NSDictionary (key, null); - Assert.AreEqual ((nuint) 1, dict.Count, "count"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 1), "count"); var baseDict = (NSDictionary) dict; var rawValue = baseDict.ObjectForKey (key); - Assert.IsInstanceOf (rawValue, "Null value should be NSNull"); + Assert.That (rawValue, Is.InstanceOf (), "Null value should be NSNull"); } [Test] @@ -57,8 +57,8 @@ public void Ctor_NSDictionary () var other = new NSDictionary ((NSString) "key", (NSString) "value"); var j = new NSDictionary (other); - Assert.AreEqual (j.Count, (nuint) 1, "count"); - Assert.AreEqual ((string) (NSString) (j ["key"]), "value", "key lookup"); + Assert.That (j.Count, Is.EqualTo ((nuint) 1), "count"); + Assert.That ((string) (NSString) (j ["key"]), Is.EqualTo ("value"), "key lookup"); } [Test] @@ -90,9 +90,9 @@ public void FromObjectsAndKeysGenericTest () }; var dict = NSDictionary.FromObjectsAndKeys (values, keys, values.Length); - Assert.AreEqual (dict.Count, (nuint) 5, "count"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 5), "count"); for (int i = 0; i < values.Length; i++) - Assert.AreEqual (dict [keys [i]], values [i], $"key lookup, Iteration: {i}"); + Assert.That (values [i], Is.EqualTo (dict [keys [i]]), $"key lookup, Iteration: {i}"); } [Test] @@ -110,12 +110,12 @@ public void FromObjectsAndKeysGenericTest_NullValue () }; var dict = NSDictionary.FromObjectsAndKeys (values, keys, values.Length); - Assert.AreEqual (dict.Count, (nuint) 3, "count"); - Assert.AreEqual (dict [keys [0]], values [0], "key lookup 0"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 3), "count"); + Assert.That (values [0], Is.EqualTo (dict [keys [0]]), "key lookup 0"); var baseDict = (NSDictionary) dict; var rawValue = baseDict.ObjectForKey (keys [1]); - Assert.IsInstanceOf (rawValue, "Null value"); - Assert.AreEqual (dict [keys [2]], values [2], "key lookup 2"); + Assert.That (rawValue, Is.InstanceOf (), "Null value"); + Assert.That (values [2], Is.EqualTo (dict [keys [2]]), "key lookup 2"); } [Test] @@ -133,12 +133,12 @@ public void FromObjectsAndKeysGenericTest_NSObjects_NullValue () }; var dict = NSDictionary.FromObjectsAndKeys (values, keys, values.Length); - Assert.AreEqual (dict.Count, (nuint) 3, "count"); - Assert.AreEqual (1, dict [(NSString) keys [0]].ByteValue, "key lookup 0"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 3), "count"); + Assert.That (dict [(NSString) keys [0]].ByteValue, Is.EqualTo (1), "key lookup 0"); var baseDict = (NSDictionary) dict; var rawValue = baseDict.ObjectForKey ((NSString) keys [1]); - Assert.IsInstanceOf (rawValue, "Null value"); - Assert.AreEqual (42, dict [(NSString) keys [2]].Int32Value, "key lookup 2"); + Assert.That (rawValue, Is.InstanceOf (), "Null value"); + Assert.That (dict [(NSString) keys [2]].Int32Value, Is.EqualTo (42), "key lookup 2"); } [Test] @@ -156,12 +156,12 @@ public void FromObjectsAndKeysGenericTest_NullValue_NoCount () }; var dict = NSDictionary.FromObjectsAndKeys (values, keys); - Assert.AreEqual (dict.Count, (nuint) 3, "count"); - Assert.AreEqual (dict [keys [0]], values [0], "key lookup 0"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 3), "count"); + Assert.That (values [0], Is.EqualTo (dict [keys [0]]), "key lookup 0"); var baseDict = (NSDictionary) dict; var rawValue = baseDict.ObjectForKey (keys [1]); - Assert.IsInstanceOf (rawValue, "Null value"); - Assert.AreEqual (dict [keys [2]], values [2], "key lookup 2"); + Assert.That (rawValue, Is.InstanceOf (), "Null value"); + Assert.That (values [2], Is.EqualTo (dict [keys [2]]), "key lookup 2"); } [Test] @@ -179,12 +179,12 @@ public void FromObjectsAndKeysGenericTest_NSObjects_NullValue_NoCount () }; var dict = NSDictionary.FromObjectsAndKeys (values, keys); - Assert.AreEqual (dict.Count, (nuint) 3, "count"); - Assert.AreEqual (1, dict [(NSString) keys [0]].ByteValue, "key lookup 0"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 3), "count"); + Assert.That (dict [(NSString) keys [0]].ByteValue, Is.EqualTo (1), "key lookup 0"); var baseDict = (NSDictionary) dict; var rawValue = baseDict.ObjectForKey ((NSString) keys [1]); - Assert.IsInstanceOf (rawValue, "Null value"); - Assert.AreEqual (42, dict [(NSString) keys [2]].Int32Value, "key lookup 2"); + Assert.That (rawValue, Is.InstanceOf (), "Null value"); + Assert.That (dict [(NSString) keys [2]].Int32Value, Is.EqualTo (42), "key lookup 2"); } [Test] @@ -206,13 +206,13 @@ public void KeyValue_Autorelease () v2 = v.RetainCount; Assert.That (v2, Is.GreaterThan (v1), "Value.RetainCount-b"); - Assert.NotNull (d.Keys, "Keys"); + Assert.That (d.Keys, Is.Not.Null, "Keys"); // accessing `allKeys` should *NOT* change the retainCount // that would happen without an [Autorelease] and can lead to memory exhaustion // https://bugzilla.xamarin.com/show_bug.cgi?id=7723 Assert.That (k.RetainCount, Is.EqualTo (k2), "Key.RetainCount-c"); - Assert.NotNull (d.Values, "Values"); + Assert.That (d.Values, Is.Not.Null, "Values"); Assert.That (v.RetainCount, Is.EqualTo (v2), "Value.RetainCount-c"); } Assert.That (k.RetainCount, Is.LessThan (k2), "Key.RetainCount-d"); @@ -243,7 +243,7 @@ public void XForY_Autorelease () Assert.That (x [0], Is.SameAs (k), "KeysForObject"); var y = d.ObjectForKey (k); - Assert.NotNull (y, "ObjectForKey"); + Assert.That (y, Is.Not.Null, "ObjectForKey"); using (var a = new NSMutableArray ()) { a.Add (k); @@ -268,17 +268,17 @@ public void Copy () // NSObject.Copy works because NSDictionary conforms to NSCopying // note: we do not Dispose the "copies" because it's the same instance being returned var copy1 = (NSDictionary) d.Copy (); - Assert.AreSame (d, copy1, "1"); + Assert.That (copy1, Is.SameAs (d), "1"); Assert.That (copy1, Is.Not.TypeOf (), "NSDictionary-1"); Assert.That (copy1.Count, Is.EqualTo ((nuint) 1), "Count-1"); var copy2 = (NSDictionary) d.Copy (null); - Assert.AreSame (d, copy2, "2"); + Assert.That (copy2, Is.SameAs (d), "2"); Assert.That (copy2, Is.Not.TypeOf (), "NSDictionary-2"); Assert.That (copy2.Count, Is.EqualTo ((nuint) 1), "Count-2"); var copy3 = (NSDictionary) d.Copy (NSZone.Default); - Assert.AreSame (d, copy3, "3"); + Assert.That (copy3, Is.SameAs (d), "3"); Assert.That (copy3, Is.Not.TypeOf (), "NSDictionary-3"); Assert.That (copy3.Count, Is.EqualTo ((nuint) 1), "Count-3"); } @@ -316,8 +316,8 @@ public void ObjectForKeyTest () var dict = new NSDictionary (key, value); Assert.Throws (() => dict.ObjectForKey ((NSString) null), "ANE"); - Assert.AreSame (value, dict.ObjectForKey (key), "right"); - Assert.IsNull (dict.ObjectForKey ((NSString) "wrong key"), "wrong"); + Assert.That (dict.ObjectForKey (key), Is.SameAs (value), "right"); + Assert.That (dict.ObjectForKey ((NSString) "wrong key"), Is.Null, "wrong"); } [Test] @@ -328,8 +328,8 @@ public void KeysTest () var dict = new NSDictionary (key, value); var keys = dict.Keys; - Assert.AreEqual (1, keys.Length, "Length"); - Assert.AreSame (key, keys [0], "1"); + Assert.That (keys.Length, Is.EqualTo (1), "Length"); + Assert.That (keys [0], Is.SameAs (key), "1"); } [Test] @@ -348,14 +348,14 @@ public void KeysForObjectTest () ); var rv = dict.KeysForObject (value1); - Assert.AreEqual (2, rv.Length, "v1"); + Assert.That (rv.Length, Is.EqualTo (2), "v1"); rv = dict.KeysForObject (value2); - Assert.AreEqual (1, rv.Length, "v2"); - Assert.AreSame (key3, rv [0], "v2 key"); + Assert.That (rv.Length, Is.EqualTo (1), "v2"); + Assert.That (rv [0], Is.SameAs (key3), "v2 key"); rv = dict.KeysForObject (value3); - Assert.AreEqual (0, rv.Length, "v3"); + Assert.That (rv.Length, Is.EqualTo (0), "v3"); Assert.Throws (() => dict.KeysForObject (null), "ANE"); } @@ -368,8 +368,8 @@ public void ValuesTest () var dict = new NSDictionary (key, value); var keys = dict.Values; - Assert.AreEqual (1, dict.Values.Length, "Length"); - Assert.AreSame (value, dict [key], "1"); + Assert.That (dict.Values.Length, Is.EqualTo (1), "Length"); + Assert.That (dict [key], Is.SameAs (value), "1"); } [Test] @@ -389,12 +389,12 @@ public void ObjectsForKeysTest () ); var rv = dict.ObjectsForKeys (new NSString [] { key1, key4 }, value3); - Assert.AreEqual (2, rv.Length, "a"); - Assert.AreSame (value1, rv [0], "a 0"); - Assert.AreSame (value3, rv [1], "a 1"); + Assert.That (rv.Length, Is.EqualTo (2), "a"); + Assert.That (rv [0], Is.SameAs (value1), "a 0"); + Assert.That (rv [1], Is.SameAs (value3), "a 1"); rv = dict.ObjectsForKeys (new NSString [] { }, value3); - Assert.AreEqual (0, rv.Length, "b length"); + Assert.That (rv.Length, Is.EqualTo (0), "b length"); Assert.Throws (() => dict.ObjectsForKeys ((NSString []) null, value3), "c"); Assert.Throws (() => dict.ObjectsForKeys (new NSString [] { }, null), "d"); @@ -415,8 +415,8 @@ public void ContainsKeyTest () new NSDate [] { value1, value1 } ); - Assert.True (dict.ContainsKey (key1), "a"); - Assert.False (dict.ContainsKey (key3), "b"); + Assert.That (dict.ContainsKey (key1), Is.True, "a"); + Assert.That (dict.ContainsKey (key3), Is.False, "b"); Assert.Throws (() => dict.ContainsKey ((NSString) null), "ANE"); } @@ -437,11 +437,11 @@ public void TryGetValueTest () NSDate value; - Assert.True (dict.TryGetValue (key1, out value), "a"); - Assert.AreSame (value1, value, "a same"); + Assert.That (dict.TryGetValue (key1, out value), Is.True, "a"); + Assert.That (value, Is.SameAs (value1), "a same"); - Assert.False (dict.TryGetValue (key3, out value), "b"); - Assert.IsNull (value, "b null"); + Assert.That (dict.TryGetValue (key3, out value), Is.False, "b"); + Assert.That (value, Is.Null, "b null"); } [Test] @@ -459,8 +459,8 @@ public void IndexerTest () new NSDate [] { value1, value1 } ); - Assert.AreSame (value1, dict [key1], "a"); - Assert.IsNull (dict [key3], "b"); + Assert.That (dict [key1], Is.SameAs (value1), "a"); + Assert.That (dict [key3], Is.Null, "b"); Assert.Throws (() => GC.KeepAlive (dict [(NSString) null]), "c"); } @@ -474,11 +474,11 @@ public void IndexerGetterKeyNotFoundBehaviorTest () var dict = new NSDictionary (key1, value1); // Accessing via the property indexer should return null for missing keys - Assert.IsNull (dict [keyMissing], "missing key"); + Assert.That (dict [keyMissing], Is.Null, "missing key"); // Accessing via IDictionary interface should also return null (NSDictionary behavior) IDictionary idict = dict; - Assert.IsNull (idict [keyMissing], "missing key via interface"); + Assert.That (idict [keyMissing], Is.Null, "missing key via interface"); } [Test] @@ -496,22 +496,22 @@ public void MissingKeyAccessTest () ); // ObjectForKey should return null for missing keys - Assert.IsNull (dict.ObjectForKey (keyMissing), "ObjectForKey missing"); + Assert.That (dict.ObjectForKey (keyMissing), Is.Null, "ObjectForKey missing"); // TryGetValue should return false for missing keys NSDate value; - Assert.IsFalse (dict.TryGetValue (keyMissing, out value), "TryGetValue missing"); - Assert.IsNull (value, "TryGetValue out value"); + Assert.That (dict.TryGetValue (keyMissing, out value), Is.False, "TryGetValue missing"); + Assert.That (value, Is.Null, "TryGetValue out value"); // ContainsKey should return false for missing keys - Assert.IsFalse (dict.ContainsKey (keyMissing), "ContainsKey missing"); + Assert.That (dict.ContainsKey (keyMissing), Is.False, "ContainsKey missing"); // Indexer getter should return null for missing keys - Assert.IsNull (dict [keyMissing], "Indexer missing"); + Assert.That (dict [keyMissing], Is.Null, "Indexer missing"); // IDictionary indexer should also return null for missing keys IDictionary idict = dict; - Assert.IsNull (idict [keyMissing], "IDictionary indexer missing"); + Assert.That (idict [keyMissing], Is.Null, "IDictionary indexer missing"); } [Test] @@ -521,17 +521,17 @@ public void EmptyDictionaryMissingKeyTest () var keyMissing = new NSString ("missing"); // All access methods should handle missing keys in empty dictionary - Assert.IsNull (dict.ObjectForKey (keyMissing), "ObjectForKey"); - Assert.IsFalse (dict.ContainsKey (keyMissing), "ContainsKey"); + Assert.That (dict.ObjectForKey (keyMissing), Is.Null, "ObjectForKey"); + Assert.That (dict.ContainsKey (keyMissing), Is.False, "ContainsKey"); NSDate value; - Assert.IsFalse (dict.TryGetValue (keyMissing, out value), "TryGetValue"); - Assert.IsNull (value, "TryGetValue out"); + Assert.That (dict.TryGetValue (keyMissing, out value), Is.False, "TryGetValue"); + Assert.That (value, Is.Null, "TryGetValue out"); - Assert.IsNull (dict [keyMissing], "Indexer"); + Assert.That (dict [keyMissing], Is.Null, "Indexer"); IDictionary idict = dict; - Assert.IsNull (idict [keyMissing], "IDictionary indexer"); + Assert.That (idict [keyMissing], Is.Null, "IDictionary indexer"); } [Test] @@ -552,17 +552,17 @@ public void ObjectsForKeysMissingKeysTest () // Request mix of existing and missing keys - marker should replace missing values var result = dict.ObjectsForKeys (new NSString [] { key1, keyMissing1, key2, keyMissing2 }, marker); - Assert.AreEqual (4, result.Length, "Length"); - Assert.AreSame (value1, result [0], "0 - existing"); - Assert.AreSame (marker, result [1], "1 - missing"); - Assert.AreSame (value2, result [2], "2 - existing"); - Assert.AreSame (marker, result [3], "3 - missing"); + Assert.That (result.Length, Is.EqualTo (4), "Length"); + Assert.That (result [0], Is.SameAs (value1), "0 - existing"); + Assert.That (result [1], Is.SameAs (marker), "1 - missing"); + Assert.That (result [2], Is.SameAs (value2), "2 - existing"); + Assert.That (result [3], Is.SameAs (marker), "3 - missing"); // Request all missing keys result = dict.ObjectsForKeys (new NSString [] { keyMissing1, keyMissing2 }, marker); - Assert.AreEqual (2, result.Length, "All missing length"); - Assert.AreSame (marker, result [0], "All missing 0"); - Assert.AreSame (marker, result [1], "All missing 1"); + Assert.That (result.Length, Is.EqualTo (2), "All missing length"); + Assert.That (result [0], Is.SameAs (marker), "All missing 0"); + Assert.That (result [1], Is.SameAs (marker), "All missing 1"); } [Test] @@ -576,7 +576,7 @@ public void ReadOnlyDictionaryTest () IDictionary idict = dict; // Verify it's read-only - Assert.IsTrue (idict.IsReadOnly, "IsReadOnly"); + Assert.That (idict.IsReadOnly, Is.True, "IsReadOnly"); // Verify all mutating operations throw NotSupportedException Assert.Throws (() => idict.Add (key2, value1), "Add"); @@ -609,13 +609,13 @@ public void IDictionary2Test () Assert.Throws (() => dict.Clear (), "Clear"); // Contains - Assert.IsTrue (dict.Contains (new KeyValuePair (key1, value1)), "Contains 1"); // both key and value matches - Assert.IsFalse (dict.Contains (new KeyValuePair (key1, value2)), "Contains 2"); // found key, wrong value - Assert.IsFalse (dict.Contains (new KeyValuePair (key3, value2)), "Contains 3"); // wrong key + Assert.That (dict.Contains (new KeyValuePair (key1, value1)), Is.True, "Contains 1"); // both key and value matches + Assert.That (dict.Contains (new KeyValuePair (key1, value2)), Is.False, "Contains 2"); // found key, wrong value + Assert.That (dict.Contains (new KeyValuePair (key3, value2)), Is.False, "Contains 3"); // wrong key // ContainsKey - Assert.IsTrue (dict.ContainsKey (key1), "ContainsKey 1"); - Assert.IsFalse (dict.ContainsKey (key3), "ContainsKey 2"); + Assert.That (dict.ContainsKey (key1), Is.True, "ContainsKey 1"); + Assert.That (dict.ContainsKey (key3), Is.False, "ContainsKey 2"); // CopyTo var kvp_array = new KeyValuePair [1]; @@ -629,22 +629,22 @@ public void IDictionary2Test () Assert.Throws (() => dict.CopyTo (kvp_array, 1), "CopyTo AE 4"); dict.CopyTo (kvp_array, 0); Assert.That (key1, Is.SameAs (kvp_array [0].Key).Or.SameAs (kvp_array [1].Key), "CopyTo K1"); - Assert.AreSame (value1, kvp_array [0].Value, "CopyTo V1"); + Assert.That (kvp_array [0].Value, Is.SameAs (value1), "CopyTo V1"); Assert.That (key2, Is.SameAs (kvp_array [0].Key).Or.SameAs (kvp_array [1].Key), "CopyTo K2"); - Assert.AreSame (value1, kvp_array [1].Value, "CopyTo V2"); + Assert.That (kvp_array [1].Value, Is.SameAs (value1), "CopyTo V2"); // Count - Assert.AreEqual (2, dict.Count, "Count"); + Assert.That (dict.Count, Is.EqualTo (2), "Count"); // GetEnumerator var enumerated = Enumerable.ToArray (dict); - Assert.AreEqual (2, enumerated.Length, "Enumerator Count"); + Assert.That (enumerated.Length, Is.EqualTo (2), "Enumerator Count"); // IsReadOnly - Assert.IsTrue (dict.IsReadOnly, "IsReadOnly"); + Assert.That (dict.IsReadOnly, Is.True, "IsReadOnly"); // Keys - Assert.AreEqual (2, dict.Keys.Count, "Keys Count"); + Assert.That (dict.Keys.Count, Is.EqualTo (2), "Keys Count"); // Remove Assert.Throws (() => dict.Remove (null), "Remove NSE"); @@ -652,16 +652,16 @@ public void IDictionary2Test () // TryGetValue NSDate value; Assert.Throws (() => dict.TryGetValue (null, out value), "TryGetValue ANE"); - Assert.IsTrue (dict.TryGetValue (key1, out value), "TryGetValue K1"); - Assert.AreSame (value1, value, "TryGetValue V1"); - Assert.IsFalse (dict.TryGetValue (key3, out value), "TryGetValue K2"); + Assert.That (dict.TryGetValue (key1, out value), Is.True, "TryGetValue K1"); + Assert.That (value, Is.SameAs (value1), "TryGetValue V1"); + Assert.That (dict.TryGetValue (key3, out value), Is.False, "TryGetValue K2"); // Values - Assert.AreEqual (2, dict.Values.Count, "Values Count"); + Assert.That (dict.Values.Count, Is.EqualTo (2), "Values Count"); // Indexer - Assert.AreSame (value1, dict [key1], "this [1]"); - Assert.IsNull (dict [key3], "this [2]"); + Assert.That (dict [key1], Is.SameAs (value1), "this [1]"); + Assert.That (dict [key3], Is.Null, "this [2]"); Assert.Throws (() => GC.KeepAlive (dict [null]), "this [null]"); Assert.Throws (() => dict [key3] = value3, "this [1] = 1"); @@ -691,9 +691,9 @@ public void ICollection2Test () Assert.Throws (() => dict.Clear (), "Clear"); // Contains - Assert.IsTrue (dict.Contains (new KeyValuePair (key1, value1)), "Contains 1"); // both key and value matches - Assert.IsFalse (dict.Contains (new KeyValuePair (key1, value2)), "Contains 2"); // found key, wrong value - Assert.IsFalse (dict.Contains (new KeyValuePair (key3, value2)), "Contains 3"); // wrong key + Assert.That (dict.Contains (new KeyValuePair (key1, value1)), Is.True, "Contains 1"); // both key and value matches + Assert.That (dict.Contains (new KeyValuePair (key1, value2)), Is.False, "Contains 2"); // found key, wrong value + Assert.That (dict.Contains (new KeyValuePair (key3, value2)), Is.False, "Contains 3"); // wrong key // CopyTo @@ -708,19 +708,19 @@ public void ICollection2Test () Assert.Throws (() => dict.CopyTo (kvp_array, 1), "CopyTo AE 4"); dict.CopyTo (kvp_array, 0); Assert.That (key1, Is.SameAs (kvp_array [0].Key).Or.SameAs (kvp_array [1].Key), "CopyTo K1"); - Assert.AreSame (value1, kvp_array [0].Value, "CopyTo V1"); + Assert.That (kvp_array [0].Value, Is.SameAs (value1), "CopyTo V1"); Assert.That (key2, Is.SameAs (kvp_array [0].Key).Or.SameAs (kvp_array [1].Key), "CopyTo K2"); - Assert.AreSame (value1, kvp_array [1].Value, "CopyTo V2"); + Assert.That (kvp_array [1].Value, Is.SameAs (value1), "CopyTo V2"); // Count - Assert.AreEqual (2, dict.Count, "Count"); + Assert.That (dict.Count, Is.EqualTo (2), "Count"); // GetEnumerator var enumerated = Enumerable.ToArray (dict); - Assert.AreEqual (2, enumerated.Length, "Enumerator Count"); + Assert.That (enumerated.Length, Is.EqualTo (2), "Enumerator Count"); // IsReadOnly - Assert.IsTrue (dict.IsReadOnly, "IsReadOnly"); + Assert.That (dict.IsReadOnly, Is.True, "IsReadOnly"); // Remove Assert.Throws (() => dict.Remove (new KeyValuePair (null, null)), "Remove NSE"); @@ -745,7 +745,7 @@ public void IEnumerable_KVP2Test () // GetEnumerator var enumerated = Enumerable.ToArray (dict); - Assert.AreEqual (2, enumerated.Length, "Enumerator Count"); + Assert.That (enumerated.Length, Is.EqualTo (2), "Enumerator Count"); } [Test] @@ -769,7 +769,7 @@ public void IEnumerableTest () var c = 0; foreach (var obj in dict) c++; - Assert.AreEqual (2, c, "Enumerator Count"); + Assert.That (c, Is.EqualTo (2), "Enumerator Count"); } [Test] diff --git a/tests/monotouch-test/Foundation/NSDictionaryTest.cs b/tests/monotouch-test/Foundation/NSDictionaryTest.cs index cd738779b9b9..7d81d86a58ed 100644 --- a/tests/monotouch-test/Foundation/NSDictionaryTest.cs +++ b/tests/monotouch-test/Foundation/NSDictionaryTest.cs @@ -17,14 +17,14 @@ public void DictionaryCtorKeyValues () var value = new NSString ("value"); var j = new NSDictionary (key, value); - Assert.AreEqual (j.Count, (nuint) 1, "count"); - Assert.AreEqual (j [key], value, "key lookup"); + Assert.That (j.Count, Is.EqualTo ((nuint) 1), "count"); + Assert.That (value, Is.EqualTo (j [key]), "key lookup"); j = new NSDictionary (new NSString ("first"), new NSString ("first-k"), new NSString ("second"), new NSString ("second-k")); - Assert.AreEqual (j.Count, (nuint) 2, "count"); - Assert.AreEqual ((string) (NSString) (j ["first"]), "first-k", "lookup1"); - Assert.AreEqual ((string) (NSString) (j ["second"]), "second-k", "lookup2"); + Assert.That (j.Count, Is.EqualTo ((nuint) 2), "count"); + Assert.That ((string) (NSString) (j ["first"]), Is.EqualTo ("first-k"), "lookup1"); + Assert.That ((string) (NSString) (j ["second"]), Is.EqualTo ("second-k"), "lookup2"); } [Test] @@ -32,14 +32,14 @@ public void DictionaryCtorKeyValuesObjects () { var j = new NSDictionary ("key", "value"); - Assert.AreEqual (j.Count, (nuint) 1, "count"); - Assert.AreEqual ((string) (NSString) (j ["key"]), "value", "key lookup"); + Assert.That (j.Count, Is.EqualTo ((nuint) 1), "count"); + Assert.That ((string) (NSString) (j ["key"]), Is.EqualTo ("value"), "key lookup"); j = new NSDictionary (1, 2, 3, 4); - Assert.AreEqual (j.Count, (nuint) 2, "count"); - Assert.AreEqual (((NSNumber) j [new NSNumber (1)]).Int32Value, 2, "lookup1"); - Assert.AreEqual (((NSNumber) j [new NSNumber (3)]).Int32Value, 4, "lookup2"); + Assert.That (j.Count, Is.EqualTo ((nuint) 2), "count"); + Assert.That (((NSNumber) j [new NSNumber (1)]).Int32Value, Is.EqualTo (2), "lookup1"); + Assert.That (((NSNumber) j [new NSNumber (3)]).Int32Value, Is.EqualTo (4), "lookup2"); } [Test] @@ -83,13 +83,13 @@ public void KeyValue_Autorelease () v2 = v.RetainCount; Assert.That (v2, Is.GreaterThan (v1), "Value.RetainCount-b"); - Assert.NotNull (d.Keys, "Keys"); + Assert.That (d.Keys, Is.Not.Null, "Keys"); // accessing `allKeys` should *NOT* change the retainCount // that would happen without an [Autorelease] and can lead to memory exhaustion // https://bugzilla.xamarin.com/show_bug.cgi?id=7723 Assert.That (k.RetainCount, Is.EqualTo (k2), "Key.RetainCount-c"); - Assert.NotNull (d.Values, "Values"); + Assert.That (d.Values, Is.Not.Null, "Values"); Assert.That (v.RetainCount, Is.EqualTo (v2), "Value.RetainCount-c"); } Assert.That (k.RetainCount, Is.LessThan (k2), "Key.RetainCount-d"); @@ -120,7 +120,7 @@ public void XForY_Autorelease () Assert.That (x [0], Is.SameAs (k), "KeysForObject"); var y = d.ObjectForKey (k); - Assert.NotNull (y, "ObjectForKey"); + Assert.That (y, Is.Not.Null, "ObjectForKey"); using (var a = new NSMutableArray ()) { a.Add (k); @@ -144,13 +144,13 @@ public void FromObjectsAndKeysTest () var objs = new NSObject [] { new NSNumber (1), new NSNumber (4) }; NSDictionary ns = NSDictionary.FromObjectsAndKeys (objs, keys, 1); Console.WriteLine (ns.Count); - Assert.AreEqual ((nuint) 1, ns.Count, "#1"); + Assert.That (ns.Count, Is.EqualTo ((nuint) 1), "#1"); } { var keys = new object [] { 1, 2 }; var objs = new object [] { 3, 4 }; NSDictionary ns = NSDictionary.FromObjectsAndKeys (objs, keys, 1); - Assert.AreEqual ((nuint) 1, ns.Count, "#2"); + Assert.That (ns.Count, Is.EqualTo ((nuint) 1), "#2"); } } @@ -160,10 +160,10 @@ public void FromObjectsAndKeysTest_NullValue () var keys = new NSObject [] { new NSNumber (1), new NSNumber (2), new NSNumber (3) }; var objs = new NSObject? [] { new NSNumber (1), null, new NSNumber (4) }; NSDictionary ns = NSDictionary.FromObjectsAndKeys (objs, keys, 3); - Assert.AreEqual ((nuint) 3, ns.Count, "Count"); - Assert.AreEqual (1, ((NSNumber) ns [new NSNumber (1)]).Int32Value, "Value 1"); - Assert.IsInstanceOf (ns [new NSNumber (2)], "Null value"); - Assert.AreEqual (4, ((NSNumber) ns [new NSNumber (3)]).Int32Value, "Value 3"); + Assert.That (ns.Count, Is.EqualTo ((nuint) 3), "Count"); + Assert.That (((NSNumber) ns [new NSNumber (1)]).Int32Value, Is.EqualTo (1), "Value 1"); + Assert.That (ns [new NSNumber (2)], Is.InstanceOf (), "Null value"); + Assert.That (((NSNumber) ns [new NSNumber (3)]).Int32Value, Is.EqualTo (4), "Value 3"); } [Test] @@ -172,10 +172,10 @@ public void FromObjectsAndKeysTest_NullValue_NoCount () var keys = new NSObject [] { new NSNumber (1), new NSNumber (2), new NSNumber (3) }; var objs = new NSObject? [] { new NSNumber (1), null, new NSNumber (4) }; NSDictionary ns = NSDictionary.FromObjectsAndKeys (objs, keys); - Assert.AreEqual ((nuint) 3, ns.Count, "Count"); - Assert.AreEqual (1, ((NSNumber) ns [new NSNumber (1)]).Int32Value, "Value 1"); - Assert.IsInstanceOf (ns [new NSNumber (2)], "Null value"); - Assert.AreEqual (4, ((NSNumber) ns [new NSNumber (3)]).Int32Value, "Value 3"); + Assert.That (ns.Count, Is.EqualTo ((nuint) 3), "Count"); + Assert.That (((NSNumber) ns [new NSNumber (1)]).Int32Value, Is.EqualTo (1), "Value 1"); + Assert.That (ns [new NSNumber (2)], Is.InstanceOf (), "Null value"); + Assert.That (((NSNumber) ns [new NSNumber (3)]).Int32Value, Is.EqualTo (4), "Value 3"); } [Test] @@ -187,15 +187,15 @@ public void DictionaryCtorKeyValues_WithNull () // Test null value var dict = new NSDictionary (key1, null); - Assert.AreEqual ((nuint) 1, dict.Count, "count with null value"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 1), "count with null value"); var rawValue = dict.ObjectForKey (key1); - Assert.IsInstanceOf (rawValue, "Null value should be NSNull"); + Assert.That (rawValue, Is.InstanceOf (), "Null value should be NSNull"); // Test null in variadic args (value position) dict = new NSDictionary (key1, value, key2, null); - Assert.AreEqual ((nuint) 2, dict.Count, "count with null in args"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 2), "count with null in args"); rawValue = dict.ObjectForKey (key2); - Assert.IsInstanceOf (rawValue, "Null value in args should be NSNull"); + Assert.That (rawValue, Is.InstanceOf (), "Null value in args should be NSNull"); } [Test] @@ -207,17 +207,17 @@ public void Copy () // NSObject.Copy works because NSDictionary conforms to NSCopying // note: we do not Dispose the "copies" because it's the same instance being returned var copy1 = (NSDictionary) d.Copy (); - Assert.AreSame (d, copy1, "1"); + Assert.That (copy1, Is.SameAs (d), "1"); Assert.That (copy1, Is.Not.TypeOf (), "NSDictionary-1"); Assert.That (copy1.Count, Is.EqualTo ((nuint) 1), "Count-1"); var copy2 = (NSDictionary) d.Copy (null); - Assert.AreSame (d, copy2, "2"); + Assert.That (copy2, Is.SameAs (d), "2"); Assert.That (copy2, Is.Not.TypeOf (), "NSDictionary-2"); Assert.That (copy2.Count, Is.EqualTo ((nuint) 1), "Count-2"); var copy3 = (NSDictionary) d.Copy (NSZone.Default); - Assert.AreSame (d, copy3, "3"); + Assert.That (copy3, Is.SameAs (d), "3"); Assert.That (copy3, Is.Not.TypeOf (), "NSDictionary-3"); Assert.That (copy3.Count, Is.EqualTo ((nuint) 1), "Count-3"); } @@ -268,7 +268,7 @@ public void IndexerTest () objptr = Messaging.IntPtr_objc_msgSend_IntPtr (Class.GetHandle (typeof (NSString)), Selector.GetHandle ("stringWithUTF8String:"), strobjptr); using (var dict = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (Class.GetHandle (typeof (NSDictionary)), Selector.GetHandle ("dictionaryWithObject:forKey:"), objptr, keyptr))) { v = (NSString) dict ["key"]; - Assert.AreEqual ("obj", (string) v, "a"); + Assert.That ((string) v, Is.EqualTo ("obj"), "a"); Assert.Throws (() => dict ["key"] = (NSString) "value", "a ex"); } @@ -278,7 +278,7 @@ public void IndexerTest () objptr = Messaging.IntPtr_objc_msgSend_IntPtr (Class.GetHandle (typeof (NSString)), Selector.GetHandle ("stringWithUTF8String:"), strobjptr); using (var dict = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (Class.GetHandle (typeof (NSDictionary)), Selector.GetHandle ("dictionaryWithObject:forKey:"), objptr, keyptr))) { v = (NSString) dict [(NSObject) (NSString) "key"]; - Assert.AreEqual ("obj", (string) v, "b"); + Assert.That ((string) v, Is.EqualTo ("obj"), "b"); Assert.Throws (() => dict [(NSObject) (NSString) "key"] = (NSString) "value", "a ex"); } @@ -288,7 +288,7 @@ public void IndexerTest () objptr = Messaging.IntPtr_objc_msgSend_IntPtr (Class.GetHandle (typeof (NSString)), Selector.GetHandle ("stringWithUTF8String:"), strobjptr); using (var dict = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (Class.GetHandle (typeof (NSDictionary)), Selector.GetHandle ("dictionaryWithObject:forKey:"), objptr, keyptr))) { v = (NSString) dict [(NSString) "key"]; - Assert.AreEqual ("obj", (string) v, "c"); + Assert.That ((string) v, Is.EqualTo ("obj"), "c"); Assert.Throws (() => dict [(NSString) "key"] = (NSString) "value", "a ex"); } diff --git a/tests/monotouch-test/Foundation/NSExpressionTest.cs b/tests/monotouch-test/Foundation/NSExpressionTest.cs index 07e590896a2d..1f5d711d5079 100644 --- a/tests/monotouch-test/Foundation/NSExpressionTest.cs +++ b/tests/monotouch-test/Foundation/NSExpressionTest.cs @@ -57,7 +57,7 @@ public void FromKeyPath () { using (var expression = NSExpression.FromKeyPath ("value")) using (var result = expression.EvaluateWith (null, null) as NSString) - Assert.IsNull (result); + Assert.That (result, Is.Null); } [Test] @@ -65,7 +65,7 @@ public void FromFunctionTest () { using (var expression = NSExpression.FromFunction ((o, e, c) => { return new NSString ("Foo"); }, new NSExpression [] { })) using (var result = expression.EvaluateWith (null, null) as NSString) - Assert.AreEqual ("Foo", result.ToString ()); + Assert.That (result.ToString (), Is.EqualTo ("Foo")); } [Test] @@ -73,7 +73,7 @@ public void FromFormatWithArgsTest () { using (var expression = NSExpression.FromFormat ("%f*%f", new NSObject [] { new NSNumber (2.0), new NSNumber (2.0) })) using (var result = expression.EvaluateWith (null, null) as NSNumber) - Assert.AreEqual (4.0, result.DoubleValue); + Assert.That (result.DoubleValue, Is.EqualTo (4.0)); } [Test] @@ -81,7 +81,7 @@ public void FromFormatWithNoArgsTest () { using (var expression = NSExpression.FromFormat ("2*2")) using (var result = expression.EvaluateWith (null, null) as NSNumber) - Assert.AreEqual (4.0, result.DoubleValue); + Assert.That (result.DoubleValue, Is.EqualTo (4.0)); } [Test] @@ -89,7 +89,7 @@ public void FromFormatConstant () { using (var expression = NSExpression.FromFormat ("2")) using (var result = expression.EvaluateWith (null, null) as NSNumber) - Assert.AreEqual (2, result.DoubleValue); + Assert.That (result.DoubleValue, Is.EqualTo (2)); } [Test] @@ -99,7 +99,7 @@ public void AggregatePropertiesTest () using (var lower = NSExpression.FromConstant (new NSNumber (0))) using (var upper = NSExpression.FromConstant (new NSNumber (5))) using (var expression = NSExpression.FromAggregate (new NSExpression [] { lower, upper })) { - Assert.AreEqual (NSExpressionType.NSAggregate, expression.ExpressionType); + Assert.That (expression.ExpressionType, Is.EqualTo (NSExpressionType.NSAggregate)); TestProperties (expression, availableProperties); } } @@ -116,7 +116,7 @@ public void UnionSetPropertiesTest () using (var rupper = NSExpression.FromConstant (new NSNumber (50))) using (var rh = NSExpression.FromAggregate (new NSExpression [] { rlower, rupper })) using (var expression = NSExpression.FromUnionSet (lh, rh)) { - Assert.AreEqual (NSExpressionType.UnionSet, expression.ExpressionType); + Assert.That (expression.ExpressionType, Is.EqualTo (NSExpressionType.UnionSet)); TestProperties (expression, availableProperties); } } @@ -133,7 +133,7 @@ public void IntersectSetPropertiesTest () using (var rupper = NSExpression.FromConstant (new NSNumber (50))) using (var rh = NSExpression.FromAggregate (new NSExpression [] { rlower, rupper })) using (var expression = NSExpression.FromIntersectSet (lh, rh)) { - Assert.AreEqual (NSExpressionType.IntersectSet, expression.ExpressionType); + Assert.That (expression.ExpressionType, Is.EqualTo (NSExpressionType.IntersectSet)); TestProperties (expression, availableProperties); } } @@ -150,7 +150,7 @@ public void MinusSetPropertiesTest () using (var rupper = NSExpression.FromConstant (new NSNumber (50))) using (var rh = NSExpression.FromAggregate (new NSExpression [] { rlower, rupper })) using (var expression = NSExpression.FromMinusSet (lh, rh)) { - Assert.AreEqual (NSExpressionType.MinusSet, expression.ExpressionType); + Assert.That (expression.ExpressionType, Is.EqualTo (NSExpressionType.MinusSet)); TestProperties (expression, availableProperties); } } @@ -160,7 +160,7 @@ public void ConstantPropertiesTest () { var availableProperties = new List { "ConstantValue" }; using (var expression = NSExpression.FromFormat ("2")) { - Assert.AreEqual (NSExpressionType.ConstantValue, expression.ExpressionType); + Assert.That (expression.ExpressionType, Is.EqualTo (NSExpressionType.ConstantValue)); TestProperties (expression, availableProperties); } } @@ -170,7 +170,7 @@ public void VariablePropertiesTest () { var availableProperties = new List { "Variable" }; using (var expression = NSExpression.FromVariable ("Variable")) { - Assert.AreEqual (NSExpressionType.Variable, expression.ExpressionType); + Assert.That (expression.ExpressionType, Is.EqualTo (NSExpressionType.Variable)); TestProperties (expression, availableProperties); } } @@ -180,7 +180,7 @@ public void KeyPathPropertiesTest () { var availableProperties = new List { "KeyPath", "Operand", "Arguments" }; using (var expression = NSExpression.FromKeyPath ("value")) { - Assert.AreEqual (NSExpressionType.KeyPath, expression.ExpressionType); + Assert.That (expression.ExpressionType, Is.EqualTo (NSExpressionType.KeyPath)); TestProperties (expression, availableProperties); } } @@ -190,7 +190,7 @@ public void FunctionPropertiesTest () { var availableProperties = new List { "Function", "Operand", "Arguments" }; using (var expression = NSExpression.FromFormat ("2*2")) { - Assert.AreEqual (NSExpressionType.Function, expression.ExpressionType); + Assert.That (expression.ExpressionType, Is.EqualTo (NSExpressionType.Function)); TestProperties (expression, availableProperties); } } @@ -200,7 +200,7 @@ public void BlockPropertiesTest () { var availableProperties = new List { "Block", "Arguments" }; using (var expression = NSExpression.FromFunction ((o, e, c) => { return new NSString ("Foo"); }, new NSExpression [] { })) { - Assert.AreEqual (NSExpressionType.Block, expression.ExpressionType); + Assert.That (expression.ExpressionType, Is.EqualTo (NSExpressionType.Block)); TestProperties (expression, availableProperties); } } @@ -212,7 +212,7 @@ public void EvaluatedObjectPropertiesTest () var mySearchKey = new NSString ("James"); using (var predicate = NSPredicate.FromFormat ("ANY employees.firstName like 'Matthew'") as NSComparisonPredicate) using (var expression = predicate.LeftExpression.Operand) { // NSExpressionType.EvaluatedObject; - Assert.AreEqual (NSExpressionType.EvaluatedObject, expression.ExpressionType); + Assert.That (expression.ExpressionType, Is.EqualTo (NSExpressionType.EvaluatedObject)); TestProperties (expression, availableProperties); } } @@ -225,7 +225,7 @@ public void AnyKeyPropertiesTest () var availableProperties = new List { }; using (var expression = NSExpression.FromAnyKey ()) { - Assert.AreEqual (NSExpressionType.AnyKey, expression.ExpressionType); + Assert.That (expression.ExpressionType, Is.EqualTo (NSExpressionType.AnyKey)); TestProperties (expression, availableProperties); } } diff --git a/tests/monotouch-test/Foundation/NSFormatter.cs b/tests/monotouch-test/Foundation/NSFormatter.cs index 36e7f92945bf..fff19b346c09 100644 --- a/tests/monotouch-test/Foundation/NSFormatter.cs +++ b/tests/monotouch-test/Foundation/NSFormatter.cs @@ -21,7 +21,7 @@ public void NSFormatter_ShouldGetString () { var str = formatter.StringFor (NSNumber.FromFloat (0.12f)); - Assert.AreEqual (str, "$0.12"); + Assert.That (str, Is.EqualTo ("$0.12")); } [Test] @@ -29,7 +29,7 @@ public void NSFormatter_ShouldGetAttributedString () { var str = formatter.GetAttributedString (NSNumber.FromFloat (3.21f), new NSStringAttributes () { Font = NSFont.SystemFontOfSize (8) }); - Assert.AreEqual (str.Value, "$3.21"); + Assert.That (str.Value, Is.EqualTo ("$3.21")); } [Test] @@ -37,7 +37,7 @@ public void NSFormatter_ShouldGetEditingString () { var str = formatter.EditingStringFor (NSNumber.FromInt32 (14)); - Assert.AreEqual (str, "$14.00"); + Assert.That (str, Is.EqualTo ("$14.00")); } [Test] @@ -48,7 +48,7 @@ public void NSFormatter_IsPartialStringValid () formatter.PartialStringValidationEnabled = true; var valid = formatter.IsPartialStringValid ("valid string", out newstr, out error); - Assert.IsTrue (valid); + Assert.That (valid, Is.True); } } } diff --git a/tests/monotouch-test/Foundation/NSHostTest.cs b/tests/monotouch-test/Foundation/NSHostTest.cs index 1b47e560eda4..714ab1c7b51b 100644 --- a/tests/monotouch-test/Foundation/NSHostTest.cs +++ b/tests/monotouch-test/Foundation/NSHostTest.cs @@ -9,7 +9,7 @@ public class NSHostTest { public void EqualsNullAllowed () { using var host = NSHost.FromAddress ("http://microsoft.com"); - Assert.False (host.Equals (null)); + Assert.That (host.Equals (null), Is.False); } } } diff --git a/tests/monotouch-test/Foundation/NSInputStreamTest.cs b/tests/monotouch-test/Foundation/NSInputStreamTest.cs index 20eb8a39fdc9..a49481ae29d4 100644 --- a/tests/monotouch-test/Foundation/NSInputStreamTest.cs +++ b/tests/monotouch-test/Foundation/NSInputStreamTest.cs @@ -57,32 +57,32 @@ public unsafe void Read () using (var s = NSInputStream.FromData (data)) { byte [] arr = new byte [10]; s.Open (); - Assert.IsTrue (s.HasBytesAvailable ()); - Assert.AreEqual ((nint) 2, s.Read (arr, 2), "#a 1"); - Assert.AreEqual (0, arr [0], "#a[0]"); - Assert.AreEqual (1, arr [1], "#a[1]"); + Assert.That (s.HasBytesAvailable (), Is.True); + Assert.That (s.Read (arr, 2), Is.EqualTo ((nint) 2), "#a 1"); + Assert.That (arr [0], Is.EqualTo (0), "#a[0]"); + Assert.That (arr [1], Is.EqualTo (1), "#a[1]"); } using (var s = new NSInputStream (data)) { byte [] arr = new byte [10]; s.Open (); - Assert.IsTrue (s.HasBytesAvailable ()); - Assert.AreEqual ((nint) 2, s.Read (arr, 1, 2), "#b 1"); - Assert.AreEqual (0, arr [0], "#b[0]"); - Assert.AreEqual (0, arr [1], "#b[1]"); - Assert.AreEqual (1, arr [2], "#b[2]"); + Assert.That (s.HasBytesAvailable (), Is.True); + Assert.That (s.Read (arr, 1, 2), Is.EqualTo ((nint) 2), "#b 1"); + Assert.That (arr [0], Is.EqualTo (0), "#b[0]"); + Assert.That (arr [1], Is.EqualTo (0), "#b[1]"); + Assert.That (arr [2], Is.EqualTo (1), "#b[2]"); } using (var s = new NSInputStream (data)) { byte [] arr = new byte [10]; s.Open (); - Assert.IsTrue (s.HasBytesAvailable ()); + Assert.That (s.HasBytesAvailable (), Is.True); fixed (byte* ptr = &arr [2]) - Assert.AreEqual ((nint) 2, s.Read ((IntPtr) ptr, 2), "#c 1"); - Assert.AreEqual (0, arr [0], "#c[0]"); - Assert.AreEqual (0, arr [1], "#c[1]"); - Assert.AreEqual (0, arr [2], "#c[2]"); - Assert.AreEqual (1, arr [3], "#c[3]"); + Assert.That (s.Read ((IntPtr) ptr, 2), Is.EqualTo ((nint) 2), "#c 1"); + Assert.That (arr [0], Is.EqualTo (0), "#c[0]"); + Assert.That (arr [1], Is.EqualTo (0), "#c[1]"); + Assert.That (arr [2], Is.EqualTo (0), "#c[2]"); + Assert.That (arr [3], Is.EqualTo (1), "#c[3]"); } } } diff --git a/tests/monotouch-test/Foundation/NSKeyedUnarchiverTest.cs b/tests/monotouch-test/Foundation/NSKeyedUnarchiverTest.cs index 89ed5f9f6ca2..f81ee3b16152 100644 --- a/tests/monotouch-test/Foundation/NSKeyedUnarchiverTest.cs +++ b/tests/monotouch-test/Foundation/NSKeyedUnarchiverTest.cs @@ -10,25 +10,25 @@ public void GetUnarchivedObject_TypeWrappers () NSDictionary testValues = new NSDictionary ((NSString) "1", (NSString) "a"); NSData data = NSKeyedArchiver.GetArchivedData (testValues, true, out NSError error); - Assert.IsNull (error); + Assert.That (error, Is.Null); Type dictionaryType = typeof (NSDictionary); Class dictionaryClass = new Class (dictionaryType); NSObject o = NSKeyedUnarchiver.GetUnarchivedObject (dictionaryClass, data, out error); - Assert.IsNotNull (o); - Assert.IsNull (error, "GetUnarchivedObject - Class"); + Assert.That (o, Is.Not.Null); + Assert.That (error, Is.Null, "GetUnarchivedObject - Class"); o = NSKeyedUnarchiver.GetUnarchivedObject (new NSSet (new Class [] { dictionaryClass }), data, out error); - Assert.IsNotNull (o); - Assert.IsNull (error, "GetUnarchivedObject - NSSet"); + Assert.That (o, Is.Not.Null); + Assert.That (error, Is.Null, "GetUnarchivedObject - NSSet"); o = NSKeyedUnarchiver.GetUnarchivedObject (dictionaryType, data, out error); - Assert.IsNotNull (o); - Assert.IsNull (error, "GetUnarchivedObject - Type"); + Assert.That (o, Is.Not.Null); + Assert.That (error, Is.Null, "GetUnarchivedObject - Type"); o = NSKeyedUnarchiver.GetUnarchivedObject (new Type [] { dictionaryType }, data, out error); - Assert.IsNotNull (o); - Assert.IsNull (error, "GetUnarchivedObject - Type []"); + Assert.That (o, Is.Not.Null); + Assert.That (error, Is.Null, "GetUnarchivedObject - Type []"); } [Test] @@ -39,7 +39,7 @@ public void DataTransformer_AllowedTopLevelTypes_WrapperTests () Class [] classes = NSSecureUnarchiveFromDataTransformer.AllowedTopLevelClasses; Type [] types = NSSecureUnarchiveFromDataTransformer.AllowedTopLevelTypes; - Assert.AreEqual (classes.Length, types.Length, "Lengths not equal"); + Assert.That (types.Length, Is.EqualTo (classes.Length), "Lengths not equal"); } } } diff --git a/tests/monotouch-test/Foundation/NSLinguisticAnalysisTest.cs b/tests/monotouch-test/Foundation/NSLinguisticAnalysisTest.cs index 9997f8002af9..7d1a39b31611 100644 --- a/tests/monotouch-test/Foundation/NSLinguisticAnalysisTest.cs +++ b/tests/monotouch-test/Foundation/NSLinguisticAnalysisTest.cs @@ -32,8 +32,8 @@ public void EnumerateSubstringsInRangeTest () var testString = new NSString ("Hello Hola Bonjour!"); var range = new NSRange (0, testString.Length - 1); testString.EnumerateLinguisticTags (range, NSLinguisticTagScheme.Token, NSLinguisticTaggerOptions.OmitWhitespace, null, Enumerator); - Assert.AreEqual (3, words.Count, "Word count: " + string.Join (", ", words)); - Assert.True (words.Contains (NSLinguisticTag.Word.GetConstant ()), "Token type."); + Assert.That (words.Count, Is.EqualTo (3), "Word count: " + string.Join (", ", words)); + Assert.That (words.Contains (NSLinguisticTag.Word.GetConstant ()), Is.True, "Token type."); } [Test] @@ -42,8 +42,8 @@ public void StopEnumerateSubstringsInRangeTest () var testString = new NSString ("Hello Hola Bonjour!"); var range = new NSRange (0, testString.Length - 1); testString.EnumerateLinguisticTags (range, NSLinguisticTagScheme.Token, NSLinguisticTaggerOptions.OmitWhitespace, null, StopEnumerator); - Assert.AreEqual (1, words.Count, "Word count"); - Assert.True (words.Contains (NSLinguisticTag.Word.GetConstant ()), "Token type."); + Assert.That (words.Count, Is.EqualTo (1), "Word count"); + Assert.That (words.Contains (NSLinguisticTag.Word.GetConstant ()), Is.True, "Token type."); } [Test] @@ -53,7 +53,7 @@ public void GetLinguisticTagsTest () var range = new NSRange (0, testString.Length - 1); NSValue [] tokenRanges; var tags = testString.GetLinguisticTags (range, NSLinguisticTagScheme.NameOrLexicalClass, NSLinguisticTaggerOptions.OmitWhitespace, null, out tokenRanges); - Assert.AreEqual (3, tags.Length, "Tags Length"); + Assert.That (tags.Length, Is.EqualTo (3), "Tags Length"); } } } diff --git a/tests/monotouch-test/Foundation/NSMetadataItem.cs b/tests/monotouch-test/Foundation/NSMetadataItem.cs index 38ddc5bc7155..7769b8d6ce75 100644 --- a/tests/monotouch-test/Foundation/NSMetadataItem.cs +++ b/tests/monotouch-test/Foundation/NSMetadataItem.cs @@ -17,32 +17,32 @@ public void CtorUrl () var url = NSBundle.MainBundle.BundleUrl; using (var mi = new NSMetadataItem (url)) { Assert.That (mi.DisplayName.ToString (), Is.EqualTo ("apitest"), "DisplayName"); - Assert.NotNull (mi.FileSystemContentChangeDate, "FileSystemContentChangeDate"); - Assert.NotNull (mi.FileSystemCreationDate, "FileSystemCreationDate"); + Assert.That (mi.FileSystemContentChangeDate, Is.Not.Null, "FileSystemContentChangeDate"); + Assert.That (mi.FileSystemCreationDate, Is.Not.Null, "FileSystemCreationDate"); Assert.That (mi.FileSystemName.ToString (), Is.EqualTo ("apitest.app"), "FileSystemName"); Assert.That (mi.FileSystemSize.UInt64Value, Is.GreaterThan (0), "FileSystemSize"); - Assert.False (mi.IsUbiquitous, "IsUbiquitous"); + Assert.That (mi.IsUbiquitous, Is.False, "IsUbiquitous"); Assert.That (mi.Path.ToString (), Does.EndWith ("/apitest.app"), "Path"); - Assert.False (mi.UbiquitousItemHasUnresolvedConflicts, "UbiquitousItemHasUnresolvedConflicts"); - Assert.False (mi.UbiquitousItemIsDownloading, "UbiquitousItemIsDownloading"); - Assert.False (mi.UbiquitousItemIsUploaded, "UbiquitousItemIsUploaded"); - Assert.False (mi.UbiquitousItemIsUploading, "UbiquitousItemIsUploading"); + Assert.That (mi.UbiquitousItemHasUnresolvedConflicts, Is.False, "UbiquitousItemHasUnresolvedConflicts"); + Assert.That (mi.UbiquitousItemIsDownloading, Is.False, "UbiquitousItemIsDownloading"); + Assert.That (mi.UbiquitousItemIsUploaded, Is.False, "UbiquitousItemIsUploaded"); + Assert.That (mi.UbiquitousItemIsUploading, Is.False, "UbiquitousItemIsUploading"); Assert.That (mi.UbiquitousItemPercentDownloaded, Is.EqualTo (0), "UbiquitousItemPercentDownloaded"); Assert.That (mi.UbiquitousItemPercentUploaded, Is.EqualTo (0), "UbiquitousItemPercentUploaded"); - Assert.Null (mi.Url, "Url"); + Assert.That (mi.Url, Is.Null, "Url"); Assert.That (mi.ContentType.ToString (), Is.EqualTo ("com.apple.application-bundle"), "ContentType"); Assert.That (mi.ContentTypeTree.Length, Is.GreaterThan (1), "ContentTypeTree"); Assert.That (mi.UbiquitousItemDownloadingStatus, Is.EqualTo (NSItemDownloadingStatus.Unknown), "UbiquitousItemDownloadingStatus"); - Assert.Null (mi.UbiquitousItemDownloadingError, "UbiquitousItemDownloadingError"); - Assert.Null (mi.UbiquitousItemUploadingError, "UbiquitousItemUploadingError"); - Assert.Null (mi.UbiquitousItemContainerDisplayName, "UbiquitousItemContainerDisplayName"); - Assert.Null (mi.UbiquitousItemUrlInLocalContainer, "UbiquitousItemUrlInLocalContainer"); + Assert.That (mi.UbiquitousItemDownloadingError, Is.Null, "UbiquitousItemDownloadingError"); + Assert.That (mi.UbiquitousItemUploadingError, Is.Null, "UbiquitousItemUploadingError"); + Assert.That (mi.UbiquitousItemContainerDisplayName, Is.Null, "UbiquitousItemContainerDisplayName"); + Assert.That (mi.UbiquitousItemUrlInLocalContainer, Is.Null, "UbiquitousItemUrlInLocalContainer"); // 10.10 if (TestRuntime.CheckXcodeVersion (6, 0)) { - Assert.False (mi.UbiquitousItemDownloadRequested, "UbiquitousItemDownloadRequested"); - Assert.False (mi.UbiquitousItemIsExternalDocument, "UbiquitousItemIsExternalDocument"); + Assert.That (mi.UbiquitousItemDownloadRequested, Is.False, "UbiquitousItemDownloadRequested"); + Assert.That (mi.UbiquitousItemIsExternalDocument, Is.False, "UbiquitousItemIsExternalDocument"); } } } diff --git a/tests/monotouch-test/Foundation/NSMutableArray1Test.cs b/tests/monotouch-test/Foundation/NSMutableArray1Test.cs index 81baaa391653..c5189f2b0944 100644 --- a/tests/monotouch-test/Foundation/NSMutableArray1Test.cs +++ b/tests/monotouch-test/Foundation/NSMutableArray1Test.cs @@ -10,7 +10,7 @@ public class NSMutableArray1Test { public void Ctor () { using (var arr = new NSMutableArray ()) { - Assert.AreEqual ((nuint) 0, arr.Count, "Count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "Count"); } } @@ -18,7 +18,7 @@ public void Ctor () public void Ctor_Capacity () { using (var arr = new NSMutableArray (1)) { - Assert.AreEqual ((nuint) 0, arr.Count, "Count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "Count"); } } @@ -29,8 +29,8 @@ public void ContainsTest () var v2 = (NSString) "value 2"; using (var arr = new NSMutableArray (v, v)) { Assert.Throws (() => arr.Contains (null), "Contains ANE"); - Assert.IsTrue (arr.Contains (v), "Contains 1"); - Assert.IsFalse (arr.Contains (v2), "Contains 2"); + Assert.That (arr.Contains (v), Is.True, "Contains 1"); + Assert.That (arr.Contains (v2), Is.False, "Contains 2"); } } @@ -42,8 +42,8 @@ public void IndexOfTest () using (var arr = new NSMutableArray (v1)) { Assert.Throws (() => arr.IndexOf (null), "IndexOf ANE"); - Assert.AreEqual ((nuint) 0, arr.IndexOf (v1), "IndexOf 1"); - Assert.AreEqual ((nuint) nint.MaxValue, arr.IndexOf (v2), "IndxOf 2"); // [NSArray indexOfObject:] returns NSNotFound = NSIntegerMax when object isn't found in the array + Assert.That (arr.IndexOf (v1), Is.EqualTo ((nuint) 0), "IndexOf 1"); + Assert.That (arr.IndexOf (v2), Is.EqualTo ((nuint) nint.MaxValue), "IndxOf 2"); // [NSArray indexOfObject:] returns NSNotFound = NSIntegerMax when object isn't found in the array } } @@ -54,11 +54,11 @@ public void AddTest () var v2 = (NSString) "2"; using (var arr = new NSMutableArray (v1)) { - Assert.AreEqual ((nuint) 1, arr.Count, "Count 1"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 1), "Count 1"); Assert.Throws (() => arr.Add (null), "Add ANE"); arr.Add (v2); - Assert.AreEqual ((nuint) 2, arr.Count, "Count 2"); - Assert.AreSame (v2, arr [1], "idx[1]"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "Count 2"); + Assert.That (arr [1], Is.SameAs (v2), "idx[1]"); } } @@ -70,15 +70,15 @@ public void InsertTest () var v3 = (NSString) "3"; using (var arr = new NSMutableArray (v1, v3)) { - Assert.AreEqual ((nuint) 2, arr.Count, "Insert 1"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "Insert 1"); Assert.Throws (() => arr.Insert (null, 0), "Insert ANE"); Assert.Throws (() => arr.Insert (v2, -1), "Insert AOORE 1"); Assert.Throws (() => arr.Insert (v2, 3), "Insert AOORE 2"); arr.Insert (v2, 1); - Assert.AreEqual ((nuint) 3, arr.Count, "Insert 2"); - Assert.AreSame (v1, arr [0], "[0]"); - Assert.AreSame (v2, arr [1], "[1]"); - Assert.AreSame (v3, arr [2], "[2]"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 3), "Insert 2"); + Assert.That (arr [0], Is.SameAs (v1), "[0]"); + Assert.That (arr [1], Is.SameAs (v2), "[1]"); + Assert.That (arr [2], Is.SameAs (v3), "[2]"); } using (var arr = new NSMutableArray ()) { @@ -94,16 +94,16 @@ public void ReplaceObjectTest () var v3 = (NSString) "3"; using (var arr = new NSMutableArray (v1, v3)) { - Assert.AreEqual ((nuint) 2, arr.Count, "ReplaceObject 1"); - Assert.AreSame (v1, arr [0], "a [0]"); - Assert.AreSame (v3, arr [1], "a [1]"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "ReplaceObject 1"); + Assert.That (arr [0], Is.SameAs (v1), "a [0]"); + Assert.That (arr [1], Is.SameAs (v3), "a [1]"); Assert.Throws (() => arr.ReplaceObject (0, null), "Insert ANE"); Assert.Throws (() => arr.ReplaceObject (-1, v2), "Insert AOORE 1"); Assert.Throws (() => arr.ReplaceObject (3, v2), "Insert AOORE 2"); arr.ReplaceObject (1, v2); - Assert.AreEqual ((nuint) 2, arr.Count, "ReplaceObject 2"); - Assert.AreSame (v1, arr [0], "b [0]"); - Assert.AreSame (v2, arr [1], "b [1]"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "ReplaceObject 2"); + Assert.That (arr [0], Is.SameAs (v1), "b [0]"); + Assert.That (arr [1], Is.SameAs (v2), "b [1]"); } } @@ -116,18 +116,18 @@ public void AddObjectsTest () using (var arr = new NSMutableArray ()) { Assert.Throws (() => arr.AddObjects ((NSString []) null), "AddObjects ANE 1"); - Assert.AreEqual ((nuint) 0, arr.Count, "Count 1"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "Count 1"); Assert.Throws (() => arr.AddObjects (new NSString [] { null }), "AddObjects ANE 2"); - Assert.AreEqual ((nuint) 0, arr.Count, "Count 2"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "Count 2"); Assert.Throws (() => arr.AddObjects (new NSString [] { v1, null, v3 }), "AddObjects ANE 3"); - Assert.AreEqual ((nuint) 0, arr.Count, "Count 3"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "Count 3"); arr.AddObjects (v1, v2); - Assert.AreEqual ((nuint) 2, arr.Count, "AddObjects 1"); - Assert.AreSame (v1, arr [0], "a [0]"); - Assert.AreSame (v2, arr [1], "a [1]"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "AddObjects 1"); + Assert.That (arr [0], Is.SameAs (v1), "a [0]"); + Assert.That (arr [1], Is.SameAs (v2), "a [1]"); } } @@ -145,24 +145,24 @@ public void InsertObjectsTest () iset.Add (2); Assert.Throws (() => arr.InsertObjects ((NSString []) null, iset), "InsertObjects ANE 1"); - Assert.AreEqual ((nuint) 2, arr.Count, "Count 1"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "Count 1"); Assert.Throws (() => arr.InsertObjects (new NSString [] { null, null }, iset), "InsertObjects ANE 2"); - Assert.AreEqual ((nuint) 2, arr.Count, "Count 2"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "Count 2"); Assert.Throws (() => arr.InsertObjects (new NSString [] { v1, null }, iset), "InsertObjects ANE 3"); - Assert.AreEqual ((nuint) 2, arr.Count, "Count 3"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "Count 3"); Assert.Throws (() => arr.InsertObjects (new NSString [] { v1 }, null), "InsertObjects ANE 4"); - Assert.AreEqual ((nuint) 2, arr.Count, "Count 4"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "Count 4"); arr.InsertObjects (new NSString [] { v3, v4 }, iset); - Assert.AreEqual ((nuint) 4, arr.Count, "InsertObjects 1"); - Assert.AreSame (v1, arr [0], "a [0]"); - Assert.AreSame (v3, arr [1], "a [1]"); - Assert.AreSame (v4, arr [2], "a [2]"); - Assert.AreSame (v2, arr [3], "a [3]"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 4), "InsertObjects 1"); + Assert.That (arr [0], Is.SameAs (v1), "a [0]"); + Assert.That (arr [1], Is.SameAs (v3), "a [1]"); + Assert.That (arr [2], Is.SameAs (v4), "a [2]"); + Assert.That (arr [3], Is.SameAs (v2), "a [3]"); iset.Clear (); iset.Add (9); @@ -179,9 +179,9 @@ public void IndexerTest () using (var arr = new NSMutableArray (v1, v2)) { arr [1] = v3; - Assert.AreEqual ((nuint) 2, arr.Count, "a 1"); - Assert.AreSame (v1, arr [0], "a [0]"); - Assert.AreSame (v3, arr [1], "a [1]"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "a 1"); + Assert.That (arr [0], Is.SameAs (v1), "a [0]"); + Assert.That (arr [1], Is.SameAs (v3), "a [1]"); Assert.Throws (() => arr [0] = null, "ANE 1"); Assert.Throws (() => arr [2] = v3, "IOORE 1"); @@ -195,16 +195,16 @@ public void IEnumerableTest () using (var arr = new NSMutableArray ()) { for (int i = 0; i < C; i++) arr.Add ((NSString) i.ToString ()); - Assert.AreEqual ((nuint) C, arr.Count, "Count 1"); + Assert.That (arr.Count, Is.EqualTo ((nuint) C), "Count 1"); var lst = new List (); foreach (NSString a in (IEnumerable) arr) { - Assert.IsNotNull (a, "null item iterator"); - Assert.IsFalse (lst.Contains (a), "duplicated item iterator"); - Assert.AreEqual (lst.Count.ToString (), (string) a, "#" + lst.Count.ToString ()); + Assert.That (a, Is.Not.Null, "null item iterator"); + Assert.That (lst.Contains (a), Is.False, "duplicated item iterator"); + Assert.That ((string) a, Is.EqualTo (lst.Count.ToString ()), "#" + lst.Count.ToString ()); lst.Add (a); } - Assert.AreEqual (C, lst.Count, "iterator count"); + Assert.That (lst.Count, Is.EqualTo (C), "iterator count"); } } @@ -215,16 +215,16 @@ public void IEnumerable1Test () using (var arr = new NSMutableArray ()) { for (int i = 0; i < C; i++) arr.Add ((NSString) i.ToString ()); - Assert.AreEqual ((nuint) C, arr.Count, "Count 1"); + Assert.That (arr.Count, Is.EqualTo ((nuint) C), "Count 1"); var lst = new List (); foreach (var a in (IEnumerable) arr) { - Assert.IsNotNull (a, "null item iterator"); - Assert.IsFalse (lst.Contains (a), "duplicated item iterator"); - Assert.AreEqual (lst.Count.ToString (), (string) a, "#" + lst.Count.ToString ()); + Assert.That (a, Is.Not.Null, "null item iterator"); + Assert.That (lst.Contains (a), Is.False, "duplicated item iterator"); + Assert.That ((string) a, Is.EqualTo (lst.Count.ToString ()), "#" + lst.Count.ToString ()); lst.Add (a); } - Assert.AreEqual (C, lst.Count, "iterator count"); + Assert.That (lst.Count, Is.EqualTo (C), "iterator count"); } } diff --git a/tests/monotouch-test/Foundation/NSMutableDictionary2Test.cs b/tests/monotouch-test/Foundation/NSMutableDictionary2Test.cs index bd1cba17986c..1419256c3409 100644 --- a/tests/monotouch-test/Foundation/NSMutableDictionary2Test.cs +++ b/tests/monotouch-test/Foundation/NSMutableDictionary2Test.cs @@ -13,7 +13,7 @@ public class NSMutableDictionary2Test { public void Ctor () { var dict = new NSMutableDictionary (); - Assert.AreEqual ((nuint) 0, dict.Count, "Count"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 0), "Count"); } [Test] @@ -22,8 +22,8 @@ public void Ctor_NSDictionary () var other = new NSDictionary ((NSString) "key", (NSString) "value"); var j = new NSMutableDictionary (other); - Assert.AreEqual (j.Count, (nuint) 1, "count"); - Assert.AreEqual ((string) (NSString) (j [(NSString) "key"]), "value", "key lookup"); + Assert.That (j.Count, Is.EqualTo ((nuint) 1), "count"); + Assert.That ((string) (NSString) (j [(NSString) "key"]), Is.EqualTo ("value"), "key lookup"); } [Test] @@ -33,8 +33,8 @@ public void Ctor_NSMutableDictionary () other.Add ((NSString) "key", (NSString) "value"); var j = new NSMutableDictionary (other); - Assert.AreEqual (j.Count, (nuint) 1, "count"); - Assert.AreEqual ((string) (NSString) (j [(NSString) "key"]), "value", "key lookup"); + Assert.That (j.Count, Is.EqualTo ((nuint) 1), "count"); + Assert.That ((string) (NSString) (j [(NSString) "key"]), Is.EqualTo ("value"), "key lookup"); } [Test] @@ -56,9 +56,9 @@ public void FromObjectsAndKeysGenericTest () }; var dict = NSMutableDictionary.FromObjectsAndKeys (values, keys, values.Length); - Assert.AreEqual (dict.Count, (nuint) 5, "count"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 5), "count"); for (int i = 0; i < values.Length; i++) - Assert.AreEqual (dict [keys [i]], values [i], $"key lookup, Iteration: {i}"); + Assert.That (values [i], Is.EqualTo (dict [keys [i]]), $"key lookup, Iteration: {i}"); } [Test] @@ -66,10 +66,10 @@ public void Ctor_WithNullValue () { var key = (NSString) "key"; using (var dict = new NSMutableDictionary (key, null)) { - Assert.AreEqual ((nuint) 1, dict.Count, "count"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 1), "count"); var baseDict = (NSDictionary) dict; var rawValue = baseDict.ObjectForKey (key); - Assert.IsInstanceOf (rawValue, "Null value should be NSNull"); + Assert.That (rawValue, Is.InstanceOf (), "Null value should be NSNull"); } } @@ -80,12 +80,12 @@ public void FromObjectsAndKeys_Generic_WithNull () var values = new NSString? [] { (NSString) "value1", null }; using (var dict = NSMutableDictionary.FromObjectsAndKeys (values, keys)) { - Assert.IsNotNull (dict, "Dictionary should not be null"); - Assert.AreEqual ((nuint) 2, dict!.Count, "Count"); - Assert.AreEqual ("value1", dict [keys [0]].ToString (), "First value"); + Assert.That (dict, Is.Not.Null, "Dictionary should not be null"); + Assert.That (dict!.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (dict [keys [0]].ToString (), Is.EqualTo ("value1"), "First value"); var baseDict = (NSDictionary) dict; var rawValue = baseDict.ObjectForKey (keys [1]); - Assert.IsInstanceOf (rawValue, "Null value should be NSNull"); + Assert.That (rawValue, Is.InstanceOf (), "Null value should be NSNull"); } } @@ -96,12 +96,12 @@ public void FromObjectsAndKeys_Generic_WithCount_WithNull () var values = new NSString? [] { (NSString) "value1", null, (NSString) "value3" }; using (var dict = NSMutableDictionary.FromObjectsAndKeys (values, keys, 2)) { - Assert.IsNotNull (dict, "Dictionary should not be null"); - Assert.AreEqual ((nuint) 2, dict!.Count, "Count"); - Assert.AreEqual ("value1", dict [keys [0]].ToString (), "First value"); + Assert.That (dict, Is.Not.Null, "Dictionary should not be null"); + Assert.That (dict!.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (dict [keys [0]].ToString (), Is.EqualTo ("value1"), "First value"); var baseDict = (NSDictionary) dict; var rawValue = baseDict.ObjectForKey (keys [1]); - Assert.IsInstanceOf (rawValue, "Null value should be NSNull"); + Assert.That (rawValue, Is.InstanceOf (), "Null value should be NSNull"); } } @@ -112,10 +112,10 @@ public void FromObjectsAndKeys_Object_WithCount () var objs = new object [] { "value1", "value2", "value3" }; using (var dict = NSMutableDictionary.FromObjectsAndKeys (objs, keys, 2)) { - Assert.IsNotNull (dict, "Dictionary should not be null"); - Assert.AreEqual ((nuint) 2, dict!.Count, "Count"); - Assert.AreEqual ("value1", dict [(NSString) "key1"].ToString (), "First value"); - Assert.AreEqual ("value2", dict [(NSString) "key2"].ToString (), "Second value"); + Assert.That (dict, Is.Not.Null, "Dictionary should not be null"); + Assert.That (dict!.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (dict [(NSString) "key1"].ToString (), Is.EqualTo ("value1"), "First value"); + Assert.That (dict [(NSString) "key2"].ToString (), Is.EqualTo ("value2"), "Second value"); } } @@ -126,12 +126,12 @@ public void FromObjectsAndKeys_NSObject_WithCount_WithNull () var objs = new NSObject? [] { new NSString ("value1"), null, new NSString ("value3") }; using (var dict = NSMutableDictionary.FromObjectsAndKeys (objs, keys, 2)) { - Assert.IsNotNull (dict, "Dictionary should not be null"); - Assert.AreEqual ((nuint) 2, dict!.Count, "Count"); - Assert.AreEqual ("value1", dict [(NSString) keys [0]].ToString (), "First value"); + Assert.That (dict, Is.Not.Null, "Dictionary should not be null"); + Assert.That (dict!.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (dict [(NSString) keys [0]].ToString (), Is.EqualTo ("value1"), "First value"); var baseDict = (NSDictionary) dict; var rawValue = baseDict.ObjectForKey (keys [1]); - Assert.IsInstanceOf (rawValue, "Null value should be NSNull"); + Assert.That (rawValue, Is.InstanceOf (), "Null value should be NSNull"); } } @@ -142,10 +142,10 @@ public void FromObjectsAndKeys_NSObject_WithCount () var objs = new NSObject [] { new NSString ("value1"), new NSString ("value2"), new NSString ("value3") }; using (var dict = NSMutableDictionary.FromObjectsAndKeys (objs, keys, 2)) { - Assert.IsNotNull (dict, "Dictionary should not be null"); - Assert.AreEqual ((nuint) 2, dict!.Count, "Count"); - Assert.AreEqual ("value1", dict [(NSString) keys [0]].ToString (), "First value"); - Assert.AreEqual ("value2", dict [(NSString) keys [1]].ToString (), "Second value"); + Assert.That (dict, Is.Not.Null, "Dictionary should not be null"); + Assert.That (dict!.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (dict [(NSString) keys [0]].ToString (), Is.EqualTo ("value1"), "First value"); + Assert.That (dict [(NSString) keys [1]].ToString (), Is.EqualTo ("value2"), "Second value"); } } @@ -156,8 +156,8 @@ public void FromObjectsAndKeys_Generic_WithCountZero () var values = new NSString [] { (NSString) "value1", (NSString) "value2" }; using (var dict = NSMutableDictionary.FromObjectsAndKeys (values, keys, 0)) { - Assert.IsNotNull (dict, "Dictionary should not be null"); - Assert.AreEqual ((nuint) 0, dict!.Count, "Count should be 0"); + Assert.That (dict, Is.Not.Null, "Dictionary should not be null"); + Assert.That (dict!.Count, Is.EqualTo ((nuint) 0), "Count should be 0"); } } @@ -169,10 +169,10 @@ public void FromObjectsAndKeys_DifferentArrayLengths_WithCount () // Should work fine since we only use first 2 items from each array using (var dict = NSMutableDictionary.FromObjectsAndKeys (values, keys, 2)) { - Assert.IsNotNull (dict, "Dictionary should not be null"); - Assert.AreEqual ((nuint) 2, dict!.Count, "Count"); - Assert.AreEqual ("value1", dict [keys [0]].ToString (), "First value"); - Assert.AreEqual ("value2", dict [keys [1]].ToString (), "Second value"); + Assert.That (dict, Is.Not.Null, "Dictionary should not be null"); + Assert.That (dict!.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (dict [keys [0]].ToString (), Is.EqualTo ("value1"), "First value"); + Assert.That (dict [keys [1]].ToString (), Is.EqualTo ("value2"), "Second value"); } } @@ -225,13 +225,13 @@ public void KeyValue_Autorelease () v2 = v.RetainCount; Assert.That (v2, Is.GreaterThan (v1), "Value.RetainCount-b"); - Assert.NotNull (d.Keys, "Keys"); + Assert.That (d.Keys, Is.Not.Null, "Keys"); // accessing `allKeys` should *NOT* change the retainCount // that would happen without an [Autorelease] and can lead to memory exhaustion // https://bugzilla.xamarin.com/show_bug.cgi?id=7723 Assert.That (k.RetainCount, Is.EqualTo (k2), "Key.RetainCount-c"); - Assert.NotNull (d.Values, "Values"); + Assert.That (d.Values, Is.Not.Null, "Values"); Assert.That (v.RetainCount, Is.EqualTo (v2), "Value.RetainCount-c"); } Assert.That (k.RetainCount, Is.LessThan (k2), "Key.RetainCount-d"); @@ -262,7 +262,7 @@ public void XForY_Autorelease () Assert.That (x [0], Is.SameAs (k), "KeysForObject"); var y = d.ObjectForKey (k); - Assert.NotNull (y, "ObjectForKey"); + Assert.That (y, Is.Not.Null, "ObjectForKey"); using (var a = new NSMutableArray ()) { a.Add (k); @@ -286,19 +286,19 @@ public void Copy () using (var d = new NSMutableDictionary (k, v)) { // NSObject.Copy works because NSDictionary conforms to NSCopying using (var copy1 = (NSDictionary) d.Copy ()) { - Assert.AreNotSame (d, copy1, "1"); + Assert.That (copy1, Is.Not.SameAs (d), "1"); Assert.That (copy1, Is.Not.TypeOf (), "NSDictionary-1"); Assert.That (copy1.Count, Is.EqualTo ((nuint) 1), "Count-1"); } using (var copy2 = (NSDictionary) d.Copy (null)) { - Assert.AreNotSame (d, copy2, "2"); + Assert.That (copy2, Is.Not.SameAs (d), "2"); Assert.That (copy2, Is.Not.TypeOf (), "NSDictionary-2"); Assert.That (copy2.Count, Is.EqualTo ((nuint) 1), "Count-2"); } using (var copy3 = (NSDictionary) d.Copy (NSZone.Default)) { - Assert.AreNotSame (d, copy3, "3"); + Assert.That (copy3, Is.Not.SameAs (d), "3"); Assert.That (copy3, Is.Not.TypeOf (), "NSDictionary-3"); Assert.That (copy3.Count, Is.EqualTo ((nuint) 1), "Count-3"); } @@ -337,8 +337,8 @@ public void ObjectForKeyTest () var dict = new NSMutableDictionary (key, value); Assert.Throws (() => dict.ObjectForKey ((NSString) null), "ANE"); - Assert.AreSame (value, dict.ObjectForKey (key), "right"); - Assert.IsNull (dict.ObjectForKey ((NSString) "wrong key"), "wrong"); + Assert.That (dict.ObjectForKey (key), Is.SameAs (value), "right"); + Assert.That (dict.ObjectForKey ((NSString) "wrong key"), Is.Null, "wrong"); } [Test] @@ -349,8 +349,8 @@ public void KeysTest () var dict = new NSMutableDictionary (key, value); var keys = dict.Keys; - Assert.AreEqual (1, keys.Length, "Length"); - Assert.AreSame (key, keys [0], "1"); + Assert.That (keys.Length, Is.EqualTo (1), "Length"); + Assert.That (keys [0], Is.SameAs (key), "1"); } [Test] @@ -369,14 +369,14 @@ public void KeysForObjectTest () ); var rv = dict.KeysForObject (value1); - Assert.AreEqual (2, rv.Length, "v1"); + Assert.That (rv.Length, Is.EqualTo (2), "v1"); rv = dict.KeysForObject (value2); - Assert.AreEqual (1, rv.Length, "v2"); - Assert.AreSame (key3, rv [0], "v2 key"); + Assert.That (rv.Length, Is.EqualTo (1), "v2"); + Assert.That (rv [0], Is.SameAs (key3), "v2 key"); rv = dict.KeysForObject (value3); - Assert.AreEqual (0, rv.Length, "v3"); + Assert.That (rv.Length, Is.EqualTo (0), "v3"); Assert.Throws (() => dict.KeysForObject (null), "ANE"); } @@ -389,8 +389,8 @@ public void ValuesTest () var dict = new NSMutableDictionary (key, value); var keys = dict.Values; - Assert.AreEqual (1, dict.Values.Length, "Length"); - Assert.AreSame (value, dict [key], "1"); + Assert.That (dict.Values.Length, Is.EqualTo (1), "Length"); + Assert.That (dict [key], Is.SameAs (value), "1"); } [Test] @@ -410,12 +410,12 @@ public void ObjectsForKeysTest () ); var rv = dict.ObjectsForKeys (new NSString [] { key1, key4 }, value3); - Assert.AreEqual (2, rv.Length, "a"); - Assert.AreSame (value1, rv [0], "a 0"); - Assert.AreSame (value3, rv [1], "a 1"); + Assert.That (rv.Length, Is.EqualTo (2), "a"); + Assert.That (rv [0], Is.SameAs (value1), "a 0"); + Assert.That (rv [1], Is.SameAs (value3), "a 1"); rv = dict.ObjectsForKeys (new NSString [] { }, value3); - Assert.AreEqual (0, rv.Length, "b length"); + Assert.That (rv.Length, Is.EqualTo (0), "b length"); Assert.Throws (() => dict.ObjectsForKeys ((NSString []) null, value3), "c"); Assert.Throws (() => dict.ObjectsForKeys (new NSString [] { }, null), "d"); @@ -436,8 +436,8 @@ public void ContainsKeyTest () new NSDate [] { value1, value1 } ); - Assert.True (dict.ContainsKey (key1), "a"); - Assert.False (dict.ContainsKey (key3), "b"); + Assert.That (dict.ContainsKey (key1), Is.True, "a"); + Assert.That (dict.ContainsKey (key3), Is.False, "b"); Assert.Throws (() => dict.ContainsKey ((NSString) null), "ANE"); } @@ -458,11 +458,11 @@ public void TryGetValueTest () NSDate value; - Assert.True (dict.TryGetValue (key1, out value), "a"); - Assert.AreSame (value1, value, "a same"); + Assert.That (dict.TryGetValue (key1, out value), Is.True, "a"); + Assert.That (value, Is.SameAs (value1), "a same"); - Assert.False (dict.TryGetValue (key3, out value), "b"); - Assert.IsNull (value, "b null"); + Assert.That (dict.TryGetValue (key3, out value), Is.False, "b"); + Assert.That (value, Is.Null, "b null"); } [Test] @@ -480,8 +480,8 @@ public void IndexerTest () new NSDate [] { value1, value1 } ); - Assert.AreSame (value1, dict [key1], "a"); - Assert.IsNull (dict [key3], "b"); + Assert.That (dict [key1], Is.SameAs (value1), "a"); + Assert.That (dict [key3], Is.Null, "b"); Assert.Throws (() => GC.KeepAlive (dict [(NSString) null]), "c"); } @@ -495,11 +495,11 @@ public void IndexerGetterKeyNotFoundBehaviorTest () var dict = new NSMutableDictionary (key1, value1); // Accessing via the indexer property should return null - Assert.IsNull (dict [keyMissing], "missing key"); + Assert.That (dict [keyMissing], Is.Null, "missing key"); // Accessing via IDictionary interface should return null too IDictionary idict = dict; - Assert.IsNull (idict [keyMissing], "missing key via interface"); + Assert.That (idict [keyMissing], Is.Null, "missing key via interface"); } [Test] @@ -517,22 +517,22 @@ public void MissingKeyAccessTest () ); // ObjectForKey should return null for missing keys - Assert.IsNull (dict.ObjectForKey (keyMissing), "ObjectForKey missing"); + Assert.That (dict.ObjectForKey (keyMissing), Is.Null, "ObjectForKey missing"); // TryGetValue should return false for missing keys NSDate value; - Assert.IsFalse (dict.TryGetValue (keyMissing, out value), "TryGetValue missing"); - Assert.IsNull (value, "TryGetValue out value"); + Assert.That (dict.TryGetValue (keyMissing, out value), Is.False, "TryGetValue missing"); + Assert.That (value, Is.Null, "TryGetValue out value"); // ContainsKey should return false for missing keys - Assert.IsFalse (dict.ContainsKey (keyMissing), "ContainsKey missing"); + Assert.That (dict.ContainsKey (keyMissing), Is.False, "ContainsKey missing"); // Indexer getter should return null - Assert.IsNull (dict [keyMissing], "Indexer missing"); + Assert.That (dict [keyMissing], Is.Null, "Indexer missing"); // IDictionary indexer should also return null IDictionary idict = dict; - Assert.IsNull (idict [keyMissing], "IDictionary indexer missing"); + Assert.That (idict [keyMissing], Is.Null, "IDictionary indexer missing"); } [Test] @@ -542,17 +542,17 @@ public void EmptyDictionaryMissingKeyTest () var keyMissing = new NSString ("missing"); // All access methods should handle missing keys in empty dictionary - Assert.IsNull (dict.ObjectForKey (keyMissing), "ObjectForKey"); - Assert.IsFalse (dict.ContainsKey (keyMissing), "ContainsKey"); + Assert.That (dict.ObjectForKey (keyMissing), Is.Null, "ObjectForKey"); + Assert.That (dict.ContainsKey (keyMissing), Is.False, "ContainsKey"); NSDate value; - Assert.IsFalse (dict.TryGetValue (keyMissing, out value), "TryGetValue"); - Assert.IsNull (value, "TryGetValue out"); + Assert.That (dict.TryGetValue (keyMissing, out value), Is.False, "TryGetValue"); + Assert.That (value, Is.Null, "TryGetValue out"); - Assert.IsNull (dict [keyMissing], "Indexer"); + Assert.That (dict [keyMissing], Is.Null, "Indexer"); IDictionary idict = dict; - Assert.IsNull (idict [keyMissing], "IDictionary indexer"); + Assert.That (idict [keyMissing], Is.Null, "IDictionary indexer"); } [Test] @@ -573,17 +573,17 @@ public void ObjectsForKeysMissingKeysTest () // Request mix of existing and missing keys - marker should replace missing values var result = dict.ObjectsForKeys (new NSString [] { key1, keyMissing1, key2, keyMissing2 }, marker); - Assert.AreEqual (4, result.Length, "Length"); - Assert.AreSame (value1, result [0], "0 - existing"); - Assert.AreSame (marker, result [1], "1 - missing"); - Assert.AreSame (value2, result [2], "2 - existing"); - Assert.AreSame (marker, result [3], "3 - missing"); + Assert.That (result.Length, Is.EqualTo (4), "Length"); + Assert.That (result [0], Is.SameAs (value1), "0 - existing"); + Assert.That (result [1], Is.SameAs (marker), "1 - missing"); + Assert.That (result [2], Is.SameAs (value2), "2 - existing"); + Assert.That (result [3], Is.SameAs (marker), "3 - missing"); // Request all missing keys result = dict.ObjectsForKeys (new NSString [] { keyMissing1, keyMissing2 }, marker); - Assert.AreEqual (2, result.Length, "All missing length"); - Assert.AreSame (marker, result [0], "All missing 0"); - Assert.AreSame (marker, result [1], "All missing 1"); + Assert.That (result.Length, Is.EqualTo (2), "All missing length"); + Assert.That (result [0], Is.SameAs (marker), "All missing 0"); + Assert.That (result [1], Is.SameAs (marker), "All missing 1"); } [Test] @@ -607,24 +607,24 @@ public void IDictionary2Test () Assert.Throws (() => dict.Add (new KeyValuePair (null, value1)), "Add ANE 1"); Assert.Throws (() => dict.Add (new KeyValuePair (key1, null)), "Add ANE 2"); dict.Add (new KeyValuePair (key3, value3)); - Assert.AreSame (value3, dictobj [key3], "Add 1"); - Assert.AreEqual (3, dict.Count, "Add Count"); + Assert.That (dictobj [key3], Is.SameAs (value3), "Add 1"); + Assert.That (dict.Count, Is.EqualTo (3), "Add Count"); dictobj.Remove (key3); // restore state. // Clear dict.Clear (); - Assert.AreEqual (0, dict.Count, "Clear Count"); + Assert.That (dict.Count, Is.EqualTo (0), "Clear Count"); dictobj.Add (key1, value1); // restore state dictobj.Add (key2, value1); // restore state // Contains - Assert.IsTrue (dict.Contains (new KeyValuePair (key1, value1)), "Contains 1"); // both key and value matches - Assert.IsFalse (dict.Contains (new KeyValuePair (key1, value2)), "Contains 2"); // found key, wrong value - Assert.IsFalse (dict.Contains (new KeyValuePair (key3, value2)), "Contains 3"); // wrong key + Assert.That (dict.Contains (new KeyValuePair (key1, value1)), Is.True, "Contains 1"); // both key and value matches + Assert.That (dict.Contains (new KeyValuePair (key1, value2)), Is.False, "Contains 2"); // found key, wrong value + Assert.That (dict.Contains (new KeyValuePair (key3, value2)), Is.False, "Contains 3"); // wrong key // ContainsKey - Assert.IsTrue (dict.ContainsKey (key1), "ContainsKey 1"); - Assert.IsFalse (dict.ContainsKey (key3), "ContainsKey 2"); + Assert.That (dict.ContainsKey (key1), Is.True, "ContainsKey 1"); + Assert.That (dict.ContainsKey (key3), Is.False, "ContainsKey 2"); // CopyTo var kvp_array = new KeyValuePair [1]; @@ -638,54 +638,54 @@ public void IDictionary2Test () Assert.Throws (() => dict.CopyTo (kvp_array, 1), "CopyTo AE 4"); dict.CopyTo (kvp_array, 0); Assert.That (key1, Is.SameAs (kvp_array [0].Key).Or.SameAs (kvp_array [1].Key), "CopyTo K1"); - Assert.AreSame (value1, kvp_array [0].Value, "CopyTo V1"); + Assert.That (kvp_array [0].Value, Is.SameAs (value1), "CopyTo V1"); Assert.That (key2, Is.SameAs (kvp_array [0].Key).Or.SameAs (kvp_array [1].Key), "CopyTo K2"); - Assert.AreSame (value1, kvp_array [1].Value, "CopyTo V2"); + Assert.That (kvp_array [1].Value, Is.SameAs (value1), "CopyTo V2"); // Count - Assert.AreEqual (2, dict.Count, "Count"); + Assert.That (dict.Count, Is.EqualTo (2), "Count"); // GetEnumerator var enumerated = Enumerable.ToArray (dict); - Assert.AreEqual (2, enumerated.Length, "Enumerator Count"); + Assert.That (enumerated.Length, Is.EqualTo (2), "Enumerator Count"); // IsReadOnly - Assert.IsFalse (dict.IsReadOnly, "IsReadOnly"); + Assert.That (dict.IsReadOnly, Is.False, "IsReadOnly"); // Keys - Assert.AreEqual (2, dict.Keys.Count, "Keys Count"); + Assert.That (dict.Keys.Count, Is.EqualTo (2), "Keys Count"); // Remove Assert.Throws (() => dict.Remove (new KeyValuePair (null, value3)), "Remove ANE 1"); Assert.Throws (() => dict.Remove (new KeyValuePair (key3, null)), "Remove ANE 2"); - Assert.IsFalse (dict.Remove (new KeyValuePair (key3, value3)), "Remove 1"); // inexistent key - Assert.AreEqual (2, dict.Count, "Remove 1 Count"); + Assert.That (dict.Remove (new KeyValuePair (key3, value3)), Is.False, "Remove 1"); // inexistent key + Assert.That (dict.Count, Is.EqualTo (2), "Remove 1 Count"); - Assert.IsFalse (dict.Remove (new KeyValuePair (key1, value2)), "Remove 2"); // existing key, wrong value - Assert.AreEqual (2, dict.Count, "Remove 2 Count"); + Assert.That (dict.Remove (new KeyValuePair (key1, value2)), Is.False, "Remove 2"); // existing key, wrong value + Assert.That (dict.Count, Is.EqualTo (2), "Remove 2 Count"); - Assert.IsTrue (dict.Remove (new KeyValuePair (key1, value1)), "Remove 3"); // existing key,value pair - Assert.AreEqual (1, dict.Count, "Remove 3 Count"); + Assert.That (dict.Remove (new KeyValuePair (key1, value1)), Is.True, "Remove 3"); // existing key,value pair + Assert.That (dict.Count, Is.EqualTo (1), "Remove 3 Count"); dictobj.Add (key1, value1); // restore state // TryGetValue NSDate value; Assert.Throws (() => dict.TryGetValue (null, out value), "TryGetValue ANE"); - Assert.IsTrue (dict.TryGetValue (key1, out value), "TryGetValue K1"); - Assert.AreSame (value1, value, "TryGetValue V1"); - Assert.IsFalse (dict.TryGetValue (key3, out value), "TryGetValue K2"); + Assert.That (dict.TryGetValue (key1, out value), Is.True, "TryGetValue K1"); + Assert.That (value, Is.SameAs (value1), "TryGetValue V1"); + Assert.That (dict.TryGetValue (key3, out value), Is.False, "TryGetValue K2"); // Values - Assert.AreEqual (2, dict.Values.Count, "Values Count"); + Assert.That (dict.Values.Count, Is.EqualTo (2), "Values Count"); // Indexer - Assert.AreSame (value1, dict [key1], "this [1]"); - Assert.IsNull (dict [key3], "this [2]"); + Assert.That (dict [key1], Is.SameAs (value1), "this [1]"); + Assert.That (dict [key3], Is.Null, "this [2]"); Assert.Throws (() => GC.KeepAlive (dict [null]), "this [null]"); dict [key3] = value3; - Assert.AreEqual (3, dict.Count, "this [3] Count"); - Assert.AreSame (value3, dict [key3], "this [3] = 3"); + Assert.That (dict.Count, Is.EqualTo (3), "this [3] Count"); + Assert.That (dict [key3], Is.SameAs (value3), "this [3] = 3"); dictobj.Remove (key3); // restore state Assert.Throws (() => dict [key3] = null, "this [4] = null"); @@ -712,20 +712,20 @@ public void ICollection2Test () Assert.Throws (() => dict.Add (new KeyValuePair (null, value1)), "Add ANE 1"); Assert.Throws (() => dict.Add (new KeyValuePair (key1, null)), "Add ANE 2"); dict.Add (new KeyValuePair (key3, value3)); - Assert.AreSame (value3, dictobj [key3], "Add 1"); - Assert.AreEqual (3, dict.Count, "Add Count"); + Assert.That (dictobj [key3], Is.SameAs (value3), "Add 1"); + Assert.That (dict.Count, Is.EqualTo (3), "Add Count"); dictobj.Remove (key3); // restore state. // Clear dict.Clear (); - Assert.AreEqual (0, dict.Count, "Clear Count"); + Assert.That (dict.Count, Is.EqualTo (0), "Clear Count"); dictobj.Add (key1, value1); // restore state dictobj.Add (key2, value1); // restore state // Contains - Assert.IsTrue (dict.Contains (new KeyValuePair (key1, value1)), "Contains 1"); // both key and value matches - Assert.IsFalse (dict.Contains (new KeyValuePair (key1, value2)), "Contains 2"); // found key, wrong value - Assert.IsFalse (dict.Contains (new KeyValuePair (key3, value2)), "Contains 3"); // wrong key + Assert.That (dict.Contains (new KeyValuePair (key1, value1)), Is.True, "Contains 1"); // both key and value matches + Assert.That (dict.Contains (new KeyValuePair (key1, value2)), Is.False, "Contains 2"); // found key, wrong value + Assert.That (dict.Contains (new KeyValuePair (key3, value2)), Is.False, "Contains 3"); // wrong key // CopyTo @@ -740,31 +740,31 @@ public void ICollection2Test () Assert.Throws (() => dict.CopyTo (kvp_array, 1), "CopyTo AE 4"); dict.CopyTo (kvp_array, 0); Assert.That (key1, Is.SameAs (kvp_array [0].Key).Or.SameAs (kvp_array [1].Key), "CopyTo K1"); - Assert.AreSame (value1, kvp_array [0].Value, "CopyTo V1"); + Assert.That (kvp_array [0].Value, Is.SameAs (value1), "CopyTo V1"); Assert.That (key2, Is.SameAs (kvp_array [0].Key).Or.SameAs (kvp_array [1].Key), "CopyTo K2"); - Assert.AreSame (value1, kvp_array [1].Value, "CopyTo V2"); + Assert.That (kvp_array [1].Value, Is.SameAs (value1), "CopyTo V2"); // Count - Assert.AreEqual (2, dict.Count, "Count"); + Assert.That (dict.Count, Is.EqualTo (2), "Count"); // GetEnumerator var enumerated = Enumerable.ToArray (dict); - Assert.AreEqual (2, enumerated.Length, "Enumerator Count"); + Assert.That (enumerated.Length, Is.EqualTo (2), "Enumerator Count"); // IsReadOnly - Assert.IsFalse (dict.IsReadOnly, "IsReadOnly"); + Assert.That (dict.IsReadOnly, Is.False, "IsReadOnly"); // Remove Assert.Throws (() => dict.Remove (new KeyValuePair (null, value3)), "Remove ANE 1"); Assert.Throws (() => dict.Remove (new KeyValuePair (key3, null)), "Remove ANE 2"); - Assert.IsFalse (dict.Remove (new KeyValuePair (key3, value3)), "Remove 1"); // inexistent key - Assert.AreEqual (2, dict.Count, "Remove 1 Count"); + Assert.That (dict.Remove (new KeyValuePair (key3, value3)), Is.False, "Remove 1"); // inexistent key + Assert.That (dict.Count, Is.EqualTo (2), "Remove 1 Count"); - Assert.IsFalse (dict.Remove (new KeyValuePair (key1, value2)), "Remove 2"); // existing key, wrong value - Assert.AreEqual (2, dict.Count, "Remove 2 Count"); + Assert.That (dict.Remove (new KeyValuePair (key1, value2)), Is.False, "Remove 2"); // existing key, wrong value + Assert.That (dict.Count, Is.EqualTo (2), "Remove 2 Count"); - Assert.IsTrue (dict.Remove (new KeyValuePair (key1, value1)), "Remove 3"); // existing key,value pair - Assert.AreEqual (1, dict.Count, "Remove 3 Count"); + Assert.That (dict.Remove (new KeyValuePair (key1, value1)), Is.True, "Remove 3"); // existing key,value pair + Assert.That (dict.Count, Is.EqualTo (1), "Remove 3 Count"); dictobj.Add (key1, value1); // restore state } @@ -787,7 +787,7 @@ public void IEnumerable_KVP2Test () // GetEnumerator var enumerated = Enumerable.ToArray (dict); - Assert.AreEqual (2, enumerated.Length, "Enumerator Count"); + Assert.That (enumerated.Length, Is.EqualTo (2), "Enumerator Count"); } [Test] @@ -811,7 +811,7 @@ public void IEnumerableTest () var c = 0; foreach (var obj in dict) c++; - Assert.AreEqual (2, c, "Enumerator Count"); + Assert.That (c, Is.EqualTo (2), "Enumerator Count"); } [Test] @@ -828,16 +828,16 @@ public void AddTest () Assert.Throws (() => dict.Add (key1, null), "ANE 2"); dict.Add (key1, value1); - Assert.AreEqual ((nuint) 1, dict.Count, "a Count"); - Assert.AreSame (value1, dict [key1], "a idx"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 1), "a Count"); + Assert.That (dict [key1], Is.SameAs (value1), "a idx"); dict.Add (key1, value1); - Assert.AreEqual ((nuint) 1, dict.Count, "b Count"); - Assert.AreSame (value1, dict [key1], "b idx"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 1), "b Count"); + Assert.That (dict [key1], Is.SameAs (value1), "b idx"); dict.Add (key2, value1); - Assert.AreEqual ((nuint) 2, dict.Count, "c Count"); - Assert.AreSame (value1, dict [key2], "c idx"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 2), "c Count"); + Assert.That (dict [key2], Is.SameAs (value1), "c idx"); } [Test] @@ -855,11 +855,11 @@ public void RemoveTest () dict.Add (key1, value1); dict.Remove (key2); - Assert.AreEqual ((nuint) 1, dict.Count, "a Count"); - Assert.AreSame (value1, dict [key1], "a idx"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 1), "a Count"); + Assert.That (dict [key1], Is.SameAs (value1), "a idx"); dict.Remove (key1); - Assert.AreEqual ((nuint) 0, dict.Count, "b Count"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 0), "b Count"); } [Test] @@ -892,28 +892,28 @@ public void AddEntries () using (var dic1 = new NSMutableDictionary ()) { var now = NSDate.Now; using (var dic2 = NSDictionary.FromObjectAndKey ((NSDate) now, (NSString) "key")) { - Assert.AreEqual ((nuint) 0, dic1.Count, "Count 0"); + Assert.That (dic1.Count, Is.EqualTo ((nuint) 0), "Count 0"); dic1.AddEntries (dic2); - Assert.AreEqual ((nuint) 1, dic1.Count, "Count 1"); - Assert.AreEqual (now, dic1 ["key"], "Value 1"); + Assert.That (dic1.Count, Is.EqualTo ((nuint) 1), "Count 1"); + Assert.That (dic1 ["key"], Is.EqualTo (now), "Value 1"); dic1.AddEntries (dic2); - Assert.AreEqual ((nuint) 1, dic1.Count, "Count 2"); - Assert.AreEqual (now, dic1 ["key"], "Value 2"); + Assert.That (dic1.Count, Is.EqualTo ((nuint) 1), "Count 2"); + Assert.That (dic1 ["key"], Is.EqualTo (now), "Value 2"); } // Be nasty, and put something of the wrong type in the dictionary dic1.Clear (); var value = (NSString) "value"; using (var dic2 = NSDictionary.FromObjectAndKey (value, (NSString) "key")) { - Assert.AreEqual ((nuint) 0, dic1.Count, "X Count 0"); + Assert.That (dic1.Count, Is.EqualTo ((nuint) 0), "X Count 0"); dic1.AddEntries (dic2); - Assert.AreEqual ((nuint) 1, dic1.Count, "X Count 1"); + Assert.That (dic1.Count, Is.EqualTo ((nuint) 1), "X Count 1"); Assert.Throws (() => { var obj = dic1 [(NSString) "key"]; // We shouldn't get this far @@ -924,13 +924,13 @@ public void AddEntries () // Use a generic dict of the right types dic1.Clear (); using (var dic2 = new NSDictionary ((NSString) "key2", now.AddSeconds (3600))) { - Assert.AreEqual ((nuint) 0, dic1.Count, "Y Count 0"); + Assert.That (dic1.Count, Is.EqualTo ((nuint) 0), "Y Count 0"); dic1.AddEntries (dic2); - Assert.AreEqual ((nuint) 1, dic1.Count, "Y Count 1"); + Assert.That (dic1.Count, Is.EqualTo ((nuint) 1), "Y Count 1"); var obj = dic1 [(NSString) "key2"]; - Assert.AreEqual (now.AddSeconds (3600).SecondsSinceReferenceDate, obj.SecondsSinceReferenceDate, "Y Value 1"); + Assert.That (obj.SecondsSinceReferenceDate, Is.EqualTo (now.AddSeconds (3600).SecondsSinceReferenceDate), "Y Value 1"); } } } diff --git a/tests/monotouch-test/Foundation/NSMutableDictionaryTest.cs b/tests/monotouch-test/Foundation/NSMutableDictionaryTest.cs index fa772dce2fdb..3d7e1c6bd9d2 100644 --- a/tests/monotouch-test/Foundation/NSMutableDictionaryTest.cs +++ b/tests/monotouch-test/Foundation/NSMutableDictionaryTest.cs @@ -23,11 +23,11 @@ public void IndexerTest () objptr = Messaging.IntPtr_objc_msgSend_IntPtr (Class.GetHandle (typeof (NSString)), Selector.GetHandle ("stringWithUTF8String:"), strobjptr); using (var dict = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (Class.GetHandle (typeof (NSMutableDictionary)), Selector.GetHandle ("dictionaryWithObject:forKey:"), objptr, keyptr))) { v = (NSString) dict ["key"]; - Assert.AreEqual ("obj", (string) v, "a"); + Assert.That ((string) v, Is.EqualTo ("obj"), "a"); dict ["key"] = (NSString) "value"; v = (NSString) dict ["key"]; - Assert.AreEqual ("value", (string) v, "a"); + Assert.That ((string) v, Is.EqualTo ("value"), "a"); } // this[NSObject] @@ -35,11 +35,11 @@ public void IndexerTest () objptr = Messaging.IntPtr_objc_msgSend_IntPtr (Class.GetHandle (typeof (NSString)), Selector.GetHandle ("stringWithUTF8String:"), strobjptr); using (var dict = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (Class.GetHandle (typeof (NSMutableDictionary)), Selector.GetHandle ("dictionaryWithObject:forKey:"), objptr, keyptr))) { v = (NSString) dict [(NSObject) (NSString) "key"]; - Assert.AreEqual ("obj", (string) v, "b"); + Assert.That ((string) v, Is.EqualTo ("obj"), "b"); dict [(NSObject) (NSString) "key"] = (NSString) "value"; v = (NSString) dict ["key"]; - Assert.AreEqual ("value", (string) v, "a"); + Assert.That ((string) v, Is.EqualTo ("value"), "a"); } // this[NSString] @@ -47,11 +47,11 @@ public void IndexerTest () objptr = Messaging.IntPtr_objc_msgSend_IntPtr (Class.GetHandle (typeof (NSString)), Selector.GetHandle ("stringWithUTF8String:"), strobjptr); using (var dict = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (Class.GetHandle (typeof (NSMutableDictionary)), Selector.GetHandle ("dictionaryWithObject:forKey:"), objptr, keyptr))) { v = (NSString) dict [(NSString) "key"]; - Assert.AreEqual ("obj", (string) v, "c"); + Assert.That ((string) v, Is.EqualTo ("obj"), "c"); dict [(NSString) "key"] = (NSString) "value"; v = (NSString) dict ["key"]; - Assert.AreEqual ("value", (string) v, "a"); + Assert.That ((string) v, Is.EqualTo ("value"), "a"); } } finally { @@ -66,8 +66,8 @@ public void Bug39993 () using (NSMutableDictionary testDict = new NSMutableDictionary ()) { testDict.Add ((NSString) "Key1", (NSString) "Key1"); testDict.Add ((NSString) "Key2", (NSString) "KeyTest2"); - Assert.NotNull (testDict ["Key1"], "Key1"); - Assert.NotNull (testDict ["Key2"], "Key2"); + Assert.That (testDict ["Key1"], Is.Not.Null, "Key1"); + Assert.That (testDict ["Key2"], Is.Not.Null, "Key2"); } } @@ -76,17 +76,17 @@ public void AddEntries () { using (var dic1 = new NSMutableDictionary ()) { using (var dic2 = NSDictionary.FromObjectAndKey ((NSString) "value", (NSString) "key")) { - Assert.AreEqual ((nuint) 0, dic1.Count, "Count 0"); + Assert.That (dic1.Count, Is.EqualTo ((nuint) 0), "Count 0"); dic1.AddEntries (dic2); - Assert.AreEqual ((nuint) 1, dic1.Count, "Count 1"); - Assert.AreEqual ("value", dic1 ["key"].ToString (), "Value 1"); + Assert.That (dic1.Count, Is.EqualTo ((nuint) 1), "Count 1"); + Assert.That (dic1 ["key"].ToString (), Is.EqualTo ("value"), "Value 1"); dic1.AddEntries (dic2); - Assert.AreEqual ((nuint) 1, dic1.Count, "Count 2"); - Assert.AreEqual ("value", dic1 ["key"].ToString (), "Value 2"); + Assert.That (dic1.Count, Is.EqualTo ((nuint) 1), "Count 2"); + Assert.That (dic1 ["key"].ToString (), Is.EqualTo ("value"), "Value 2"); } } } @@ -99,10 +99,10 @@ public void MissingKey_StringIndexer () // Accessing a missing key should return null var result = dict ["missingKey"]; - Assert.IsNull (result, "Missing key should return null"); + Assert.That (result, Is.Null, "Missing key should return null"); // Verify the existing key still works - Assert.IsNotNull (dict ["existingKey"], "Existing key should return value"); + Assert.That (dict ["existingKey"], Is.Not.Null, "Existing key should return value"); } } @@ -116,10 +116,10 @@ public void MissingKey_NSObjectIndexer () // Accessing a missing key should return null var result = dict [missingKey]; - Assert.IsNull (result, "Missing key should return null"); + Assert.That (result, Is.Null, "Missing key should return null"); // Verify the existing key still works - Assert.IsNotNull (existingKey, "Existing key should return value"); + Assert.That (existingKey, Is.Not.Null, "Existing key should return value"); } } @@ -131,10 +131,10 @@ public void MissingKey_NSStringIndexer () // Accessing a missing key should return null var result = dict [(NSString) "missingKey"]; - Assert.IsNull (result, "Missing key should return null"); + Assert.That (result, Is.Null, "Missing key should return null"); // Verify the existing key still works - Assert.IsNotNull (dict [(NSString) "existingKey"], "Existing key should return value"); + Assert.That (dict [(NSString) "existingKey"], Is.Not.Null, "Existing key should return value"); } } @@ -146,10 +146,10 @@ public void MissingKey_ObjectForKey () // ObjectForKey with missing key should return null var result = dict.ObjectForKey ((NSString) "missingKey"); - Assert.IsNull (result, "ObjectForKey with missing key should return null"); + Assert.That (result, Is.Null, "ObjectForKey with missing key should return null"); // Verify the existing key still works - Assert.IsNotNull (dict.ObjectForKey ((NSString) "existingKey"), "ObjectForKey with existing key should return value"); + Assert.That (dict.ObjectForKey ((NSString) "existingKey"), Is.Not.Null, "ObjectForKey with existing key should return value"); } } @@ -161,14 +161,14 @@ public void MissingKey_TryGetValue () // TryGetValue with missing key should return false var found = dict.TryGetValue ((NSString) "missingKey", out var result); - Assert.IsFalse (found, "TryGetValue should return false for missing key"); - Assert.IsNull (result, "Output value should be null for missing key"); + Assert.That (found, Is.False, "TryGetValue should return false for missing key"); + Assert.That (result, Is.Null, "Output value should be null for missing key"); // Verify the existing key works found = dict.TryGetValue ((NSString) "existingKey", out result); - Assert.IsTrue (found, "TryGetValue should return true for existing key"); - Assert.IsNotNull (result, "Output value should not be null for existing key"); - Assert.AreEqual ("value", result.ToString (), "Output value should match"); + Assert.That (found, Is.True, "TryGetValue should return true for existing key"); + Assert.That (result, Is.Not.Null, "Output value should not be null for existing key"); + Assert.That (result.ToString (), Is.EqualTo ("value"), "Output value should match"); } } @@ -183,10 +183,10 @@ public void MissingKey_IDictionaryIndexer () // This is different from the typed indexers which return null var result = idict [(NSString) "missingKey"]; // The IDictionary indexer calls _ObjectForKey which returns IntPtr.Zero boxed - Assert.AreEqual (IntPtr.Zero, result, "IDictionary indexer with missing key returns IntPtr.Zero"); + Assert.That (result, Is.EqualTo (IntPtr.Zero), "IDictionary indexer with missing key returns IntPtr.Zero"); // Verify the existing key still works - Assert.IsNotNull (idict [(NSString) "existingKey"], "IDictionary indexer with existing key should return value"); + Assert.That (idict [(NSString) "existingKey"], Is.Not.Null, "IDictionary indexer with existing key should return value"); } } @@ -198,10 +198,10 @@ public void MissingKey_IDictionaryContains () idict [(NSString) "existingKey"] = (NSString) "value"; // Contains should return false for missing key - Assert.IsFalse (idict.Contains ((NSString) "missingKey"), "Contains should return false for missing key"); + Assert.That (idict.Contains ((NSString) "missingKey"), Is.False, "Contains should return false for missing key"); // Contains should return true for existing key - Assert.IsTrue (idict.Contains ((NSString) "existingKey"), "Contains should return true for existing key"); + Assert.That (idict.Contains ((NSString) "existingKey"), Is.True, "Contains should return true for existing key"); } } @@ -212,9 +212,9 @@ public void FromObjectsAndKeys_WithNull () var objs = new NSObject? [] { new NSString ("value1"), null }; using (var dict = NSMutableDictionary.FromObjectsAndKeys (objs, keys)) { - Assert.AreEqual ((nuint) 2, dict.Count, "Count"); - Assert.AreEqual ("value1", dict [keys [0]].ToString (), "First value"); - Assert.IsInstanceOf (dict [keys [1]], "Null value should be NSNull"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (dict [keys [0]].ToString (), Is.EqualTo ("value1"), "First value"); + Assert.That (dict [keys [1]], Is.InstanceOf (), "Null value should be NSNull"); } } @@ -225,9 +225,9 @@ public void FromObjectsAndKeys_NSObject_WithCount_WithNull () var objs = new NSObject? [] { new NSString ("value1"), null, new NSString ("value3") }; using (var dict = NSMutableDictionary.FromObjectsAndKeys (objs, keys, 2)) { - Assert.AreEqual ((nuint) 2, dict.Count, "Count"); - Assert.AreEqual ("value1", dict [keys [0]].ToString (), "First value"); - Assert.IsInstanceOf (dict [keys [1]], "Null value should be NSNull"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (dict [keys [0]].ToString (), Is.EqualTo ("value1"), "First value"); + Assert.That (dict [keys [1]], Is.InstanceOf (), "Null value should be NSNull"); } } @@ -238,9 +238,9 @@ public void FromObjectsAndKeys_NSObject_WithCount () var objs = new NSObject [] { new NSString ("value1"), new NSString ("value2"), new NSString ("value3") }; using (var dict = NSMutableDictionary.FromObjectsAndKeys (objs, keys, 2)) { - Assert.AreEqual ((nuint) 2, dict.Count, "Count"); - Assert.AreEqual ("value1", dict [keys [0]].ToString (), "First value"); - Assert.AreEqual ("value2", dict [keys [1]].ToString (), "Second value"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (dict [keys [0]].ToString (), Is.EqualTo ("value1"), "First value"); + Assert.That (dict [keys [1]].ToString (), Is.EqualTo ("value2"), "Second value"); } } @@ -251,7 +251,7 @@ public void FromObjectsAndKeys_NSObject_WithCountZero () var objs = new NSObject [] { new NSString ("value1"), new NSString ("value2") }; using (var dict = NSMutableDictionary.FromObjectsAndKeys (objs, keys, 0)) { - Assert.AreEqual ((nuint) 0, dict.Count, "Count should be 0"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 0), "Count should be 0"); } } @@ -262,9 +262,9 @@ public void FromObjectsAndKeys_Object_WithCount_WithNull () var objs = new object [] { "value1", "value2", "value3" }; using (var dict = NSMutableDictionary.FromObjectsAndKeys (objs, keys, 2)) { - Assert.AreEqual ((nuint) 2, dict.Count, "Count"); - Assert.AreEqual ("value1", dict [(NSString) "key1"].ToString (), "First value"); - Assert.AreEqual ("value2", dict [(NSString) "key2"].ToString (), "Second value"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (dict [(NSString) "key1"].ToString (), Is.EqualTo ("value1"), "First value"); + Assert.That (dict [(NSString) "key2"].ToString (), Is.EqualTo ("value2"), "Second value"); } } @@ -276,9 +276,9 @@ public void FromObjectsAndKeys_DifferentArrayLengths_WithCount () // Should work fine since we only use first 2 items from each array using (var dict = NSMutableDictionary.FromObjectsAndKeys (objs, keys, 2)) { - Assert.AreEqual ((nuint) 2, dict.Count, "Count"); - Assert.AreEqual ("value1", dict [keys [0]].ToString (), "First value"); - Assert.AreEqual ("value2", dict [keys [1]].ToString (), "Second value"); + Assert.That (dict.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (dict [keys [0]].ToString (), Is.EqualTo ("value1"), "First value"); + Assert.That (dict [keys [1]].ToString (), Is.EqualTo ("value2"), "Second value"); } } diff --git a/tests/monotouch-test/Foundation/NSMutableOrderedSet1Test.cs b/tests/monotouch-test/Foundation/NSMutableOrderedSet1Test.cs index 2f891c66dc3c..51ef66af57d1 100644 --- a/tests/monotouch-test/Foundation/NSMutableOrderedSet1Test.cs +++ b/tests/monotouch-test/Foundation/NSMutableOrderedSet1Test.cs @@ -21,7 +21,7 @@ public void Ctor () { var oset = new NSMutableOrderedSet (); - Assert.AreEqual ((nint) 0, oset.Count, "NSMutableOrderedSet Count"); + Assert.That (oset.Count, Is.EqualTo ((nint) 0), "NSMutableOrderedSet Count"); } [Test] @@ -29,7 +29,7 @@ public void Ctor_Capacity () { var oset = new NSMutableOrderedSet (10); - Assert.AreEqual ((nint) 0, oset.Count, "NSMutableOrderedSet Count"); + Assert.That (oset.Count, Is.EqualTo ((nint) 0), "NSMutableOrderedSet Count"); } [Test] @@ -37,7 +37,7 @@ public void Ctor_Start () { var oSet = new NSMutableOrderedSet (start: (NSString) "foo"); - Assert.AreEqual ((nint) 1, oSet.Count, "NSMutableOrderedSet Count"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 1), "NSMutableOrderedSet Count"); } [Test] @@ -45,7 +45,7 @@ public void Ctor_Params () { var oSet = new NSMutableOrderedSet ((NSString) "foo", (NSString) "bar", (NSString) "xyz"); - Assert.AreEqual ((nint) 3, oSet.Count, "NSMutableOrderedSet Count"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "NSMutableOrderedSet Count"); } [Test] @@ -54,7 +54,7 @@ public void Ctor_NSSet () var set = new NSSet ((NSString) "foo", (NSString) "bar", (NSString) "xyz"); var oSet = new NSMutableOrderedSet (set); - Assert.AreEqual ((nint) set.Count, oSet.Count, "NSMutableOrderedSet Count"); + Assert.That (oSet.Count, Is.EqualTo ((nint) set.Count), "NSMutableOrderedSet Count"); } [Test] @@ -63,7 +63,7 @@ public void Ctor_NSOrderedSet () var oSetSource = new NSOrderedSet ((NSString) "foo", (NSString) "bar", (NSString) "xyz"); var oSet = new NSMutableOrderedSet (oSetSource); - Assert.AreEqual (oSetSource.Count, oSet.Count, "NSOrderedSet1Test Count"); + Assert.That (oSet.Count, Is.EqualTo (oSetSource.Count), "NSOrderedSet1Test Count"); } [Test] @@ -72,7 +72,7 @@ public void Ctor_NSMutableOrderedSet () var oMutableSet = new NSMutableOrderedSet ((NSString) "foo", (NSString) "bar", (NSString) "xyz"); var oSet = new NSMutableOrderedSet (oMutableSet); - Assert.AreEqual (oMutableSet.Count, oSet.Count, "NSOrderedSet1Test Count"); + Assert.That (oSet.Count, Is.EqualTo (oMutableSet.Count), "NSOrderedSet1Test Count"); } [Test] @@ -83,8 +83,8 @@ public void IndexerTest () var str3 = (NSString) "3"; var oSet = new NSMutableOrderedSet (str1, str2, str3); - Assert.AreEqual ((nint) 3, oSet.Count, "NSOrderedSet1Test Count"); - Assert.AreSame (str2, oSet [1], "NSOrderedSet1Test IndexOf"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "NSOrderedSet1Test Count"); + Assert.That (oSet [1], Is.SameAs (str2), "NSOrderedSet1Test IndexOf"); Assert.Throws (() => oSet [1] = null); } @@ -97,9 +97,9 @@ public void AsSetTest () var oSet = new NSMutableOrderedSet (str1, str2, str3); NSSet set = oSet.AsSet (); - Assert.AreEqual ((nint) 3, oSet.Count, "NSOrderedSet1Test Count"); - Assert.AreEqual ((nuint) 3, set.Count, "NSOrderedSet1Test Count"); - Assert.AreSame (str3, set.LookupMember (str3), "NSOrderedSet1Test IndexOf"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "NSOrderedSet1Test Count"); + Assert.That (set.Count, Is.EqualTo ((nuint) 3), "NSOrderedSet1Test Count"); + Assert.That (set.LookupMember (str3), Is.SameAs (str3), "NSOrderedSet1Test IndexOf"); } [Test] @@ -109,12 +109,12 @@ public void InsertTest () var str2 = (NSString) "2"; var str3 = (NSString) "3"; var oSet = new NSMutableOrderedSet (); - Assert.AreEqual ((nint) 0, oSet.Count, "InsertTest Count"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 0), "InsertTest Count"); oSet.Insert (str1, 0); oSet.Insert (str2, 1); oSet.Insert (str3, 2); - Assert.AreEqual ((nint) 3, oSet.Count, "InsertTest Count"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "InsertTest Count"); } [Test] @@ -128,8 +128,8 @@ public void ReplaceTest () oSet.Replace (0, str4); - Assert.IsTrue (oSet.Contains (str4), "ReplaceTesr Contains 4"); - Assert.IsFalse (oSet.Contains (str1), "ReplaceTesr Contains 4"); + Assert.That (oSet.Contains (str4), Is.True, "ReplaceTesr Contains 4"); + Assert.That (oSet.Contains (str1), Is.False, "ReplaceTesr Contains 4"); } [Test] @@ -142,10 +142,10 @@ public void AddTest () str1, str2, str3 }; - Assert.AreEqual ((nint) 3, oSet.Count, "AddTest Count"); - Assert.IsTrue (oSet.Contains (str1), "AddTest Contains 1"); - Assert.IsTrue (oSet.Contains (str2), "AddTest Contains 2"); - Assert.IsTrue (oSet.Contains (str3), "AddTest Contains 3"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "AddTest Count"); + Assert.That (oSet.Contains (str1), Is.True, "AddTest Contains 1"); + Assert.That (oSet.Contains (str2), Is.True, "AddTest Contains 2"); + Assert.That (oSet.Contains (str3), Is.True, "AddTest Contains 3"); } [Test] @@ -157,10 +157,10 @@ public void AddObjectsTest () var oSet = new NSMutableOrderedSet (); oSet.AddObjects (str1, str2, str3); - Assert.AreEqual ((nint) 3, oSet.Count, "AddObjectsTest Count"); - Assert.IsTrue (oSet.Contains (str1), "AddObjectsTest Contains 1"); - Assert.IsTrue (oSet.Contains (str2), "AddObjectsTest Contains 2"); - Assert.IsTrue (oSet.Contains (str3), "AddObjectsTest Contains 3"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "AddObjectsTest Count"); + Assert.That (oSet.Contains (str1), Is.True, "AddObjectsTest Contains 1"); + Assert.That (oSet.Contains (str2), Is.True, "AddObjectsTest Contains 2"); + Assert.That (oSet.Contains (str3), Is.True, "AddObjectsTest Contains 3"); } [Test] @@ -173,13 +173,13 @@ public void InsertObjectsTest () var oSet = new NSMutableOrderedSet (str4); oSet.InsertObjects (new [] { str1, str2, str3 }, NSIndexSet.FromNSRange (new NSRange (0, 3))); - Assert.AreEqual ((nint) 4, oSet.Count, "InsertObjectsTest Count"); - Assert.IsTrue (oSet.Contains (str1), "InsertObjectsTest Contains 1"); - Assert.IsTrue (oSet.Contains (str2), "InsertObjectsTest Contains 2"); - Assert.IsTrue (oSet.Contains (str3), "InsertObjectsTest Contains 3"); - Assert.IsTrue (oSet.Contains (str4), "InsertObjectsTest Contains 4"); - Assert.AreSame (str1, oSet [0], "InsertObjectsTest 1 == 1"); - Assert.AreSame (str4, oSet [3], "InsertObjectsTest 4 == 4"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 4), "InsertObjectsTest Count"); + Assert.That (oSet.Contains (str1), Is.True, "InsertObjectsTest Contains 1"); + Assert.That (oSet.Contains (str2), Is.True, "InsertObjectsTest Contains 2"); + Assert.That (oSet.Contains (str3), Is.True, "InsertObjectsTest Contains 3"); + Assert.That (oSet.Contains (str4), Is.True, "InsertObjectsTest Contains 4"); + Assert.That (oSet [0], Is.SameAs (str1), "InsertObjectsTest 1 == 1"); + Assert.That (oSet [3], Is.SameAs (str4), "InsertObjectsTest 4 == 4"); } [Test] @@ -191,13 +191,13 @@ public void ReplaceObjectsTest () var str4 = (NSString) "4"; var oSet = new NSMutableOrderedSet (str1, str2); - Assert.AreEqual ((nint) 2, oSet.Count, "ReplaceObjectsTest Count"); - Assert.AreSame (str1, oSet [0], "ReplaceObjectsTest 1 == 1"); - Assert.AreSame (str2, oSet [1], "ReplaceObjectsTest 2 == 2"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 2), "ReplaceObjectsTest Count"); + Assert.That (oSet [0], Is.SameAs (str1), "ReplaceObjectsTest 1 == 1"); + Assert.That (oSet [1], Is.SameAs (str2), "ReplaceObjectsTest 2 == 2"); oSet.ReplaceObjects (NSIndexSet.FromNSRange (new NSRange (0, 2)), str3, str4); - Assert.AreSame (str3, oSet [0], "ReplaceObjectsTest 3 == 3"); - Assert.AreSame (str4, oSet [1], "ReplaceObjectsTest 4 == 4"); + Assert.That (oSet [0], Is.SameAs (str3), "ReplaceObjectsTest 3 == 3"); + Assert.That (oSet [1], Is.SameAs (str4), "ReplaceObjectsTest 4 == 4"); } [Test] @@ -207,13 +207,13 @@ public void RemoveObjectTest () var str2 = (NSString) "2"; var str3 = (NSString) "3"; var oSet = new NSMutableOrderedSet (str1, str2, str3); - Assert.AreEqual ((nint) 3, oSet.Count, "RemoveObjectTest Count"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "RemoveObjectTest Count"); oSet.RemoveObject (str2); - Assert.AreEqual ((nint) 2, oSet.Count, "RemoveObjectTest Count"); - Assert.IsFalse (oSet.Contains (str2), "RemoveObjectTest must not contain 2"); - Assert.IsTrue (oSet.Contains (str1), "RemoveObjectTest Contains 1"); - Assert.IsTrue (oSet.Contains (str3), "RemoveObjectTest Contains 3"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 2), "RemoveObjectTest Count"); + Assert.That (oSet.Contains (str2), Is.False, "RemoveObjectTest must not contain 2"); + Assert.That (oSet.Contains (str1), Is.True, "RemoveObjectTest Contains 1"); + Assert.That (oSet.Contains (str3), Is.True, "RemoveObjectTest Contains 3"); } [Test] @@ -223,13 +223,13 @@ public void RemoveObjectsTest () var str2 = (NSString) "2"; var str3 = (NSString) "3"; var oSet = new NSMutableOrderedSet (str1, str2, str3); - Assert.AreEqual ((nint) 3, oSet.Count, "RemoveObjectsTest Count"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "RemoveObjectsTest Count"); oSet.RemoveObjects (str1, str2); - Assert.AreEqual ((nint) 1, oSet.Count, "RemoveObjectsTest Count"); - Assert.IsFalse (oSet.Contains (str1), "RemoveObjectsTest must not contain 1"); - Assert.IsFalse (oSet.Contains (str2), "RemoveObjectsTest must not contain 2"); - Assert.IsTrue (oSet.Contains (str3), "RemoveObjectsTest Contains 3"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 1), "RemoveObjectsTest Count"); + Assert.That (oSet.Contains (str1), Is.False, "RemoveObjectsTest must not contain 1"); + Assert.That (oSet.Contains (str2), Is.False, "RemoveObjectsTest must not contain 2"); + Assert.That (oSet.Contains (str3), Is.True, "RemoveObjectsTest Contains 3"); } [Test] @@ -241,10 +241,10 @@ public void AddObjectsTest_NullValue () var oSet = new NSMutableOrderedSet (); oSet.AddObjects (str1, str2, str3); - Assert.AreEqual ((nint) 3, oSet.Count, "AddObjectsTest_NullValue Count"); - Assert.IsTrue (oSet.Contains (str1), "AddObjectsTest_NullValue Contains 1"); - Assert.IsTrue (oSet.Contains (NSNull.Null), "AddObjectsTest_NullValue Contains NSNull"); - Assert.IsTrue (oSet.Contains (str3), "AddObjectsTest_NullValue Contains 3"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "AddObjectsTest_NullValue Count"); + Assert.That (oSet.Contains (str1), Is.True, "AddObjectsTest_NullValue Contains 1"); + Assert.That (oSet.Contains (NSNull.Null), Is.True, "AddObjectsTest_NullValue Contains NSNull"); + Assert.That (oSet.Contains (str3), Is.True, "AddObjectsTest_NullValue Contains 3"); } [Test] @@ -257,13 +257,13 @@ public void InsertObjectsTest_NullValue () var oSet = new NSMutableOrderedSet (str4); oSet.InsertObjects (new NSString? [] { str1, str2, str3 }, NSIndexSet.FromNSRange (new NSRange (0, 3))); - Assert.AreEqual ((nint) 4, oSet.Count, "InsertObjectsTest_NullValue Count"); - Assert.IsTrue (oSet.Contains (str1), "InsertObjectsTest_NullValue Contains 1"); - Assert.IsTrue (oSet.Contains (NSNull.Null), "InsertObjectsTest_NullValue Contains NSNull"); - Assert.IsTrue (oSet.Contains (str3), "InsertObjectsTest_NullValue Contains 3"); - Assert.IsTrue (oSet.Contains (str4), "InsertObjectsTest_NullValue Contains 4"); - Assert.AreSame (str1, oSet [0], "InsertObjectsTest_NullValue 1 == 1"); - Assert.AreSame (str4, oSet [3], "InsertObjectsTest_NullValue 4 == 4"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 4), "InsertObjectsTest_NullValue Count"); + Assert.That (oSet.Contains (str1), Is.True, "InsertObjectsTest_NullValue Contains 1"); + Assert.That (oSet.Contains (NSNull.Null), Is.True, "InsertObjectsTest_NullValue Contains NSNull"); + Assert.That (oSet.Contains (str3), Is.True, "InsertObjectsTest_NullValue Contains 3"); + Assert.That (oSet.Contains (str4), Is.True, "InsertObjectsTest_NullValue Contains 4"); + Assert.That (oSet [0], Is.SameAs (str1), "InsertObjectsTest_NullValue 1 == 1"); + Assert.That (oSet [3], Is.SameAs (str4), "InsertObjectsTest_NullValue 4 == 4"); } [Test] @@ -275,15 +275,15 @@ public void ReplaceObjectsTest_NullValue () var str4 = (NSString) "4"; var oSet = new NSMutableOrderedSet (str1, str2); - Assert.AreEqual ((nint) 2, oSet.Count, "ReplaceObjectsTest_NullValue Count"); - Assert.AreSame (str1, oSet [0], "ReplaceObjectsTest_NullValue 1 == 1"); - Assert.AreSame (str2, oSet [1], "ReplaceObjectsTest_NullValue 2 == 2"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 2), "ReplaceObjectsTest_NullValue Count"); + Assert.That (oSet [0], Is.SameAs (str1), "ReplaceObjectsTest_NullValue 1 == 1"); + Assert.That (oSet [1], Is.SameAs (str2), "ReplaceObjectsTest_NullValue 2 == 2"); oSet.ReplaceObjects (NSIndexSet.FromNSRange (new NSRange (0, 2)), str3, str4); var baseSet = (NSOrderedSet) oSet; var item0 = baseSet [0]; - Assert.IsInstanceOf (item0, "ReplaceObjectsTest_NullValue NSNull"); - Assert.AreSame (str4, oSet [1], "ReplaceObjectsTest_NullValue 4 == 4"); + Assert.That (item0, Is.InstanceOf (), "ReplaceObjectsTest_NullValue NSNull"); + Assert.That (oSet [1], Is.SameAs (str4), "ReplaceObjectsTest_NullValue 4 == 4"); } [Test] @@ -294,13 +294,13 @@ public void RemoveObjectsTest_NullValue () var str3 = (NSString) "3"; var oSet = new NSMutableOrderedSet (); oSet.AddObjects (str1, str2, str3); - Assert.AreEqual ((nint) 3, oSet.Count, "RemoveObjectsTest_NullValue Count"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "RemoveObjectsTest_NullValue Count"); oSet.RemoveObjects (str1, str2); - Assert.AreEqual ((nint) 1, oSet.Count, "RemoveObjectsTest_NullValue Count After Remove"); - Assert.IsFalse (oSet.Contains (str1), "RemoveObjectsTest_NullValue must not contain 1"); - Assert.IsFalse (oSet.Contains (NSNull.Null), "RemoveObjectsTest_NullValue must not contain NSNull"); - Assert.IsTrue (oSet.Contains (str3), "RemoveObjectsTest_NullValue Contains 3"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 1), "RemoveObjectsTest_NullValue Count After Remove"); + Assert.That (oSet.Contains (str1), Is.False, "RemoveObjectsTest_NullValue must not contain 1"); + Assert.That (oSet.Contains (NSNull.Null), Is.False, "RemoveObjectsTest_NullValue must not contain NSNull"); + Assert.That (oSet.Contains (str3), Is.True, "RemoveObjectsTest_NullValue Contains 3"); } [Test] @@ -312,16 +312,16 @@ public void IEnumerable1Test () values [i] = (NSString) i.ToString (); var st = new NSMutableOrderedSet (values); - Assert.AreEqual ((nint) C, st.Count, "Count 1"); + Assert.That (st.Count, Is.EqualTo ((nint) C), "Count 1"); var lst = new List (); foreach (var a in (IEnumerable) st) { - Assert.IsNotNull (a, "null item iterator"); - Assert.IsFalse (lst.Contains (a), "duplicated item iterator"); + Assert.That (a, Is.Not.Null, "null item iterator"); + Assert.That (lst.Contains (a), Is.False, "duplicated item iterator"); lst.Add (a); - Assert.IsTrue (Array.IndexOf (values, a) >= 0, "different object"); + Assert.That (Array.IndexOf (values, a) >= 0, Is.True, "different object"); } - Assert.AreEqual (C, lst.Count, "iterator count"); + Assert.That (lst.Count, Is.EqualTo (C), "iterator count"); } [Test] @@ -344,16 +344,16 @@ public void IEnumerableTest () values [i] = (NSString) i.ToString (); var st = new NSMutableOrderedSet (values); - Assert.AreEqual ((nint) C, st.Count, "Count 1"); + Assert.That (st.Count, Is.EqualTo ((nint) C), "Count 1"); var lst = new List (); foreach (NSString a in (IEnumerable) st) { - Assert.IsNotNull (a, "null item iterator"); - Assert.IsFalse (lst.Contains (a), "duplicated item iterator"); + Assert.That (a, Is.Not.Null, "null item iterator"); + Assert.That (lst.Contains (a), Is.False, "duplicated item iterator"); lst.Add (a); - Assert.IsTrue (Array.IndexOf (values, a) >= 0, "different object"); + Assert.That (Array.IndexOf (values, a) >= 0, Is.True, "different object"); } - Assert.AreEqual (C, lst.Count, "iterator count"); + Assert.That (lst.Count, Is.EqualTo (C), "iterator count"); } [Test] @@ -367,11 +367,11 @@ public void OperatorAddTest () var first = new NSMutableOrderedSet (str1, str2); var second = new NSMutableOrderedSet (str3, str4); var third = first + second; - Assert.AreEqual ((nint) 4, third.Count, "OperatorAdd Count"); - Assert.IsTrue (third.Contains (str1), "OperatorAdd 1"); - Assert.IsTrue (third.Contains (str2), "OperatorAdd 2"); - Assert.IsTrue (third.Contains (str3), "OperatorAdd 3"); - Assert.IsTrue (third.Contains (str4), "OperatorAdd 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 4), "OperatorAdd Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorAdd 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorAdd 2"); + Assert.That (third.Contains (str3), Is.True, "OperatorAdd 3"); + Assert.That (third.Contains (str4), Is.True, "OperatorAdd 4"); } [Test] @@ -385,11 +385,11 @@ public void OperatorAddTest2 () var first = new NSMutableOrderedSet (str1, str2); var second = new NSSet (str3, str4); var third = first + second; - Assert.AreEqual ((nint) 4, third.Count, "OperatorAdd Count"); - Assert.IsTrue (third.Contains (str1), "OperatorAdd 1"); - Assert.IsTrue (third.Contains (str2), "OperatorAdd 2"); - Assert.IsTrue (third.Contains (str3), "OperatorAdd 3"); - Assert.IsTrue (third.Contains (str4), "OperatorAdd 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 4), "OperatorAdd Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorAdd 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorAdd 2"); + Assert.That (third.Contains (str3), Is.True, "OperatorAdd 3"); + Assert.That (third.Contains (str4), Is.True, "OperatorAdd 4"); } [Test] @@ -403,11 +403,11 @@ public void OperatorAddTest3 () var first = new NSMutableOrderedSet (str1, str2); var second = new NSOrderedSet (str3, str4); var third = first + second; - Assert.AreEqual ((nint) 4, third.Count, "OperatorAdd Count"); - Assert.IsTrue (third.Contains (str1), "OperatorAdd 1"); - Assert.IsTrue (third.Contains (str2), "OperatorAdd 2"); - Assert.IsTrue (third.Contains (str3), "OperatorAdd 3"); - Assert.IsTrue (third.Contains (str4), "OperatorAdd 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 4), "OperatorAdd Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorAdd 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorAdd 2"); + Assert.That (third.Contains (str3), Is.True, "OperatorAdd 3"); + Assert.That (third.Contains (str4), Is.True, "OperatorAdd 4"); } [Test] @@ -422,11 +422,11 @@ public void OperatorSubtractTest () var second = new NSMutableOrderedSet (str3, str4); var third = first - second; - Assert.AreEqual ((nint) 2, third.Count, "OperatorSubtract Count"); - Assert.IsTrue (third.Contains (str1), "OperatorSubtract 1"); - Assert.IsTrue (third.Contains (str2), "OperatorSubtract 2"); - Assert.IsFalse (third.Contains (str3), "OperatorSubtract 3"); - Assert.IsFalse (third.Contains (str4), "OperatorSubtract 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 2), "OperatorSubtract Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorSubtract 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorSubtract 2"); + Assert.That (third.Contains (str3), Is.False, "OperatorSubtract 3"); + Assert.That (third.Contains (str4), Is.False, "OperatorSubtract 4"); } [Test] @@ -441,11 +441,11 @@ public void OperatorSubtractTest2 () var second = new NSSet (str3, str4); var third = first - second; - Assert.AreEqual ((nint) 2, third.Count, "OperatorSubtract Count"); - Assert.IsTrue (third.Contains (str1), "OperatorSubtract 1"); - Assert.IsTrue (third.Contains (str2), "OperatorSubtract 2"); - Assert.IsFalse (third.Contains (str3), "OperatorSubtract 3"); - Assert.IsFalse (third.Contains (str4), "OperatorSubtract 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 2), "OperatorSubtract Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorSubtract 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorSubtract 2"); + Assert.That (third.Contains (str3), Is.False, "OperatorSubtract 3"); + Assert.That (third.Contains (str4), Is.False, "OperatorSubtract 4"); } [Test] @@ -460,11 +460,11 @@ public void OperatorSubtractTest3 () var second = new NSOrderedSet (str3, str4); var third = first - second; - Assert.AreEqual ((nint) 2, third.Count, "OperatorSubtract Count"); - Assert.IsTrue (third.Contains (str1), "OperatorSubtract 1"); - Assert.IsTrue (third.Contains (str2), "OperatorSubtract 2"); - Assert.IsFalse (third.Contains (str3), "OperatorSubtract 3"); - Assert.IsFalse (third.Contains (str4), "OperatorSubtract 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 2), "OperatorSubtract Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorSubtract 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorSubtract 2"); + Assert.That (third.Contains (str3), Is.False, "OperatorSubtract 3"); + Assert.That (third.Contains (str4), Is.False, "OperatorSubtract 4"); } [Test] @@ -485,8 +485,8 @@ public void OperatorPlusReferenceTest () using (var sum3 = one + two) { } - Assert.AreNotEqual (IntPtr.Zero, one.Handle, "Handle must be != IntPtr.Zero"); - Assert.AreNotEqual (IntPtr.Zero, two.Handle, "Handle must be != IntPtr.Zero"); + Assert.That (one.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); + Assert.That (two.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); } [Test] @@ -495,7 +495,7 @@ public void OperatorAdd_NullNull () NSMutableOrderedSet first = null; NSMutableOrderedSet second = null; var result = first + second; - Assert.IsNull (result, "null + null should be null"); + Assert.That (result, Is.Null, "null + null should be null"); } [Test] @@ -504,10 +504,10 @@ public void OperatorAdd_NullNonEmpty () NSMutableOrderedSet first = null; var second = new NSMutableOrderedSet ((NSString) "1", (NSString) "2"); var result = first + second; - Assert.IsNotNull (result, "null + non-empty should not be null"); - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Should contain 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Should contain 2"); + Assert.That (result, Is.Not.Null, "null + non-empty should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Should contain 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Should contain 2"); } [Test] @@ -516,10 +516,10 @@ public void OperatorAdd_NonEmptyNull () var first = new NSMutableOrderedSet ((NSString) "1", (NSString) "2"); NSMutableOrderedSet second = null; var result = first + second; - Assert.IsNotNull (result, "non-empty + null should not be null"); - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Should contain 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Should contain 2"); + Assert.That (result, Is.Not.Null, "non-empty + null should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Should contain 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Should contain 2"); } [Test] @@ -528,8 +528,8 @@ public void OperatorAdd_EmptyEmpty () var first = new NSMutableOrderedSet (); var second = new NSMutableOrderedSet (); var result = first + second; - Assert.IsNotNull (result, "empty + empty should not be null"); - Assert.AreEqual ((nint) 0, result.Count, "Count should be 0"); + Assert.That (result, Is.Not.Null, "empty + empty should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 0), "Count should be 0"); } [Test] @@ -538,10 +538,10 @@ public void OperatorAdd_EmptyNonEmpty () var first = new NSMutableOrderedSet (); var second = new NSMutableOrderedSet ((NSString) "1", (NSString) "2"); var result = first + second; - Assert.IsNotNull (result, "empty + non-empty should not be null"); - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Should contain 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Should contain 2"); + Assert.That (result, Is.Not.Null, "empty + non-empty should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Should contain 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Should contain 2"); } [Test] @@ -550,10 +550,10 @@ public void OperatorAdd_NonEmptyEmpty () var first = new NSMutableOrderedSet ((NSString) "1", (NSString) "2"); var second = new NSMutableOrderedSet (); var result = first + second; - Assert.IsNotNull (result, "non-empty + empty should not be null"); - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Should contain 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Should contain 2"); + Assert.That (result, Is.Not.Null, "non-empty + empty should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Should contain 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Should contain 2"); } [Test] @@ -562,7 +562,7 @@ public void OperatorAdd_WithNSSet_NullNull () NSMutableOrderedSet first = null; NSSet second = null; var result = first + second; - Assert.IsNull (result, "null + null should be null"); + Assert.That (result, Is.Null, "null + null should be null"); } [Test] @@ -571,10 +571,10 @@ public void OperatorAdd_WithNSSet_NullNonEmpty () NSMutableOrderedSet first = null; var second = new NSSet ((NSString) "1", (NSString) "2"); var result = first + second; - Assert.IsNotNull (result, "null + non-empty NSSet should not be null"); - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Should contain 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Should contain 2"); + Assert.That (result, Is.Not.Null, "null + non-empty NSSet should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Should contain 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Should contain 2"); } [Test] @@ -583,10 +583,10 @@ public void OperatorAdd_WithNSSet_NonEmptyNull () var first = new NSMutableOrderedSet ((NSString) "1", (NSString) "2"); NSSet second = null; var result = first + second; - Assert.IsNotNull (result, "non-empty + null NSSet should not be null"); - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Should contain 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Should contain 2"); + Assert.That (result, Is.Not.Null, "non-empty + null NSSet should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Should contain 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Should contain 2"); } [Test] @@ -595,8 +595,8 @@ public void OperatorAdd_WithNSSet_EmptyEmpty () var first = new NSMutableOrderedSet (); var second = new NSSet (); var result = first + second; - Assert.IsNotNull (result, "empty + empty NSSet should not be null"); - Assert.AreEqual ((nint) 0, result.Count, "Count should be 0"); + Assert.That (result, Is.Not.Null, "empty + empty NSSet should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 0), "Count should be 0"); } [Test] @@ -605,7 +605,7 @@ public void OperatorAdd_WithNSOrderedSet_NullNull () NSMutableOrderedSet first = null; NSOrderedSet second = null; var result = first + second; - Assert.IsNull (result, "null + null should be null"); + Assert.That (result, Is.Null, "null + null should be null"); } [Test] @@ -614,10 +614,10 @@ public void OperatorAdd_WithNSOrderedSet_NullNonEmpty () NSMutableOrderedSet first = null; var second = new NSOrderedSet ((NSString) "1", (NSString) "2"); var result = first + second; - Assert.IsNotNull (result, "null + non-empty NSOrderedSet should not be null"); - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Should contain 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Should contain 2"); + Assert.That (result, Is.Not.Null, "null + non-empty NSOrderedSet should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Should contain 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Should contain 2"); } [Test] @@ -626,10 +626,10 @@ public void OperatorAdd_WithNSOrderedSet_NonEmptyNull () var first = new NSMutableOrderedSet ((NSString) "1", (NSString) "2"); NSOrderedSet second = null; var result = first + second; - Assert.IsNotNull (result, "non-empty + null NSOrderedSet should not be null"); - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Should contain 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Should contain 2"); + Assert.That (result, Is.Not.Null, "non-empty + null NSOrderedSet should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Should contain 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Should contain 2"); } [Test] @@ -638,8 +638,8 @@ public void OperatorAdd_WithNSOrderedSet_EmptyEmpty () var first = new NSMutableOrderedSet (); var second = new NSOrderedSet (); var result = first + second; - Assert.IsNotNull (result, "empty + empty NSOrderedSet should not be null"); - Assert.AreEqual ((nint) 0, result.Count, "Count should be 0"); + Assert.That (result, Is.Not.Null, "empty + empty NSOrderedSet should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 0), "Count should be 0"); } [Test] @@ -648,7 +648,7 @@ public void OperatorSubtract_NullNull () NSMutableOrderedSet first = null; NSMutableOrderedSet second = null; var result = first - second; - Assert.IsNull (result, "null - null should be null"); + Assert.That (result, Is.Null, "null - null should be null"); } [Test] @@ -657,7 +657,7 @@ public void OperatorSubtract_NullNonEmpty () NSMutableOrderedSet first = null; var second = new NSMutableOrderedSet ((NSString) "1", (NSString) "2"); var result = first - second; - Assert.IsNull (result, "null - non-empty should be null"); + Assert.That (result, Is.Null, "null - non-empty should be null"); } [Test] @@ -666,10 +666,10 @@ public void OperatorSubtract_NonEmptyNull () var first = new NSMutableOrderedSet ((NSString) "1", (NSString) "2"); NSMutableOrderedSet second = null; var result = first - second; - Assert.IsNotNull (result, "non-empty - null should not be null"); - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Should contain 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Should contain 2"); + Assert.That (result, Is.Not.Null, "non-empty - null should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Should contain 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Should contain 2"); } [Test] @@ -678,8 +678,8 @@ public void OperatorSubtract_EmptyEmpty () var first = new NSMutableOrderedSet (); var second = new NSMutableOrderedSet (); var result = first - second; - Assert.IsNotNull (result, "empty - empty should not be null"); - Assert.AreEqual ((nint) 0, result.Count, "Count should be 0"); + Assert.That (result, Is.Not.Null, "empty - empty should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 0), "Count should be 0"); } [Test] @@ -688,8 +688,8 @@ public void OperatorSubtract_EmptyNonEmpty () var first = new NSMutableOrderedSet (); var second = new NSMutableOrderedSet ((NSString) "1", (NSString) "2"); var result = first - second; - Assert.IsNotNull (result, "empty - non-empty should not be null"); - Assert.AreEqual ((nint) 0, result.Count, "Count should be 0"); + Assert.That (result, Is.Not.Null, "empty - non-empty should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 0), "Count should be 0"); } [Test] @@ -698,10 +698,10 @@ public void OperatorSubtract_NonEmptyEmpty () var first = new NSMutableOrderedSet ((NSString) "1", (NSString) "2"); var second = new NSMutableOrderedSet (); var result = first - second; - Assert.IsNotNull (result, "non-empty - empty should not be null"); - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Should contain 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Should contain 2"); + Assert.That (result, Is.Not.Null, "non-empty - empty should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Should contain 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Should contain 2"); } [Test] @@ -710,7 +710,7 @@ public void OperatorSubtract_WithNSSet_NullNull () NSMutableOrderedSet first = null; NSSet second = null; var result = first - second; - Assert.IsNull (result, "null - null should be null"); + Assert.That (result, Is.Null, "null - null should be null"); } [Test] @@ -719,7 +719,7 @@ public void OperatorSubtract_WithNSSet_NullNonEmpty () NSMutableOrderedSet first = null; var second = new NSSet ((NSString) "1", (NSString) "2"); var result = first - second; - Assert.IsNull (result, "null - non-empty NSSet should be null"); + Assert.That (result, Is.Null, "null - non-empty NSSet should be null"); } [Test] @@ -728,10 +728,10 @@ public void OperatorSubtract_WithNSSet_NonEmptyNull () var first = new NSMutableOrderedSet ((NSString) "1", (NSString) "2"); NSSet second = null; var result = first - second; - Assert.IsNotNull (result, "non-empty - null NSSet should not be null"); - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Should contain 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Should contain 2"); + Assert.That (result, Is.Not.Null, "non-empty - null NSSet should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Should contain 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Should contain 2"); } [Test] @@ -740,8 +740,8 @@ public void OperatorSubtract_WithNSSet_EmptyEmpty () var first = new NSMutableOrderedSet (); var second = new NSSet (); var result = first - second; - Assert.IsNotNull (result, "empty - empty NSSet should not be null"); - Assert.AreEqual ((nint) 0, result.Count, "Count should be 0"); + Assert.That (result, Is.Not.Null, "empty - empty NSSet should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 0), "Count should be 0"); } [Test] @@ -750,7 +750,7 @@ public void OperatorSubtract_WithNSOrderedSet_NullNull () NSMutableOrderedSet first = null; NSOrderedSet second = null; var result = first - second; - Assert.IsNull (result, "null - null should be null"); + Assert.That (result, Is.Null, "null - null should be null"); } [Test] @@ -759,7 +759,7 @@ public void OperatorSubtract_WithNSOrderedSet_NullNonEmpty () NSMutableOrderedSet first = null; var second = new NSOrderedSet ((NSString) "1", (NSString) "2"); var result = first - second; - Assert.IsNull (result, "null - non-empty NSOrderedSet should be null"); + Assert.That (result, Is.Null, "null - non-empty NSOrderedSet should be null"); } [Test] @@ -768,10 +768,10 @@ public void OperatorSubtract_WithNSOrderedSet_NonEmptyNull () var first = new NSMutableOrderedSet ((NSString) "1", (NSString) "2"); NSOrderedSet second = null; var result = first - second; - Assert.IsNotNull (result, "non-empty - null NSOrderedSet should not be null"); - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Should contain 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Should contain 2"); + Assert.That (result, Is.Not.Null, "non-empty - null NSOrderedSet should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Should contain 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Should contain 2"); } [Test] @@ -780,8 +780,8 @@ public void OperatorSubtract_WithNSOrderedSet_EmptyEmpty () var first = new NSMutableOrderedSet (); var second = new NSOrderedSet (); var result = first - second; - Assert.IsNotNull (result, "empty - empty NSOrderedSet should not be null"); - Assert.AreEqual ((nint) 0, result.Count, "Count should be 0"); + Assert.That (result, Is.Not.Null, "empty - empty NSOrderedSet should not be null"); + Assert.That (result.Count, Is.EqualTo ((nint) 0), "Count should be 0"); } [Test] @@ -795,10 +795,10 @@ public void OperatorAdd_WithDuplicates () var second = new NSMutableOrderedSet (str2, str3); var result = first + second; - Assert.AreEqual ((nint) 3, result.Count, "Count should be 3 (no duplicates)"); - Assert.IsTrue (result.Contains (str1), "Should contain 1"); - Assert.IsTrue (result.Contains (str2), "Should contain 2"); - Assert.IsTrue (result.Contains (str3), "Should contain 3"); + Assert.That (result.Count, Is.EqualTo ((nint) 3), "Count should be 3 (no duplicates)"); + Assert.That (result.Contains (str1), Is.True, "Should contain 1"); + Assert.That (result.Contains (str2), Is.True, "Should contain 2"); + Assert.That (result.Contains (str3), Is.True, "Should contain 3"); } [Test] @@ -813,11 +813,11 @@ public void OperatorSubtract_PartialOverlap () var second = new NSMutableOrderedSet (str2, str4); var result = first - second; - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains (str1), "Should contain 1"); - Assert.IsFalse (result.Contains (str2), "Should not contain 2"); - Assert.IsTrue (result.Contains (str3), "Should contain 3"); - Assert.IsFalse (result.Contains (str4), "Should not contain 4"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains (str1), Is.True, "Should contain 1"); + Assert.That (result.Contains (str2), Is.False, "Should not contain 2"); + Assert.That (result.Contains (str3), Is.True, "Should contain 3"); + Assert.That (result.Contains (str4), Is.False, "Should not contain 4"); } [Test] @@ -832,11 +832,11 @@ public void OperatorSubtract_NoOverlap () var second = new NSMutableOrderedSet (str3, str4); var result = first - second; - Assert.AreEqual ((nint) 2, result.Count, "Count should be 2"); - Assert.IsTrue (result.Contains (str1), "Should contain 1"); - Assert.IsTrue (result.Contains (str2), "Should contain 2"); - Assert.IsFalse (result.Contains (str3), "Should not contain 3"); - Assert.IsFalse (result.Contains (str4), "Should not contain 4"); + Assert.That (result.Count, Is.EqualTo ((nint) 2), "Count should be 2"); + Assert.That (result.Contains (str1), Is.True, "Should contain 1"); + Assert.That (result.Contains (str2), Is.True, "Should contain 2"); + Assert.That (result.Contains (str3), Is.False, "Should not contain 3"); + Assert.That (result.Contains (str4), Is.False, "Should not contain 4"); } [Test] @@ -924,9 +924,9 @@ public void Indexer_OrderPreservation () var str3 = (NSString) "3"; var oSet = new NSMutableOrderedSet (str1, str2, str3); - Assert.AreSame (str1, oSet [0], "Index 0 should be str1"); - Assert.AreSame (str2, oSet [1], "Index 1 should be str2"); - Assert.AreSame (str3, oSet [2], "Index 2 should be str3"); + Assert.That (oSet [0], Is.SameAs (str1), "Index 0 should be str1"); + Assert.That (oSet [1], Is.SameAs (str2), "Index 1 should be str2"); + Assert.That (oSet [2], Is.SameAs (str3), "Index 2 should be str3"); } [Test] @@ -938,8 +938,8 @@ public void Indexer_SetValue () var oSet = new NSMutableOrderedSet (str1, str2); oSet [1] = str3; - Assert.AreSame (str3, oSet [1], "Index 1 should now be str3"); - Assert.AreEqual ((nint) 2, oSet.Count, "Count should remain 2"); + Assert.That (oSet [1], Is.SameAs (str3), "Index 1 should now be str3"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 2), "Count should remain 2"); } [Test] @@ -947,10 +947,10 @@ public void Add_DuplicateElement () { var str1 = (NSString) "1"; var oSet = new NSMutableOrderedSet (str1); - Assert.AreEqual ((nint) 1, oSet.Count, "Initial count should be 1"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 1), "Initial count should be 1"); oSet.Add (str1); - Assert.AreEqual ((nint) 1, oSet.Count, "Count should still be 1 after adding duplicate"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 1), "Count should still be 1 after adding duplicate"); } [Test] @@ -962,10 +962,10 @@ public void Insert_AtBeginning () var oSet = new NSMutableOrderedSet (str2, str3); oSet.Insert (str1, 0); - Assert.AreEqual ((nint) 3, oSet.Count, "Count should be 3"); - Assert.AreSame (str1, oSet [0], "Index 0 should be str1"); - Assert.AreSame (str2, oSet [1], "Index 1 should be str2"); - Assert.AreSame (str3, oSet [2], "Index 2 should be str3"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "Count should be 3"); + Assert.That (oSet [0], Is.SameAs (str1), "Index 0 should be str1"); + Assert.That (oSet [1], Is.SameAs (str2), "Index 1 should be str2"); + Assert.That (oSet [2], Is.SameAs (str3), "Index 2 should be str3"); } [Test] @@ -977,10 +977,10 @@ public void Insert_AtEnd () var oSet = new NSMutableOrderedSet (str1, str2); oSet.Insert (str3, 2); - Assert.AreEqual ((nint) 3, oSet.Count, "Count should be 3"); - Assert.AreSame (str1, oSet [0], "Index 0 should be str1"); - Assert.AreSame (str2, oSet [1], "Index 1 should be str2"); - Assert.AreSame (str3, oSet [2], "Index 2 should be str3"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "Count should be 3"); + Assert.That (oSet [0], Is.SameAs (str1), "Index 0 should be str1"); + Assert.That (oSet [1], Is.SameAs (str2), "Index 1 should be str2"); + Assert.That (oSet [2], Is.SameAs (str3), "Index 2 should be str3"); } [Test] @@ -988,8 +988,8 @@ public void AsSet_EmptySet () { var oSet = new NSMutableOrderedSet (); var set = oSet.AsSet (); - Assert.IsNotNull (set, "AsSet should not return null"); - Assert.AreEqual ((nuint) 0, set.Count, "Set count should be 0"); + Assert.That (set, Is.Not.Null, "AsSet should not return null"); + Assert.That (set.Count, Is.EqualTo ((nuint) 0), "Set count should be 0"); } [Test] @@ -1000,8 +1000,8 @@ public void RemoveObject_NotPresent () var oSet = new NSMutableOrderedSet (str1); oSet.RemoveObject (str2); - Assert.AreEqual ((nint) 1, oSet.Count, "Count should remain 1"); - Assert.IsTrue (oSet.Contains (str1), "Should still contain str1"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 1), "Count should remain 1"); + Assert.That (oSet.Contains (str1), Is.True, "Should still contain str1"); } [Test] @@ -1011,8 +1011,8 @@ public void RemoveObjects_EmptyArray () var oSet = new NSMutableOrderedSet (str1); oSet.RemoveObjects (new NSString [0]); - Assert.AreEqual ((nint) 1, oSet.Count, "Count should remain 1"); - Assert.IsTrue (oSet.Contains (str1), "Should still contain str1"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 1), "Count should remain 1"); + Assert.That (oSet.Contains (str1), Is.True, "Should still contain str1"); } [Test] @@ -1020,7 +1020,7 @@ public void AddObjects_EmptyArray () { var oSet = new NSMutableOrderedSet (); oSet.AddObjects (new NSString [0]); - Assert.AreEqual ((nint) 0, oSet.Count, "Count should be 0"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 0), "Count should be 0"); } } } diff --git a/tests/monotouch-test/Foundation/NSMutableOrderedSetTest.cs b/tests/monotouch-test/Foundation/NSMutableOrderedSetTest.cs index 50b4bc5a4f1f..20621c2e1abe 100644 --- a/tests/monotouch-test/Foundation/NSMutableOrderedSetTest.cs +++ b/tests/monotouch-test/Foundation/NSMutableOrderedSetTest.cs @@ -24,10 +24,10 @@ public void OperatorAddTest () using (var set1 = new NSMutableOrderedSet (str1)) using (var set2 = new NSMutableOrderedSet (str2, str3)) using (var result = set1 + set2) { - Assert.AreEqual ((nint) 3, result.Count, "AddTest Count"); - Assert.IsTrue (result.Contains (str1), "AddTest Contains 1"); - Assert.IsTrue (result.Contains (str2), "AddTest Contains 2"); - Assert.IsTrue (result.Contains (str3), "AddTest Contains 3"); + Assert.That (result.Count, Is.EqualTo ((nint) 3), "AddTest Count"); + Assert.That (result.Contains (str1), Is.True, "AddTest Contains 1"); + Assert.That (result.Contains (str2), Is.True, "AddTest Contains 2"); + Assert.That (result.Contains (str3), Is.True, "AddTest Contains 3"); } } @@ -43,11 +43,11 @@ public void OperatorSubtractTest () using (var second = new NSMutableOrderedSet (str3, str4)) using (var third = first - second) { - Assert.AreEqual ((nint) 2, third.Count, "OperatorSubtract Count"); - Assert.IsTrue (third.Contains (str1), "OperatorSubtract 1"); - Assert.IsTrue (third.Contains (str2), "OperatorSubtract 2"); - Assert.IsFalse (third.Contains (str3), "OperatorSubtract 3"); - Assert.IsFalse (third.Contains (str4), "OperatorSubtract 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 2), "OperatorSubtract Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorSubtract 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorSubtract 2"); + Assert.That (third.Contains (str3), Is.False, "OperatorSubtract 3"); + Assert.That (third.Contains (str4), Is.False, "OperatorSubtract 4"); } } @@ -62,8 +62,8 @@ public void OperatorPlusReferenceTest () using (var sum3 = one + two) { } - Assert.AreNotEqual (IntPtr.Zero, one.Handle, "Handle must be != IntPtr.Zero"); - Assert.AreNotEqual (IntPtr.Zero, two.Handle, "Handle must be != IntPtr.Zero"); + Assert.That (one.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); + Assert.That (two.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); } [Test] @@ -75,8 +75,8 @@ public void OperatorEqualTest () using (var oSet = new NSMutableOrderedSet (str1, str2, str3)) using (var oSet2 = new NSMutableOrderedSet (str1, str2, str3)) { - Assert.IsTrue (oSet == oSet2, "NSMutableOrderedSetTest == must be true"); - Assert.IsTrue (oSet.Equals (oSet2), "NSMutableOrderedSetTest Equals must be true"); + Assert.That (oSet == oSet2, Is.True, "NSMutableOrderedSetTest == must be true"); + Assert.That (oSet.Equals (oSet2), Is.True, "NSMutableOrderedSetTest Equals must be true"); } } @@ -89,8 +89,8 @@ public void OperatorDifferentTest () using (var oSet = new NSMutableOrderedSet (str1, str2, str3)) using (var oSet2 = new NSMutableOrderedSet (str3, str2, str1)) { - Assert.IsTrue (oSet != oSet2, "NSMutableOrderedSetTest != must be true"); - Assert.IsFalse (oSet.Equals (oSet2), "NSMutableOrderedSetTest Equals must be false"); + Assert.That (oSet != oSet2, Is.True, "NSMutableOrderedSetTest != must be true"); + Assert.That (oSet.Equals (oSet2), Is.False, "NSMutableOrderedSetTest Equals must be false"); } } @@ -100,9 +100,9 @@ public void Ctor_WithNull () var str1 = (NSString) "1"; NSObject? nullObj = null; using (var set = new NSMutableOrderedSet (str1, nullObj)) { - Assert.AreEqual (2, (int) set.Count, "Count should include null"); - Assert.AreEqual (str1, set [0], "First item"); - Assert.IsInstanceOf (set [1], "Second item should be NSNull"); + Assert.That ((int) set.Count, Is.EqualTo (2), "Count should include null"); + Assert.That (set [0], Is.EqualTo (str1), "First item"); + Assert.That (set [1], Is.InstanceOf (), "Second item should be NSNull"); } } @@ -111,7 +111,7 @@ public void Ctor_NullArray () { NSObject []? objs = null; using (var set = new NSMutableOrderedSet (objs)) { - Assert.AreEqual (0, (int) set.Count, "Null array should create empty set"); + Assert.That ((int) set.Count, Is.EqualTo (0), "Null array should create empty set"); } } } diff --git a/tests/monotouch-test/Foundation/NSMutableSet1Test.cs b/tests/monotouch-test/Foundation/NSMutableSet1Test.cs index c3014749dd10..95317729fac0 100644 --- a/tests/monotouch-test/Foundation/NSMutableSet1Test.cs +++ b/tests/monotouch-test/Foundation/NSMutableSet1Test.cs @@ -10,7 +10,7 @@ public class NSMutableSet1Test { public void Ctor () { using (var arr = new NSMutableSet ()) { - Assert.AreEqual ((nuint) 0, arr.Count, "Count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "Count"); } } @@ -18,10 +18,10 @@ public void Ctor () public void Ctor_Params () { using (var arr = new NSMutableSet ((NSString) "foo")) { - Assert.AreEqual ((nuint) 1, arr.Count, "Count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 1), "Count"); } using (var arr = new NSMutableSet ((NSString) "foo", (NSString) "bar")) { - Assert.AreEqual ((nuint) 2, arr.Count, "Count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "Count"); } } @@ -32,8 +32,8 @@ public void Ctor_OtherSet () using (var first = new NSSet (v1)) { using (var second = new NSMutableSet (first)) { - Assert.AreEqual ((nuint) 1, first.Count, "1 count"); - Assert.AreEqual ((nuint) 1, second.Count, "2 count"); + Assert.That (first.Count, Is.EqualTo ((nuint) 1), "1 count"); + Assert.That (second.Count, Is.EqualTo ((nuint) 1), "2 count"); } } } @@ -45,8 +45,8 @@ public void Ctor_OtherMutableSet () using (var first = new NSMutableSet (v1)) { using (var second = new NSMutableSet (first)) { - Assert.AreEqual ((nuint) 1, first.Count, "1 count"); - Assert.AreEqual ((nuint) 1, second.Count, "2 count"); + Assert.That (first.Count, Is.EqualTo ((nuint) 1), "1 count"); + Assert.That (second.Count, Is.EqualTo ((nuint) 1), "2 count"); } } } @@ -59,8 +59,8 @@ public void LookupMemberTest () using (var st = new NSMutableSet (v1)) { Assert.Throws (() => st.LookupMember ((NSString) null), "LookupMember ANE 1"); - Assert.AreSame (v1, st.LookupMember (v1), "LookupMember 1"); - Assert.IsNull (st.LookupMember (v2), "LookupMember 2"); + Assert.That (st.LookupMember (v1), Is.SameAs (v1), "LookupMember 1"); + Assert.That (st.LookupMember (v2), Is.Null, "LookupMember 2"); } } @@ -71,11 +71,11 @@ public void AnyObjectTest () var v2 = (NSString) "2"; using (var st = new NSMutableSet ()) { - Assert.IsNull (st.AnyObject, "AnyObject 1"); + Assert.That (st.AnyObject, Is.Null, "AnyObject 1"); } using (var st = new NSMutableSet (v1)) { - Assert.AreSame (v1, st.AnyObject, "AnyObject 2"); + Assert.That (st.AnyObject, Is.SameAs (v1), "AnyObject 2"); } } @@ -87,8 +87,8 @@ public void ContainsTest () using (var st = new NSMutableSet (v1)) { Assert.Throws (() => st.Contains ((NSString) null), "Contains ANE 1"); - Assert.IsTrue (st.Contains (v1), "Contains 1"); - Assert.IsFalse (st.Contains (v2), "Contains 2"); + Assert.That (st.Contains (v1), Is.True, "Contains 1"); + Assert.That (st.Contains (v2), Is.False, "Contains 2"); } } @@ -99,8 +99,8 @@ public void ToArrayTest () using (var st = new NSMutableSet (v1)) { var arr = st.ToArray (); - Assert.AreEqual (1, arr.Length, "ToArray Length"); - Assert.AreSame (v1, arr [0], "ToArray () [0]"); + Assert.That (arr.Length, Is.EqualTo (1), "ToArray Length"); + Assert.That (arr [0], Is.SameAs (v1), "ToArray () [0]"); } } @@ -113,9 +113,9 @@ public void OperatorAddTest () using (var first = new NSMutableSet (v1)) { using (var second = new NSMutableSet (v2)) { using (var third = first + second) { - Assert.AreEqual ((nuint) 2, third.Count, "+ Count"); - Assert.IsTrue (third.Contains (v1), "+ 1"); - Assert.IsTrue (third.Contains (v2), "+ 2"); + Assert.That (third.Count, Is.EqualTo ((nuint) 2), "+ Count"); + Assert.That (third.Contains (v1), Is.True, "+ 1"); + Assert.That (third.Contains (v2), Is.True, "+ 2"); } } } @@ -130,8 +130,8 @@ public void OperatorSubtractTest () using (var first = new NSMutableSet (v1, v2)) { using (var second = new NSMutableSet (v2)) { using (var third = first - second) { - Assert.AreEqual ((nuint) 1, third.Count, "- Count"); - Assert.IsTrue (third.Contains (v1), "- 1"); + Assert.That (third.Count, Is.EqualTo ((nuint) 1), "- Count"); + Assert.That (third.Contains (v1), Is.True, "- 1"); } } } @@ -146,8 +146,8 @@ public void AddTest () Assert.Throws (() => st.Add ((NSString) null), "Add ANE 1"); st.Add (v1); - Assert.IsTrue (st.Contains (v1), "Add 1"); - Assert.AreSame (v1, st.AnyObject, "Add 2"); + Assert.That (st.Contains (v1), Is.True, "Add 1"); + Assert.That (st.AnyObject, Is.SameAs (v1), "Add 2"); } } @@ -161,12 +161,12 @@ public void RemoveTest () Assert.Throws (() => st.Remove ((NSString) null), "Remove ANE 1"); st.Remove (v2); - Assert.AreEqual ((nuint) 1, st.Count, "Remove 1 Count"); - Assert.IsTrue (st.Contains (v1), "Remove 1 Contains"); - Assert.AreSame (v1, st.AnyObject, "Remove 1 AnyObject"); + Assert.That (st.Count, Is.EqualTo ((nuint) 1), "Remove 1 Count"); + Assert.That (st.Contains (v1), Is.True, "Remove 1 Contains"); + Assert.That (st.AnyObject, Is.SameAs (v1), "Remove 1 AnyObject"); st.Remove (v1); - Assert.AreEqual ((nuint) 0, st.Count, "Remove 2 Count"); + Assert.That (st.Count, Is.EqualTo ((nuint) 0), "Remove 2 Count"); } } @@ -181,19 +181,19 @@ public void AddObjectsTest () Assert.Throws (() => st.AddObjects ((NSString []) null), "AddObjects ANE 2"); st.AddObjects (v1); - Assert.AreEqual ((nuint) 1, st.Count, "AddObjects 1 Count"); - Assert.IsTrue (st.Contains (v1), "AddObjects 1 Contains"); + Assert.That (st.Count, Is.EqualTo ((nuint) 1), "AddObjects 1 Count"); + Assert.That (st.Contains (v1), Is.True, "AddObjects 1 Contains"); st.RemoveAll (); st.AddObjects (v1, v1); - Assert.AreEqual ((nuint) 1, st.Count, "AddObjects 2 Count"); - Assert.IsTrue (st.Contains (v1), "AddObjects 2 Contains"); + Assert.That (st.Count, Is.EqualTo ((nuint) 1), "AddObjects 2 Count"); + Assert.That (st.Contains (v1), Is.True, "AddObjects 2 Contains"); st.RemoveAll (); st.AddObjects (v2, v1); - Assert.AreEqual ((nuint) 2, st.Count, "AddObjects 3 Count"); - Assert.IsTrue (st.Contains (v1), "AddObjects 3 Contains a"); - Assert.IsTrue (st.Contains (v2), "AddObjects 3 Contains b"); + Assert.That (st.Count, Is.EqualTo ((nuint) 2), "AddObjects 3 Count"); + Assert.That (st.Contains (v1), Is.True, "AddObjects 3 Contains a"); + Assert.That (st.Contains (v2), Is.True, "AddObjects 3 Contains b"); } } @@ -206,16 +206,16 @@ public void IEnumerable1Test () values [i] = (NSString) i.ToString (); using (var st = new NSMutableSet (values)) { - Assert.AreEqual ((nuint) C, st.Count, "Count 1"); + Assert.That (st.Count, Is.EqualTo ((nuint) C), "Count 1"); var lst = new List (); foreach (var a in (IEnumerable) st) { - Assert.IsNotNull (a, "null item iterator"); - Assert.IsFalse (lst.Contains (a), "duplicated item iterator"); + Assert.That (a, Is.Not.Null, "null item iterator"); + Assert.That (lst.Contains (a), Is.False, "duplicated item iterator"); lst.Add (a); - Assert.IsTrue (Array.IndexOf (values, a) >= 0, "different object"); + Assert.That (Array.IndexOf (values, a) >= 0, Is.True, "different object"); } - Assert.AreEqual (C, lst.Count, "iterator count"); + Assert.That (lst.Count, Is.EqualTo (C), "iterator count"); } } @@ -239,16 +239,16 @@ public void IEnumerableTest () values [i] = (NSString) i.ToString (); using (var st = new NSMutableSet (values)) { - Assert.AreEqual ((nuint) C, st.Count, "Count 1"); + Assert.That (st.Count, Is.EqualTo ((nuint) C), "Count 1"); var lst = new List (); foreach (NSString a in (IEnumerable) st) { - Assert.IsNotNull (a, "null item iterator"); - Assert.IsFalse (lst.Contains (a), "duplicated item iterator"); + Assert.That (a, Is.Not.Null, "null item iterator"); + Assert.That (lst.Contains (a), Is.False, "duplicated item iterator"); lst.Add (a); - Assert.IsTrue (Array.IndexOf (values, a) >= 0, "different object"); + Assert.That (Array.IndexOf (values, a) >= 0, Is.True, "different object"); } - Assert.AreEqual (C, lst.Count, "iterator count"); + Assert.That (lst.Count, Is.EqualTo (C), "iterator count"); } } @@ -263,8 +263,8 @@ public void OperatorPlusReferenceTest () using (var sum3 = one + two) { } - Assert.AreNotEqual (IntPtr.Zero, one.Handle, "Handle must be != IntPtr.Zero"); - Assert.AreNotEqual (IntPtr.Zero, two.Handle, "Handle must be != IntPtr.Zero"); + Assert.That (one.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); + Assert.That (two.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); } [Test] @@ -273,7 +273,7 @@ public void OperatorPlus_BothNull () NSMutableSet first = null; NSMutableSet second = null; var result = first + second; - Assert.IsNull (result, "Both null should return null"); + Assert.That (result, Is.Null, "Both null should return null"); } [Test] @@ -282,10 +282,10 @@ public void OperatorPlus_FirstNull () NSMutableSet first = null; using (var second = new NSMutableSet ((NSString) "1", (NSString) "2")) { using (var result = first + second) { - Assert.IsNotNull (result, "Result should not be null"); - Assert.AreEqual ((nuint) 2, result.Count, "Count"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Contains 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Contains 2"); + Assert.That (result, Is.Not.Null, "Result should not be null"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Contains 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Contains 2"); } } } @@ -296,10 +296,10 @@ public void OperatorPlus_SecondNull () using (var first = new NSMutableSet ((NSString) "1", (NSString) "2")) { NSMutableSet second = null; using (var result = first + second) { - Assert.IsNotNull (result, "Result should not be null"); - Assert.AreEqual ((nuint) 2, result.Count, "Count"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Contains 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Contains 2"); + Assert.That (result, Is.Not.Null, "Result should not be null"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Contains 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Contains 2"); } } } @@ -310,8 +310,8 @@ public void OperatorPlus_BothEmpty () using (var first = new NSMutableSet ()) using (var second = new NSMutableSet ()) using (var result = first + second) { - Assert.IsNotNull (result, "Result should not be null"); - Assert.AreEqual ((nuint) 0, result.Count, "Count should be 0"); + Assert.That (result, Is.Not.Null, "Result should not be null"); + Assert.That (result.Count, Is.EqualTo ((nuint) 0), "Count should be 0"); } } @@ -321,10 +321,10 @@ public void OperatorPlus_FirstEmpty () using (var first = new NSMutableSet ()) using (var second = new NSMutableSet ((NSString) "1", (NSString) "2")) using (var result = first + second) { - Assert.IsNotNull (result, "Result should not be null"); - Assert.AreEqual ((nuint) 2, result.Count, "Count"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Contains 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Contains 2"); + Assert.That (result, Is.Not.Null, "Result should not be null"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Contains 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Contains 2"); } } @@ -334,10 +334,10 @@ public void OperatorPlus_SecondEmpty () using (var first = new NSMutableSet ((NSString) "1", (NSString) "2")) using (var second = new NSMutableSet ()) using (var result = first + second) { - Assert.IsNotNull (result, "Result should not be null"); - Assert.AreEqual ((nuint) 2, result.Count, "Count"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Contains 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Contains 2"); + Assert.That (result, Is.Not.Null, "Result should not be null"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Contains 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Contains 2"); } } @@ -347,11 +347,11 @@ public void OperatorPlus_Overlapping () using (var first = new NSMutableSet ((NSString) "1", (NSString) "2")) using (var second = new NSMutableSet ((NSString) "2", (NSString) "3")) using (var result = first + second) { - Assert.IsNotNull (result, "Result should not be null"); - Assert.AreEqual ((nuint) 3, result.Count, "Count should be 3 (set union)"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Contains 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Contains 2"); - Assert.IsTrue (result.Contains ((NSString) "3"), "Contains 3"); + Assert.That (result, Is.Not.Null, "Result should not be null"); + Assert.That (result.Count, Is.EqualTo ((nuint) 3), "Count should be 3 (set union)"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Contains 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Contains 2"); + Assert.That (result.Contains ((NSString) "3"), Is.True, "Contains 3"); } } @@ -361,7 +361,7 @@ public void OperatorMinus_BothNull () NSMutableSet first = null; NSMutableSet second = null; var result = first - second; - Assert.IsNull (result, "Both null should return null"); + Assert.That (result, Is.Null, "Both null should return null"); } [Test] @@ -370,7 +370,7 @@ public void OperatorMinus_FirstNull () NSMutableSet first = null; using (var second = new NSMutableSet ((NSString) "1", (NSString) "2")) { var result = first - second; - Assert.IsNull (result, "First null should return null"); + Assert.That (result, Is.Null, "First null should return null"); } } @@ -380,10 +380,10 @@ public void OperatorMinus_SecondNull () using (var first = new NSMutableSet ((NSString) "1", (NSString) "2")) { NSMutableSet second = null; using (var result = first - second) { - Assert.IsNotNull (result, "Result should not be null"); - Assert.AreEqual ((nuint) 2, result.Count, "Count"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Contains 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Contains 2"); + Assert.That (result, Is.Not.Null, "Result should not be null"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Contains 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Contains 2"); } } } @@ -394,7 +394,7 @@ public void OperatorMinus_FirstEmpty () using (var first = new NSMutableSet ()) using (var second = new NSMutableSet ((NSString) "1", (NSString) "2")) { var result = first - second; - Assert.IsNull (result, "Empty first should return null"); + Assert.That (result, Is.Null, "Empty first should return null"); } } @@ -404,10 +404,10 @@ public void OperatorMinus_SecondEmpty () using (var first = new NSMutableSet ((NSString) "1", (NSString) "2")) using (var second = new NSMutableSet ()) using (var result = first - second) { - Assert.IsNotNull (result, "Result should not be null"); - Assert.AreEqual ((nuint) 2, result.Count, "Count"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Contains 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Contains 2"); + Assert.That (result, Is.Not.Null, "Result should not be null"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Contains 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Contains 2"); } } @@ -417,7 +417,7 @@ public void OperatorMinus_BothEmpty () using (var first = new NSMutableSet ()) using (var second = new NSMutableSet ()) { var result = first - second; - Assert.IsNull (result, "Both empty should return null"); + Assert.That (result, Is.Null, "Both empty should return null"); } } @@ -427,10 +427,10 @@ public void OperatorMinus_NoOverlap () using (var first = new NSMutableSet ((NSString) "1", (NSString) "2")) using (var second = new NSMutableSet ((NSString) "3", (NSString) "4")) using (var result = first - second) { - Assert.IsNotNull (result, "Result should not be null"); - Assert.AreEqual ((nuint) 2, result.Count, "Count"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Contains 1"); - Assert.IsTrue (result.Contains ((NSString) "2"), "Contains 2"); + Assert.That (result, Is.Not.Null, "Result should not be null"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Contains 1"); + Assert.That (result.Contains ((NSString) "2"), Is.True, "Contains 2"); } } @@ -440,11 +440,11 @@ public void OperatorMinus_PartialOverlap () using (var first = new NSMutableSet ((NSString) "1", (NSString) "2", (NSString) "3")) using (var second = new NSMutableSet ((NSString) "2", (NSString) "4")) using (var result = first - second) { - Assert.IsNotNull (result, "Result should not be null"); - Assert.AreEqual ((nuint) 2, result.Count, "Count"); - Assert.IsTrue (result.Contains ((NSString) "1"), "Contains 1"); - Assert.IsTrue (result.Contains ((NSString) "3"), "Contains 3"); - Assert.IsFalse (result.Contains ((NSString) "2"), "Should not contain 2"); + Assert.That (result, Is.Not.Null, "Result should not be null"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "Count"); + Assert.That (result.Contains ((NSString) "1"), Is.True, "Contains 1"); + Assert.That (result.Contains ((NSString) "3"), Is.True, "Contains 3"); + Assert.That (result.Contains ((NSString) "2"), Is.False, "Should not contain 2"); } } @@ -454,8 +454,8 @@ public void OperatorMinus_CompleteOverlap () using (var first = new NSMutableSet ((NSString) "1", (NSString) "2")) using (var second = new NSMutableSet ((NSString) "1", (NSString) "2")) using (var result = first - second) { - Assert.IsNotNull (result, "Result should not be null"); - Assert.AreEqual ((nuint) 0, result.Count, "Count should be 0"); + Assert.That (result, Is.Not.Null, "Result should not be null"); + Assert.That (result.Count, Is.EqualTo ((nuint) 0), "Count should be 0"); } } @@ -463,7 +463,7 @@ public void OperatorMinus_CompleteOverlap () public void Ctor_Capacity () { using (var set = new NSMutableSet (10)) { - Assert.AreEqual ((nuint) 0, set.Count, "Empty with capacity"); + Assert.That (set.Count, Is.EqualTo ((nuint) 0), "Empty with capacity"); } } @@ -472,8 +472,8 @@ public void ToArray_Empty () { using (var set = new NSMutableSet ()) { var arr = set.ToArray (); - Assert.IsNotNull (arr, "Array should not be null"); - Assert.AreEqual (0, arr.Length, "Length should be 0"); + Assert.That (arr, Is.Not.Null, "Array should not be null"); + Assert.That (arr.Length, Is.EqualTo (0), "Length should be 0"); } } @@ -486,10 +486,10 @@ public void ToArray_Multiple () using (var set = new NSMutableSet (v1, v2, v3)) { var arr = set.ToArray (); - Assert.AreEqual (3, arr.Length, "Length"); - Assert.Contains (v1, arr, "Contains v1"); - Assert.Contains (v2, arr, "Contains v2"); - Assert.Contains (v3, arr, "Contains v3"); + Assert.That (arr.Length, Is.EqualTo (3), "Length"); + Assert.That (arr, Has.Member (v1), "Contains v1"); + Assert.That (arr, Has.Member (v2), "Contains v2"); + Assert.That (arr, Has.Member (v3), "Contains v3"); } } @@ -500,10 +500,10 @@ public void Add_Duplicate () using (var set = new NSMutableSet ()) { set.Add (v1); - Assert.AreEqual ((nuint) 1, set.Count, "Count after first add"); + Assert.That (set.Count, Is.EqualTo ((nuint) 1), "Count after first add"); set.Add (v1); - Assert.AreEqual ((nuint) 1, set.Count, "Count after duplicate add"); + Assert.That (set.Count, Is.EqualTo ((nuint) 1), "Count after duplicate add"); } } @@ -515,8 +515,8 @@ public void Remove_NonExistent () using (var set = new NSMutableSet (v1)) { set.Remove (v2); - Assert.AreEqual ((nuint) 1, set.Count, "Count should remain 1"); - Assert.IsTrue (set.Contains (v1), "Should still contain v1"); + Assert.That (set.Count, Is.EqualTo ((nuint) 1), "Count should remain 1"); + Assert.That (set.Contains (v1), Is.True, "Should still contain v1"); } } @@ -525,7 +525,7 @@ public void AddObjects_Empty () { using (var set = new NSMutableSet ()) { set.AddObjects (); - Assert.AreEqual ((nuint) 0, set.Count, "Count should be 0"); + Assert.That (set.Count, Is.EqualTo ((nuint) 0), "Count should be 0"); } } @@ -546,7 +546,7 @@ public void LookupMember_Empty () using (var set = new NSMutableSet ()) { var result = set.LookupMember (v1); - Assert.IsNull (result, "Should return null for empty set"); + Assert.That (result, Is.Null, "Should return null for empty set"); } } @@ -556,7 +556,7 @@ public void Contains_Empty () var v1 = (NSString) "1"; using (var set = new NSMutableSet ()) { - Assert.IsFalse (set.Contains (v1), "Empty set should not contain any element"); + Assert.That (set.Contains (v1), Is.False, "Empty set should not contain any element"); } } @@ -568,7 +568,7 @@ public void Enumeration_Empty () foreach (var item in set) { count++; } - Assert.AreEqual (0, count, "Should not enumerate any items"); + Assert.That (count, Is.EqualTo (0), "Should not enumerate any items"); } } @@ -584,8 +584,8 @@ public void Enumeration_Single () count++; found = item; } - Assert.AreEqual (1, count, "Should enumerate one item"); - Assert.AreSame (v1, found, "Should find v1"); + Assert.That (count, Is.EqualTo (1), "Should enumerate one item"); + Assert.That (found, Is.SameAs (v1), "Should find v1"); } } @@ -593,7 +593,7 @@ public void Enumeration_Single () public void Ctor_Params_Empty () { using (var set = new NSMutableSet ()) { - Assert.AreEqual ((nuint) 0, set.Count, "Empty params"); + Assert.That (set.Count, Is.EqualTo ((nuint) 0), "Empty params"); } } } diff --git a/tests/monotouch-test/Foundation/NSMutableSetTest.cs b/tests/monotouch-test/Foundation/NSMutableSetTest.cs index cadef860d89e..943e0613fb65 100644 --- a/tests/monotouch-test/Foundation/NSMutableSetTest.cs +++ b/tests/monotouch-test/Foundation/NSMutableSetTest.cs @@ -24,10 +24,10 @@ public void OperatorAddTest () using (var set1 = new NSMutableSet (str1)) using (var set2 = new NSMutableSet (str2, str3)) using (var result = set1 + set2) { - Assert.AreEqual ((nuint) 3, result.Count, "AddTest Count"); - Assert.IsTrue (result.Contains (str1), "AddTest Contains 1"); - Assert.IsTrue (result.Contains (str2), "AddTest Contains 2"); - Assert.IsTrue (result.Contains (str3), "AddTest Contains 3"); + Assert.That (result.Count, Is.EqualTo ((nuint) 3), "AddTest Count"); + Assert.That (result.Contains (str1), Is.True, "AddTest Contains 1"); + Assert.That (result.Contains (str2), Is.True, "AddTest Contains 2"); + Assert.That (result.Contains (str3), Is.True, "AddTest Contains 3"); } } @@ -43,11 +43,11 @@ public void OperatorSubtractTest () var second = new NSMutableSet (str3, str4); var third = first - second; - Assert.AreEqual ((nuint) 2, third.Count, "OperatorSubtract Count"); - Assert.IsTrue (third.Contains (str1), "OperatorSubtract 1"); - Assert.IsTrue (third.Contains (str2), "OperatorSubtract 2"); - Assert.IsFalse (third.Contains (str3), "OperatorSubtract 3"); - Assert.IsFalse (third.Contains (str4), "OperatorSubtract 4"); + Assert.That (third.Count, Is.EqualTo ((nuint) 2), "OperatorSubtract Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorSubtract 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorSubtract 2"); + Assert.That (third.Contains (str3), Is.False, "OperatorSubtract 3"); + Assert.That (third.Contains (str4), Is.False, "OperatorSubtract 4"); } [Test] @@ -61,8 +61,8 @@ public void OperatorPlusReferenceTest () using (var sum3 = one + two) { } - Assert.AreNotEqual (IntPtr.Zero, one.Handle, "Handle must be != IntPtr.Zero"); - Assert.AreNotEqual (IntPtr.Zero, two.Handle, "Handle must be != IntPtr.Zero"); + Assert.That (one.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); + Assert.That (two.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); } [Test] @@ -71,7 +71,7 @@ public void OperatorAdd_BothNull () NSMutableSet first = null; NSMutableSet second = null; var result = first + second; - Assert.IsNull (result, "BothNull should return null"); + Assert.That (result, Is.Null, "BothNull should return null"); } [Test] @@ -80,10 +80,10 @@ public void OperatorAdd_FirstNull_SecondNonEmpty () NSMutableSet first = null; using (var second = new NSMutableSet ("1", "2")) using (var result = first + second) { - Assert.IsNotNull (result, "FirstNull should return new set"); - Assert.AreEqual ((nuint) 2, result.Count, "FirstNull Count"); - Assert.IsTrue (result.Contains ("1"), "FirstNull Contains 1"); - Assert.IsTrue (result.Contains ("2"), "FirstNull Contains 2"); + Assert.That (result, Is.Not.Null, "FirstNull should return new set"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "FirstNull Count"); + Assert.That (result.Contains ("1"), Is.True, "FirstNull Contains 1"); + Assert.That (result.Contains ("2"), Is.True, "FirstNull Contains 2"); } } @@ -93,8 +93,8 @@ public void OperatorAdd_FirstNull_SecondEmpty () NSMutableSet first = null; using (var second = new NSMutableSet ()) using (var result = first + second) { - Assert.IsNotNull (result, "FirstNull SecondEmpty should return new set"); - Assert.AreEqual ((nuint) 0, result.Count, "FirstNull SecondEmpty Count"); + Assert.That (result, Is.Not.Null, "FirstNull SecondEmpty should return new set"); + Assert.That (result.Count, Is.EqualTo ((nuint) 0), "FirstNull SecondEmpty Count"); } } @@ -103,10 +103,10 @@ public void OperatorAdd_FirstNonEmpty_SecondNull () { using (var first = new NSMutableSet ("1", "2")) using (var result = first + null) { - Assert.IsNotNull (result, "SecondNull should return new set"); - Assert.AreEqual ((nuint) 2, result.Count, "SecondNull Count"); - Assert.IsTrue (result.Contains ("1"), "SecondNull Contains 1"); - Assert.IsTrue (result.Contains ("2"), "SecondNull Contains 2"); + Assert.That (result, Is.Not.Null, "SecondNull should return new set"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "SecondNull Count"); + Assert.That (result.Contains ("1"), Is.True, "SecondNull Contains 1"); + Assert.That (result.Contains ("2"), Is.True, "SecondNull Contains 2"); } } @@ -115,8 +115,8 @@ public void OperatorAdd_FirstEmpty_SecondNull () { using (var first = new NSMutableSet ()) using (var result = first + null) { - Assert.IsNotNull (result, "FirstEmpty SecondNull should return new set"); - Assert.AreEqual ((nuint) 0, result.Count, "FirstEmpty SecondNull Count"); + Assert.That (result, Is.Not.Null, "FirstEmpty SecondNull should return new set"); + Assert.That (result.Count, Is.EqualTo ((nuint) 0), "FirstEmpty SecondNull Count"); } } @@ -126,10 +126,10 @@ public void OperatorAdd_FirstEmpty_SecondNonEmpty () using (var first = new NSMutableSet ()) using (var second = new NSMutableSet ("1", "2")) using (var result = first + second) { - Assert.IsNotNull (result, "FirstEmpty should return copy of second"); - Assert.AreEqual ((nuint) 2, result.Count, "FirstEmpty Count"); - Assert.IsTrue (result.Contains ("1"), "FirstEmpty Contains 1"); - Assert.IsTrue (result.Contains ("2"), "FirstEmpty Contains 2"); + Assert.That (result, Is.Not.Null, "FirstEmpty should return copy of second"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "FirstEmpty Count"); + Assert.That (result.Contains ("1"), Is.True, "FirstEmpty Contains 1"); + Assert.That (result.Contains ("2"), Is.True, "FirstEmpty Contains 2"); } } @@ -139,10 +139,10 @@ public void OperatorAdd_FirstNonEmpty_SecondEmpty () using (var first = new NSMutableSet ("1", "2")) using (var second = new NSMutableSet ()) using (var result = first + second) { - Assert.IsNotNull (result, "SecondEmpty should return copy of first"); - Assert.AreEqual ((nuint) 2, result.Count, "SecondEmpty Count"); - Assert.IsTrue (result.Contains ("1"), "SecondEmpty Contains 1"); - Assert.IsTrue (result.Contains ("2"), "SecondEmpty Contains 2"); + Assert.That (result, Is.Not.Null, "SecondEmpty should return copy of first"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "SecondEmpty Count"); + Assert.That (result.Contains ("1"), Is.True, "SecondEmpty Contains 1"); + Assert.That (result.Contains ("2"), Is.True, "SecondEmpty Contains 2"); } } @@ -152,8 +152,8 @@ public void OperatorAdd_BothEmpty () using (var first = new NSMutableSet ()) using (var second = new NSMutableSet ()) using (var result = first + second) { - Assert.IsNotNull (result, "BothEmpty should return new empty set"); - Assert.AreEqual ((nuint) 0, result.Count, "BothEmpty Count"); + Assert.That (result, Is.Not.Null, "BothEmpty should return new empty set"); + Assert.That (result.Count, Is.EqualTo ((nuint) 0), "BothEmpty Count"); } } @@ -163,12 +163,12 @@ public void OperatorAdd_WithOverlappingElements () using (var first = new NSMutableSet ("1", "2", "3")) using (var second = new NSMutableSet ("2", "3", "4")) using (var result = first + second) { - Assert.IsNotNull (result, "Overlapping should return new set"); - Assert.AreEqual ((nuint) 4, result.Count, "Overlapping Count"); - Assert.IsTrue (result.Contains ("1"), "Overlapping Contains 1"); - Assert.IsTrue (result.Contains ("2"), "Overlapping Contains 2"); - Assert.IsTrue (result.Contains ("3"), "Overlapping Contains 3"); - Assert.IsTrue (result.Contains ("4"), "Overlapping Contains 4"); + Assert.That (result, Is.Not.Null, "Overlapping should return new set"); + Assert.That (result.Count, Is.EqualTo ((nuint) 4), "Overlapping Count"); + Assert.That (result.Contains ("1"), Is.True, "Overlapping Contains 1"); + Assert.That (result.Contains ("2"), Is.True, "Overlapping Contains 2"); + Assert.That (result.Contains ("3"), Is.True, "Overlapping Contains 3"); + Assert.That (result.Contains ("4"), Is.True, "Overlapping Contains 4"); } } @@ -178,7 +178,7 @@ public void OperatorSubtract_FirstNull () NSMutableSet first = null; using (var second = new NSMutableSet ("1", "2")) { var result = first - second; - Assert.IsNull (result, "FirstNull should return null"); + Assert.That (result, Is.Null, "FirstNull should return null"); } } @@ -187,10 +187,10 @@ public void OperatorSubtract_SecondNull () { using (var first = new NSMutableSet ("1", "2")) using (var result = first - null) { - Assert.IsNotNull (result, "SecondNull should return copy of first"); - Assert.AreEqual ((nuint) 2, result.Count, "SecondNull Count"); - Assert.IsTrue (result.Contains ("1"), "SecondNull Contains 1"); - Assert.IsTrue (result.Contains ("2"), "SecondNull Contains 2"); + Assert.That (result, Is.Not.Null, "SecondNull should return copy of first"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "SecondNull Count"); + Assert.That (result.Contains ("1"), Is.True, "SecondNull Contains 1"); + Assert.That (result.Contains ("2"), Is.True, "SecondNull Contains 2"); } } @@ -200,7 +200,7 @@ public void OperatorSubtract_BothNull () NSMutableSet first = null; NSMutableSet second = null; var result = first - second; - Assert.IsNull (result, "BothNull should return null"); + Assert.That (result, Is.Null, "BothNull should return null"); } [Test] @@ -209,8 +209,8 @@ public void OperatorSubtract_FirstEmpty () using (var first = new NSMutableSet ()) using (var second = new NSMutableSet ("1", "2")) using (var result = first - second) { - Assert.IsNotNull (result, "FirstEmpty should return empty set"); - Assert.AreEqual ((nuint) 0, result.Count, "FirstEmpty Count"); + Assert.That (result, Is.Not.Null, "FirstEmpty should return empty set"); + Assert.That (result.Count, Is.EqualTo ((nuint) 0), "FirstEmpty Count"); } } @@ -220,10 +220,10 @@ public void OperatorSubtract_SecondEmpty () using (var first = new NSMutableSet ("1", "2")) using (var second = new NSMutableSet ()) using (var result = first - second) { - Assert.IsNotNull (result, "SecondEmpty should return copy of first"); - Assert.AreEqual ((nuint) 2, result.Count, "SecondEmpty Count"); - Assert.IsTrue (result.Contains ("1"), "SecondEmpty Contains 1"); - Assert.IsTrue (result.Contains ("2"), "SecondEmpty Contains 2"); + Assert.That (result, Is.Not.Null, "SecondEmpty should return copy of first"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "SecondEmpty Count"); + Assert.That (result.Contains ("1"), Is.True, "SecondEmpty Contains 1"); + Assert.That (result.Contains ("2"), Is.True, "SecondEmpty Contains 2"); } } @@ -233,8 +233,8 @@ public void OperatorSubtract_BothEmpty () using (var first = new NSMutableSet ()) using (var second = new NSMutableSet ()) using (var result = first - second) { - Assert.IsNotNull (result, "BothEmpty should return empty set"); - Assert.AreEqual ((nuint) 0, result.Count, "BothEmpty Count"); + Assert.That (result, Is.Not.Null, "BothEmpty should return empty set"); + Assert.That (result.Count, Is.EqualTo ((nuint) 0), "BothEmpty Count"); } } @@ -244,10 +244,10 @@ public void OperatorSubtract_NoOverlap () using (var first = new NSMutableSet ("1", "2")) using (var second = new NSMutableSet ("3", "4")) using (var result = first - second) { - Assert.IsNotNull (result, "NoOverlap should return copy of first"); - Assert.AreEqual ((nuint) 2, result.Count, "NoOverlap Count"); - Assert.IsTrue (result.Contains ("1"), "NoOverlap Contains 1"); - Assert.IsTrue (result.Contains ("2"), "NoOverlap Contains 2"); + Assert.That (result, Is.Not.Null, "NoOverlap should return copy of first"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "NoOverlap Count"); + Assert.That (result.Contains ("1"), Is.True, "NoOverlap Contains 1"); + Assert.That (result.Contains ("2"), Is.True, "NoOverlap Contains 2"); } } @@ -257,11 +257,11 @@ public void OperatorSubtract_PartialOverlap () using (var first = new NSMutableSet ("1", "2", "3")) using (var second = new NSMutableSet ("2", "3", "4")) using (var result = first - second) { - Assert.IsNotNull (result, "PartialOverlap should return difference"); - Assert.AreEqual ((nuint) 1, result.Count, "PartialOverlap Count"); - Assert.IsTrue (result.Contains ("1"), "PartialOverlap Contains 1"); - Assert.IsFalse (result.Contains ("2"), "PartialOverlap Not Contains 2"); - Assert.IsFalse (result.Contains ("3"), "PartialOverlap Not Contains 3"); + Assert.That (result, Is.Not.Null, "PartialOverlap should return difference"); + Assert.That (result.Count, Is.EqualTo ((nuint) 1), "PartialOverlap Count"); + Assert.That (result.Contains ("1"), Is.True, "PartialOverlap Contains 1"); + Assert.That (result.Contains ("2"), Is.False, "PartialOverlap Not Contains 2"); + Assert.That (result.Contains ("3"), Is.False, "PartialOverlap Not Contains 3"); } } @@ -271,8 +271,8 @@ public void OperatorSubtract_CompleteOverlap () using (var first = new NSMutableSet ("1", "2", "3")) using (var second = new NSMutableSet ("1", "2", "3")) using (var result = first - second) { - Assert.IsNotNull (result, "CompleteOverlap should return empty set"); - Assert.AreEqual ((nuint) 0, result.Count, "CompleteOverlap Count"); + Assert.That (result, Is.Not.Null, "CompleteOverlap should return empty set"); + Assert.That (result.Count, Is.EqualTo ((nuint) 0), "CompleteOverlap Count"); } } @@ -282,8 +282,8 @@ public void OperatorSubtract_SecondIsSupersetOfFirst () using (var first = new NSMutableSet ("1", "2")) using (var second = new NSMutableSet ("1", "2", "3", "4")) using (var result = first - second) { - Assert.IsNotNull (result, "Superset should return empty set"); - Assert.AreEqual ((nuint) 0, result.Count, "Superset Count"); + Assert.That (result, Is.Not.Null, "Superset should return empty set"); + Assert.That (result.Count, Is.EqualTo ((nuint) 0), "Superset Count"); } } @@ -293,9 +293,9 @@ public void Ctor_WithNull () var str1 = (NSString) "1"; NSObject? nullObj = null; using (var set = new NSMutableSet (str1, nullObj)) { - Assert.AreEqual ((nuint) 2, set.Count, "Count should include null"); - Assert.IsTrue (set.Contains (str1), "Should contain string"); - Assert.IsTrue (set.Contains (NSNull.Null), "Should contain NSNull"); + Assert.That (set.Count, Is.EqualTo ((nuint) 2), "Count should include null"); + Assert.That (set.Contains (str1), Is.True, "Should contain string"); + Assert.That (set.Contains (NSNull.Null), Is.True, "Should contain NSNull"); } } @@ -304,7 +304,7 @@ public void Ctor_NullArray () { NSObject []? objs = null; using (var set = new NSMutableSet (objs)) { - Assert.AreEqual ((nuint) 0, set.Count, "Null array should create empty set"); + Assert.That (set.Count, Is.EqualTo ((nuint) 0), "Null array should create empty set"); } } } diff --git a/tests/monotouch-test/Foundation/NSObject.cs b/tests/monotouch-test/Foundation/NSObject.cs index 7aa7066760d3..5dbf5c197c52 100644 --- a/tests/monotouch-test/Foundation/NSObject.cs +++ b/tests/monotouch-test/Foundation/NSObject.cs @@ -14,7 +14,7 @@ public void NSObjectTests_InvokeTest () bool hit = false; NSApplication.SharedApplication.Invoke (() => hit = true, 1); TestRuntime.RunAsync (TimeSpan.FromSeconds (10), () => { }, () => hit); - Assert.IsTrue (hit, "Did not see events after 10 seconds"); + Assert.That (hit, Is.True, "Did not see events after 10 seconds"); } } } diff --git a/tests/monotouch-test/Foundation/NSObjectGCTest.cs b/tests/monotouch-test/Foundation/NSObjectGCTest.cs index a089a926fd97..2b9c5e6663b3 100644 --- a/tests/monotouch-test/Foundation/NSObjectGCTest.cs +++ b/tests/monotouch-test/Foundation/NSObjectGCTest.cs @@ -27,13 +27,13 @@ public void NSObject_GCResurrectTest () // and so `GCHandle` will return its reference: var o = ObjCRuntime.Runtime.GetNSObject (nativeHandle); - Assert.AreNotEqual (IntPtr.Zero, (IntPtr) o.Handle); + Assert.That ((IntPtr) o.Handle, Is.Not.EqualTo (IntPtr.Zero)); // Pump the run loop and thus drain the NSObject_Disposer PumpLoop (); // The object is invalid now - Assert.AreNotEqual (IntPtr.Zero, (IntPtr) o.Handle); + Assert.That ((IntPtr) o.Handle, Is.Not.EqualTo (IntPtr.Zero)); } [System.Runtime.CompilerServices.MethodImpl (System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] diff --git a/tests/monotouch-test/Foundation/NSOperatingSystemVersionTest.cs b/tests/monotouch-test/Foundation/NSOperatingSystemVersionTest.cs index 46c8c78992f2..0702a25c2602 100644 --- a/tests/monotouch-test/Foundation/NSOperatingSystemVersionTest.cs +++ b/tests/monotouch-test/Foundation/NSOperatingSystemVersionTest.cs @@ -24,9 +24,9 @@ public class NSOperatingSystemVersionTest { [Test, TestCaseSource ("VersionCasesEqual")] public void NSVersionEqual ((NSOperatingSystemVersion v1, NSOperatingSystemVersion v2, bool res) sample) { - Assert.AreEqual (sample.v1 == sample.v2, sample.res, $"{sample.v1}=={sample.v2}"); - Assert.AreEqual (sample.v2 == sample.v1, sample.res, $"{sample.v2}=={sample.v1}"); - Assert.AreNotEqual (sample.v1 != sample.v2, sample.res, $"{sample.v1}!={sample.v2}"); + Assert.That (sample.res, Is.EqualTo (sample.v1 == sample.v2), $"{sample.v1}=={sample.v2}"); + Assert.That (sample.res, Is.EqualTo (sample.v2 == sample.v1), $"{sample.v2}=={sample.v1}"); + Assert.That (sample.res, Is.Not.EqualTo (sample.v1 != sample.v2), $"{sample.v1}!={sample.v2}"); } // Object Equal Tests @@ -44,7 +44,7 @@ public void NSVersionEqual ((NSOperatingSystemVersion v1, NSOperatingSystemVersi public void NSVersionObject ((Object obj, bool res) sample) { NSOperatingSystemVersion v1 = new NSOperatingSystemVersion ((nint) 1, (nint) 2, (nint) 3); - Assert.AreEqual (v1.Equals (sample.obj), sample.res); + Assert.That (sample.res, Is.EqualTo (v1.Equals (sample.obj))); } // Object Compare Tests @@ -62,7 +62,7 @@ public void NSVersionObject ((Object obj, bool res) sample) public void NSVersionCompareObject ((Object obj, int result) sample) { NSOperatingSystemVersion v1 = new NSOperatingSystemVersion ((nint) 1, (nint) 2, (nint) 3); - Assert.AreEqual (v1.CompareTo (sample.obj), sample.result); + Assert.That (sample.result, Is.EqualTo (v1.CompareTo (sample.obj))); } // Hash Tests @@ -78,7 +78,7 @@ public static IEnumerable VersionCasesHashCode { [Test, TestCaseSource ("VersionCasesHashCode")] public void NSVersionHashCode (NSOperatingSystemVersion version) - => Assert.AreEqual (version.GetHashCode (), version.GetHashCode ()); + => Assert.That (version.GetHashCode (), Is.EqualTo (version.GetHashCode ())); // ToString Tests @@ -94,7 +94,7 @@ public void NSVersionHashCode (NSOperatingSystemVersion version) [Test, TestCaseSource ("VersionCasesString")] public void NSVersionToString ((NSOperatingSystemVersion version, string versionStr) sample) - => Assert.AreEqual (sample.version.ToString (), sample.versionStr); + => Assert.That (sample.versionStr, Is.EqualTo (sample.version.ToString ())); // ICompare Tests @@ -110,7 +110,7 @@ public void NSVersionToString ((NSOperatingSystemVersion version, string version [Test, TestCaseSource ("VersionCasesCompare")] public void NSVersionCompare ((NSOperatingSystemVersion v1, NSOperatingSystemVersion v2, int res) sample) - => Assert.AreEqual (sample.v1.CompareTo (sample.v2), sample.res); + => Assert.That (sample.res, Is.EqualTo (sample.v1.CompareTo (sample.v2))); } } diff --git a/tests/monotouch-test/Foundation/NSOrderedCollectionChange1Test.cs b/tests/monotouch-test/Foundation/NSOrderedCollectionChange1Test.cs index 01003fb13bce..026bb49d576f 100644 --- a/tests/monotouch-test/Foundation/NSOrderedCollectionChange1Test.cs +++ b/tests/monotouch-test/Foundation/NSOrderedCollectionChange1Test.cs @@ -12,8 +12,8 @@ public void ChangeWithObjectTest () var str = new NSString ("Test"); var change = NSOrderedCollectionChange.ChangeWithObject (str, NSCollectionChangeType.Insert, 0); - Assert.AreEqual (str, change.Object, "Content"); - Assert.AreEqual ((nuint)0, change.Index, "Index"); + Assert.That (change.Object, Is.EqualTo (str), "Content"); + Assert.That (change.Index, Is.EqualTo ((nuint)0), "Index"); } [Test] @@ -23,9 +23,9 @@ public void ChangeWithObjectWithAssociatedIndexTest () var str = new NSString ("Test"); var change = NSOrderedCollectionChange.ChangeWithObject (str, NSCollectionChangeType.Insert, 0, 1); - Assert.AreEqual (str, change.Object, "Content"); - Assert.AreEqual ((nuint)0, change.Index, "Index"); - Assert.AreEqual ((nuint)1, change.AssociatedIndex); + Assert.That (change.Object, Is.EqualTo (str), "Content"); + Assert.That (change.Index, Is.EqualTo ((nuint)0), "Index"); + Assert.That (change.AssociatedIndex, Is.EqualTo ((nuint)1)); } } #endif diff --git a/tests/monotouch-test/Foundation/NSOrderedCollectionChangeTest.cs b/tests/monotouch-test/Foundation/NSOrderedCollectionChangeTest.cs index 00bf56165d6c..dd849bfe5f06 100644 --- a/tests/monotouch-test/Foundation/NSOrderedCollectionChangeTest.cs +++ b/tests/monotouch-test/Foundation/NSOrderedCollectionChangeTest.cs @@ -12,8 +12,8 @@ public void ChangeWithObjectTest () using var str = new NSString ("Test"); using var change = NSOrderedCollectionChange.ChangeWithObject (str, NSCollectionChangeType.Insert, 0); - Assert.AreEqual (str, change.Object, "Content"); - Assert.AreEqual ((nuint)0, change.Index, "Index"); + Assert.That (change.Object, Is.EqualTo (str), "Content"); + Assert.That (change.Index, Is.EqualTo ((nuint)0), "Index"); } [Test] @@ -23,9 +23,9 @@ public void ChangeWithObjectTestWithAssociatedindex () using var str = new NSString ("Test"); using var change = NSOrderedCollectionChange.ChangeWithObject (str, NSCollectionChangeType.Insert, 0, 1); - Assert.AreEqual (str, change.Object, "Content"); - Assert.AreEqual ((nuint)0, change.Index, "Index"); - Assert.AreEqual ((nuint)1, change.AssociatedIndex); + Assert.That (change.Object, Is.EqualTo (str), "Content"); + Assert.That (change.Index, Is.EqualTo ((nuint)0), "Index"); + Assert.That (change.AssociatedIndex, Is.EqualTo ((nuint)1)); } } #endif diff --git a/tests/monotouch-test/Foundation/NSOrderedCollectionDifference1Test.cs b/tests/monotouch-test/Foundation/NSOrderedCollectionDifference1Test.cs index b8a219144530..b39a13f95260 100644 --- a/tests/monotouch-test/Foundation/NSOrderedCollectionDifference1Test.cs +++ b/tests/monotouch-test/Foundation/NSOrderedCollectionDifference1Test.cs @@ -21,7 +21,7 @@ public void InsertionsAndRemovalsTest () }); // https://github.com/dotnet/macios/issues/15577 - Did not rewrite tests that were disabled // Any reason for not asserting on the returned value? - // Assert.AreEqual (1, diff.Insertions.Length, "insertions"); + // Assert.That (diff.Insertions.Length, Is.EqualTo (1), "insertions"); // (or whatever it's supposed to return) } } diff --git a/tests/monotouch-test/Foundation/NSOrderedCollectionDifferenceTest.cs b/tests/monotouch-test/Foundation/NSOrderedCollectionDifferenceTest.cs index 472a40935675..69018a4dafc1 100644 --- a/tests/monotouch-test/Foundation/NSOrderedCollectionDifferenceTest.cs +++ b/tests/monotouch-test/Foundation/NSOrderedCollectionDifferenceTest.cs @@ -21,7 +21,7 @@ public void InsertionsAndRemovalsTest () }); // https://github.com/dotnet/macios/issues/15577 - Did not rewrite tests that were disabled // Any reason for not asserting on the returned value? - // Assert.AreEqual (1, diff.Insertions.Length, "insertions"); + // Assert.That (diff.Insertions.Length, Is.EqualTo (1), "insertions"); // (or whatever it's supposed to return) } } diff --git a/tests/monotouch-test/Foundation/NSOrderedSet1Test.cs b/tests/monotouch-test/Foundation/NSOrderedSet1Test.cs index 1224f1bf823b..bc8029bf108d 100644 --- a/tests/monotouch-test/Foundation/NSOrderedSet1Test.cs +++ b/tests/monotouch-test/Foundation/NSOrderedSet1Test.cs @@ -21,7 +21,7 @@ public void Ctor () { var oset = new NSOrderedSet (); - Assert.AreEqual ((nint) 0, oset.Count, "NSOrderedSet1Test Count"); + Assert.That (oset.Count, Is.EqualTo ((nint) 0), "NSOrderedSet1Test Count"); } [Test] @@ -29,7 +29,7 @@ public void Ctor_Start () { var oSet = new NSOrderedSet (start: (NSString) "foo"); - Assert.AreEqual ((nint) 1, oSet.Count, "NSOrderedSet1Test Count"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 1), "NSOrderedSet1Test Count"); } [Test] @@ -37,7 +37,7 @@ public void Ctor_Params () { var oSet = new NSOrderedSet ((NSString) "foo", (NSString) "bar", (NSString) "xyz"); - Assert.AreEqual ((nint) 3, oSet.Count, "NSOrderedSet1Test Count"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "NSOrderedSet1Test Count"); } [Test] @@ -46,7 +46,7 @@ public void Ctor_NSSet () var set = new NSSet ((NSString) "foo", (NSString) "bar", (NSString) "xyz"); var oSet = new NSOrderedSet (set); - Assert.AreEqual ((nint) set.Count, oSet.Count, "NSOrderedSet1Test Count"); + Assert.That (oSet.Count, Is.EqualTo ((nint) set.Count), "NSOrderedSet1Test Count"); } [Test] @@ -55,7 +55,7 @@ public void Ctor_NSOrderedSet () var oSetSource = new NSOrderedSet ((NSString) "foo", (NSString) "bar", (NSString) "xyz"); var oSet = new NSOrderedSet (oSetSource); - Assert.AreEqual ((nint) oSetSource.Count, oSet.Count, "NSOrderedSet1Test Count"); + Assert.That (oSet.Count, Is.EqualTo ((nint) oSetSource.Count), "NSOrderedSet1Test Count"); } [Test] @@ -64,7 +64,7 @@ public void Ctor_NSMutableOrderedSet () var oMutableSet = new NSMutableOrderedSet ((NSString) "foo", (NSString) "bar", (NSString) "xyz"); var oSet = new NSOrderedSet (oMutableSet); - Assert.AreEqual (oMutableSet.Count, oSet.Count, "NSOrderedSet1Test Count"); + Assert.That (oSet.Count, Is.EqualTo (oMutableSet.Count), "NSOrderedSet1Test Count"); } [Test] @@ -75,8 +75,8 @@ public void IndexerTest () var str3 = (NSString) "3"; var oSet = new NSOrderedSet (str1, str2, str3); - Assert.AreEqual ((nint) 3, oSet.Count, "NSOrderedSet1Test Count"); - Assert.AreSame (str2, oSet [1], "NSOrderedSet1Test IndexOf"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "NSOrderedSet1Test Count"); + Assert.That (oSet [1], Is.SameAs (str2), "NSOrderedSet1Test IndexOf"); } [Test] @@ -86,8 +86,8 @@ public void ToArrayTest () var oSet = new NSOrderedSet (str); var arr = oSet.ToArray (); - Assert.AreEqual (1, arr.Length, "NSOrderedSet1Test ToArray Length"); - Assert.AreSame (str, arr [0], "NSOrderedSet1Test ToArray () [0]"); + Assert.That (arr.Length, Is.EqualTo (1), "NSOrderedSet1Test ToArray Length"); + Assert.That (arr [0], Is.SameAs (str), "NSOrderedSet1Test ToArray () [0]"); } [Test] @@ -98,8 +98,8 @@ public void ContainsTest () var oSet = new NSOrderedSet (str1); Assert.Throws (() => oSet.Contains ((NSString) null), "NSOrderedSet1Test Contains str1"); - Assert.IsTrue (oSet.Contains (str1), "NSOrderedSet1Test Contains str1"); - Assert.IsFalse (oSet.Contains (str2), "NSOrderedSet1Test Does not Contains str2"); + Assert.That (oSet.Contains (str1), Is.True, "NSOrderedSet1Test Contains str1"); + Assert.That (oSet.Contains (str2), Is.False, "NSOrderedSet1Test Does not Contains str2"); } [Test] @@ -110,8 +110,8 @@ public void IndexOfTest () var str3 = (NSString) "3"; var oSet = new NSOrderedSet (str1, str2, str3); - Assert.AreEqual ((nint) 3, oSet.Count, "NSOrderedSet1Test Count"); - Assert.AreEqual ((nint) 1, oSet.IndexOf (str2), "NSOrderedSet1Test IndexOf"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "NSOrderedSet1Test Count"); + Assert.That (oSet.IndexOf (str2), Is.EqualTo ((nint) 1), "NSOrderedSet1Test IndexOf"); } [Test] @@ -122,8 +122,8 @@ public void FirstObjectTest () var str3 = (NSString) "3"; var oSet = new NSOrderedSet (str1, str2, str3); - Assert.AreEqual ((nint) 3, oSet.Count, "NSOrderedSet1Test Count"); - Assert.AreSame (str1, oSet.FirstObject (), "NSOrderedSet1Test IndexOf"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "NSOrderedSet1Test Count"); + Assert.That (oSet.FirstObject (), Is.SameAs (str1), "NSOrderedSet1Test IndexOf"); } [Test] @@ -134,8 +134,8 @@ public void LastObjectTest () var str3 = (NSString) "3"; var oSet = new NSOrderedSet (str1, str2, str3); - Assert.AreEqual ((nint) 3, oSet.Count, "NSOrderedSet1Test Count"); - Assert.AreSame (str3, oSet.LastObject (), "NSOrderedSet1Test IndexOf"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "NSOrderedSet1Test Count"); + Assert.That (oSet.LastObject (), Is.SameAs (str3), "NSOrderedSet1Test IndexOf"); } [Test] @@ -147,9 +147,9 @@ public void AsSetTest () var oSet = new NSOrderedSet (str1, str2, str3); NSSet set = oSet.AsSet (); - Assert.AreEqual ((nint) 3, oSet.Count, "NSOrderedSet1Test Count"); - Assert.AreEqual ((nuint) 3, set.Count, "NSOrderedSet1Test Count"); - Assert.AreSame (str3, set.LookupMember (str3), "NSOrderedSet1Test IndexOf"); + Assert.That (oSet.Count, Is.EqualTo ((nint) 3), "NSOrderedSet1Test Count"); + Assert.That (set.Count, Is.EqualTo ((nuint) 3), "NSOrderedSet1Test Count"); + Assert.That (set.LookupMember (str3), Is.SameAs (str3), "NSOrderedSet1Test IndexOf"); } [Test] @@ -161,16 +161,16 @@ public void IEnumerable1Test () values [i] = (NSString) i.ToString (); var st = new NSOrderedSet (values); - Assert.AreEqual ((nint) C, st.Count, "Count 1"); + Assert.That (st.Count, Is.EqualTo ((nint) C), "Count 1"); var lst = new List (); foreach (var a in (IEnumerable) st) { - Assert.IsNotNull (a, "null item iterator"); - Assert.IsFalse (lst.Contains (a), "duplicated item iterator"); + Assert.That (a, Is.Not.Null, "null item iterator"); + Assert.That (lst.Contains (a), Is.False, "duplicated item iterator"); lst.Add (a); - Assert.IsTrue (Array.IndexOf (values, a) >= 0, "different object"); + Assert.That (Array.IndexOf (values, a) >= 0, Is.True, "different object"); } - Assert.AreEqual (C, lst.Count, "iterator count"); + Assert.That (lst.Count, Is.EqualTo (C), "iterator count"); } [Test] @@ -193,16 +193,16 @@ public void IEnumerableTest () values [i] = (NSString) i.ToString (); var st = new NSOrderedSet (values); - Assert.AreEqual ((nint) C, st.Count, "Count 1"); + Assert.That (st.Count, Is.EqualTo ((nint) C), "Count 1"); var lst = new List (); foreach (NSString a in (IEnumerable) st) { - Assert.IsNotNull (a, "null item iterator"); - Assert.IsFalse (lst.Contains (a), "duplicated item iterator"); + Assert.That (a, Is.Not.Null, "null item iterator"); + Assert.That (lst.Contains (a), Is.False, "duplicated item iterator"); lst.Add (a); - Assert.IsTrue (Array.IndexOf (values, a) >= 0, "different object"); + Assert.That (Array.IndexOf (values, a) >= 0, Is.True, "different object"); } - Assert.AreEqual (C, lst.Count, "iterator count"); + Assert.That (lst.Count, Is.EqualTo (C), "iterator count"); } [Test] @@ -214,8 +214,8 @@ public void OperatorEqualTest () var oSet = new NSOrderedSet (str1, str2, str3); var oSet2 = new NSOrderedSet (str1, str2, str3); - Assert.IsTrue (oSet == oSet2, "NSOrderedSet1Test == must be true"); - Assert.IsTrue (oSet.Equals (oSet2), "NSOrderedSet1Test Equals must be true"); + Assert.That (oSet == oSet2, Is.True, "NSOrderedSet1Test == must be true"); + Assert.That (oSet.Equals (oSet2), Is.True, "NSOrderedSet1Test Equals must be true"); } [Test] @@ -227,8 +227,8 @@ public void OperatorDifferentTest () var oSet = new NSOrderedSet (str1, str2, str3); var oSet2 = new NSOrderedSet (str3, str2, str1); - Assert.IsTrue (oSet != oSet2, "NSOrderedSet1Test != must be true"); - Assert.IsFalse (oSet.Equals (oSet2), "NSOrderedSet1Test Equals must be false"); + Assert.That (oSet != oSet2, Is.True, "NSOrderedSet1Test != must be true"); + Assert.That (oSet.Equals (oSet2), Is.False, "NSOrderedSet1Test Equals must be false"); } [Test] @@ -242,11 +242,11 @@ public void OperatorAddTest () var first = new NSOrderedSet (str1, str2); var second = new NSOrderedSet (str3, str4); var third = first + second; - Assert.AreEqual ((nint) 4, third.Count, "OperatorAdd Count"); - Assert.IsTrue (third.Contains (str1), "OperatorAdd 1"); - Assert.IsTrue (third.Contains (str2), "OperatorAdd 2"); - Assert.IsTrue (third.Contains (str3), "OperatorAdd 3"); - Assert.IsTrue (third.Contains (str4), "OperatorAdd 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 4), "OperatorAdd Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorAdd 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorAdd 2"); + Assert.That (third.Contains (str3), Is.True, "OperatorAdd 3"); + Assert.That (third.Contains (str4), Is.True, "OperatorAdd 4"); } [Test] @@ -260,11 +260,11 @@ public void OperatorAddTest2 () var first = new NSOrderedSet (str1, str2); var second = new NSSet (str3, str4); var third = first + second; - Assert.AreEqual ((nint) 4, third.Count, "OperatorAdd Count"); - Assert.IsTrue (third.Contains (str1), "OperatorAdd 1"); - Assert.IsTrue (third.Contains (str2), "OperatorAdd 2"); - Assert.IsTrue (third.Contains (str3), "OperatorAdd 3"); - Assert.IsTrue (third.Contains (str4), "OperatorAdd 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 4), "OperatorAdd Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorAdd 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorAdd 2"); + Assert.That (third.Contains (str3), Is.True, "OperatorAdd 3"); + Assert.That (third.Contains (str4), Is.True, "OperatorAdd 4"); } [Test] @@ -279,11 +279,11 @@ public void OperatorSubtractTest () var second = new NSOrderedSet (str3, str4); var third = first - second; - Assert.AreEqual ((nint) 2, third.Count, "OperatorSubtract Count"); - Assert.IsTrue (third.Contains (str1), "OperatorSubtract 1"); - Assert.IsTrue (third.Contains (str2), "OperatorSubtract 2"); - Assert.IsFalse (third.Contains (str3), "OperatorSubtract 3"); - Assert.IsFalse (third.Contains (str4), "OperatorSubtract 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 2), "OperatorSubtract Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorSubtract 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorSubtract 2"); + Assert.That (third.Contains (str3), Is.False, "OperatorSubtract 3"); + Assert.That (third.Contains (str4), Is.False, "OperatorSubtract 4"); } [Test] @@ -298,11 +298,11 @@ public void OperatorSubtractTest2 () var second = new NSSet (str3, str4); var third = first - second; - Assert.AreEqual ((nint) 2, third.Count, "OperatorSubtract2 Count"); - Assert.IsTrue (third.Contains (str1), "OperatorSubtract2 1"); - Assert.IsTrue (third.Contains (str2), "OperatorSubtract2 2"); - Assert.IsFalse (third.Contains (str3), "OperatorSubtract2 3"); - Assert.IsFalse (third.Contains (str4), "OperatorSubtract2 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 2), "OperatorSubtract2 Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorSubtract2 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorSubtract2 2"); + Assert.That (third.Contains (str3), Is.False, "OperatorSubtract2 3"); + Assert.That (third.Contains (str4), Is.False, "OperatorSubtract2 4"); } [Test] @@ -323,8 +323,8 @@ public void OperatorPlusReferenceTest () using (var sum3 = one + two) { } - Assert.AreNotEqual (IntPtr.Zero, one.Handle, "Handle must be != IntPtr.Zero"); - Assert.AreNotEqual (IntPtr.Zero, two.Handle, "Handle must be != IntPtr.Zero"); + Assert.That (one.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); + Assert.That (two.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); } } } diff --git a/tests/monotouch-test/Foundation/NSOrderedSetTest.cs b/tests/monotouch-test/Foundation/NSOrderedSetTest.cs index b4ef7934b167..84e100025491 100644 --- a/tests/monotouch-test/Foundation/NSOrderedSetTest.cs +++ b/tests/monotouch-test/Foundation/NSOrderedSetTest.cs @@ -24,10 +24,10 @@ public void OperatorAddTest () using (var set1 = new NSOrderedSet (str1)) using (var set2 = new NSOrderedSet (str2, str3)) using (var result = set1 + set2) { - Assert.AreEqual ((nint) 3, result.Count, "AddTest Count"); - Assert.IsTrue (result.Contains (str1), "AddTest Contains 1"); - Assert.IsTrue (result.Contains (str2), "AddTest Contains 2"); - Assert.IsTrue (result.Contains (str3), "AddTest Contains 3"); + Assert.That (result.Count, Is.EqualTo ((nint) 3), "AddTest Count"); + Assert.That (result.Contains (str1), Is.True, "AddTest Contains 1"); + Assert.That (result.Contains (str2), Is.True, "AddTest Contains 2"); + Assert.That (result.Contains (str3), Is.True, "AddTest Contains 3"); } } @@ -41,10 +41,10 @@ public void OperatorAddTest2 () using (var set1 = new NSOrderedSet (str1)) using (var set2 = new NSSet (str2, str3)) using (var result = set1 + set2) { - Assert.AreEqual ((nint) 3, result.Count, "AddTest Count"); - Assert.IsTrue (result.Contains (str1), "AddTest Contains 1"); - Assert.IsTrue (result.Contains (str2), "AddTest Contains 2"); - Assert.IsTrue (result.Contains (str3), "AddTest Contains 3"); + Assert.That (result.Count, Is.EqualTo ((nint) 3), "AddTest Count"); + Assert.That (result.Contains (str1), Is.True, "AddTest Contains 1"); + Assert.That (result.Contains (str2), Is.True, "AddTest Contains 2"); + Assert.That (result.Contains (str3), Is.True, "AddTest Contains 3"); } } @@ -58,10 +58,10 @@ public void OperatorAddTest3 () using (var set1 = new NSOrderedSet (str1)) using (var set2 = new NSMutableSet (str2, str3)) using (var result = set1 + set2) { - Assert.AreEqual ((nint) 3, result.Count, "AddTest Count"); - Assert.IsTrue (result.Contains (str1), "AddTest Contains 1"); - Assert.IsTrue (result.Contains (str2), "AddTest Contains 2"); - Assert.IsTrue (result.Contains (str3), "AddTest Contains 3"); + Assert.That (result.Count, Is.EqualTo ((nint) 3), "AddTest Count"); + Assert.That (result.Contains (str1), Is.True, "AddTest Contains 1"); + Assert.That (result.Contains (str2), Is.True, "AddTest Contains 2"); + Assert.That (result.Contains (str3), Is.True, "AddTest Contains 3"); } } @@ -77,11 +77,11 @@ public void OperatorSubtractTest () using (var second = new NSOrderedSet (str3, str4)) using (var third = first - second) { - Assert.AreEqual ((nint) 2, third.Count, "OperatorSubtract Count"); - Assert.IsTrue (third.Contains (str1), "OperatorSubtract 1"); - Assert.IsTrue (third.Contains (str2), "OperatorSubtract 2"); - Assert.IsFalse (third.Contains (str3), "OperatorSubtract 3"); - Assert.IsFalse (third.Contains (str4), "OperatorSubtract 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 2), "OperatorSubtract Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorSubtract 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorSubtract 2"); + Assert.That (third.Contains (str3), Is.False, "OperatorSubtract 3"); + Assert.That (third.Contains (str4), Is.False, "OperatorSubtract 4"); } } @@ -97,11 +97,11 @@ public void OperatorSubtractTest2 () using (var second = new NSSet (str3, str4)) using (var third = first - second) { - Assert.AreEqual ((nint) 2, third.Count, "OperatorSubtract Count"); - Assert.IsTrue (third.Contains (str1), "OperatorSubtract 1"); - Assert.IsTrue (third.Contains (str2), "OperatorSubtract 2"); - Assert.IsFalse (third.Contains (str3), "OperatorSubtract 3"); - Assert.IsFalse (third.Contains (str4), "OperatorSubtract 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 2), "OperatorSubtract Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorSubtract 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorSubtract 2"); + Assert.That (third.Contains (str3), Is.False, "OperatorSubtract 3"); + Assert.That (third.Contains (str4), Is.False, "OperatorSubtract 4"); } } @@ -117,11 +117,11 @@ public void OperatorSubtractTest3 () using (var second = new NSMutableSet (str3, str4)) using (var third = first - second) { - Assert.AreEqual ((nint) 2, third.Count, "OperatorSubtract Count"); - Assert.IsTrue (third.Contains (str1), "OperatorSubtract 1"); - Assert.IsTrue (third.Contains (str2), "OperatorSubtract 2"); - Assert.IsFalse (third.Contains (str3), "OperatorSubtract 3"); - Assert.IsFalse (third.Contains (str4), "OperatorSubtract 4"); + Assert.That (third.Count, Is.EqualTo ((nint) 2), "OperatorSubtract Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorSubtract 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorSubtract 2"); + Assert.That (third.Contains (str3), Is.False, "OperatorSubtract 3"); + Assert.That (third.Contains (str4), Is.False, "OperatorSubtract 4"); } } @@ -136,8 +136,8 @@ public void OperatorPlusReferenceTest () using (var sum3 = one + two) { } - Assert.AreNotEqual (IntPtr.Zero, one.Handle, "Handle must be != IntPtr.Zero"); - Assert.AreNotEqual (IntPtr.Zero, two.Handle, "Handle must be != IntPtr.Zero"); + Assert.That (one.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); + Assert.That (two.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); } [Test] @@ -149,8 +149,8 @@ public void OperatorEqualTest () using (var oSet = new NSOrderedSet (str1, str2, str3)) using (var oSet2 = new NSOrderedSet (str1, str2, str3)) { - Assert.IsTrue (oSet == oSet2, "NSOrderedSetTest == must be true"); - Assert.IsTrue (oSet.Equals (oSet2), "NSOrderedSetTest Equals must be true"); + Assert.That (oSet == oSet2, Is.True, "NSOrderedSetTest == must be true"); + Assert.That (oSet.Equals (oSet2), Is.True, "NSOrderedSetTest Equals must be true"); } } @@ -163,8 +163,8 @@ public void OperatorDifferentTest () using (var oSet = new NSOrderedSet (str1, str2, str3)) using (var oSet2 = new NSOrderedSet (str3, str2, str1)) { - Assert.IsTrue (oSet != oSet2, "NSOrderedSetTest != must be true"); - Assert.IsFalse (oSet.Equals (oSet2), "NSOrderedSetTest Equals must be false"); + Assert.That (oSet != oSet2, Is.True, "NSOrderedSetTest != must be true"); + Assert.That (oSet.Equals (oSet2), Is.False, "NSOrderedSetTest Equals must be false"); } } @@ -174,9 +174,9 @@ public void Ctor_WithNull () var str1 = (NSString) "1"; NSObject? nullObj = null; using (var set = new NSOrderedSet (str1, nullObj)) { - Assert.AreEqual (2, (int) set.Count, "Count should include null"); - Assert.AreEqual (str1, set [0], "First item"); - Assert.IsInstanceOf (set [1], "Second item should be NSNull"); + Assert.That ((int) set.Count, Is.EqualTo (2), "Count should include null"); + Assert.That (set [0], Is.EqualTo (str1), "First item"); + Assert.That (set [1], Is.InstanceOf (), "Second item should be NSNull"); } } @@ -185,7 +185,7 @@ public void Ctor_NullArray () { NSObject []? objs = null; using (var set = new NSOrderedSet (objs)) { - Assert.AreEqual (0, (int) set.Count, "Null array should create empty set"); + Assert.That ((int) set.Count, Is.EqualTo (0), "Null array should create empty set"); } } @@ -196,10 +196,10 @@ public void MakeNSOrderedSet_WithNull () var str2 = (NSString) "2"; var values = new NSString? [] { str1, null, str2 }; using (var set = NSOrderedSet.MakeNSOrderedSet (values)) { - Assert.AreEqual (3, (int) set.Count, "Count should include null"); - Assert.AreEqual (str1, set [0], "First item"); - Assert.IsInstanceOf (set [1], "Second item should be NSNull"); - Assert.AreEqual (str2, set [2], "Third item"); + Assert.That ((int) set.Count, Is.EqualTo (3), "Count should include null"); + Assert.That (set [0], Is.EqualTo (str1), "First item"); + Assert.That (set [1], Is.InstanceOf (), "Second item should be NSNull"); + Assert.That (set [2], Is.EqualTo (str2), "Third item"); } } @@ -208,8 +208,8 @@ public void MakeNSOrderedSet_NullArray () { NSString []? values = null; using (var set = NSOrderedSet.MakeNSOrderedSet (values)) { - Assert.IsNotNull (set, "Should create a set"); - Assert.AreEqual (0, (int) set.Count, "Null array should create empty set"); + Assert.That (set, Is.Not.Null, "Should create a set"); + Assert.That ((int) set.Count, Is.EqualTo (0), "Null array should create empty set"); } } } diff --git a/tests/monotouch-test/Foundation/NSRangeTest.cs b/tests/monotouch-test/Foundation/NSRangeTest.cs index b4996dae5e98..d593856a995a 100644 --- a/tests/monotouch-test/Foundation/NSRangeTest.cs +++ b/tests/monotouch-test/Foundation/NSRangeTest.cs @@ -18,10 +18,10 @@ public void IEquatableImplementation (int start1, int len1, int start2, int len2 var left = new NSRange (start1, len1); var right = new NSRange (start2, len2); - Assert.AreEqual (expected, left.Equals (right)); + Assert.That (left.Equals (right), Is.EqualTo (expected)); if (expected) { - Assert.AreEqual (left.GetHashCode (), right.GetHashCode ()); + Assert.That (right.GetHashCode (), Is.EqualTo (left.GetHashCode ())); } } diff --git a/tests/monotouch-test/Foundation/NSScriptCommandArgumentDescriptionTest.cs b/tests/monotouch-test/Foundation/NSScriptCommandArgumentDescriptionTest.cs index c67e7799d18f..d565ead29943 100644 --- a/tests/monotouch-test/Foundation/NSScriptCommandArgumentDescriptionTest.cs +++ b/tests/monotouch-test/Foundation/NSScriptCommandArgumentDescriptionTest.cs @@ -9,20 +9,20 @@ public class NSScriptCommandArgumentDescriptionKeysTest { [Test] public void TestAppleEventCodeKey () { - Assert.IsNotNull (NSScriptCommandArgumentDescriptionKeys.AppleEventCodeKey); - Assert.AreEqual ("AppleEventCode", NSScriptCommandArgumentDescriptionKeys.AppleEventCodeKey?.ToString ()); + Assert.That (NSScriptCommandArgumentDescriptionKeys.AppleEventCodeKey, Is.Not.Null); + Assert.That (NSScriptCommandArgumentDescriptionKeys.AppleEventCodeKey?.ToString (), Is.EqualTo ("AppleEventCode")); } [Test] public void TestTypeKey () { - Assert.AreEqual ("Type", NSScriptCommandArgumentDescriptionKeys.TypeKey.ToString ()); + Assert.That (NSScriptCommandArgumentDescriptionKeys.TypeKey.ToString (), Is.EqualTo ("Type")); } [Test] public void TestOptionalKey () { - Assert.AreEqual ("Optional", NSScriptCommandArgumentDescriptionKeys.OptionalKey.ToString ()); + Assert.That (NSScriptCommandArgumentDescriptionKeys.OptionalKey.ToString (), Is.EqualTo ("Optional")); } } @@ -67,9 +67,9 @@ public void TestDescription (string name, string code, string type, bool isOptio var arg = new NSScriptCommandArgumentDescription (name, code, type, isOptional); var description = arg.Dictionary; - Assert.AreEqual (code, description [new NSString ("AppleEventCode")].ToString ()); - Assert.AreEqual (type, description [new NSString ("Type")].ToString ()); - Assert.AreEqual (isOptional ? "Yes" : "No", description [new NSString ("Optional")].ToString ()); + Assert.That (description [new NSString ("AppleEventCode")].ToString (), Is.EqualTo (code)); + Assert.That (description [new NSString ("Type")].ToString (), Is.EqualTo (type)); + Assert.That (description [new NSString ("Optional")].ToString (), Is.EqualTo (isOptional ? "Yes" : "No")); } } } diff --git a/tests/monotouch-test/Foundation/NSScriptCommandDescriptionDictionaryTest.cs b/tests/monotouch-test/Foundation/NSScriptCommandDescriptionDictionaryTest.cs index 28cebbc04db6..7f5419d3d944 100644 --- a/tests/monotouch-test/Foundation/NSScriptCommandDescriptionDictionaryTest.cs +++ b/tests/monotouch-test/Foundation/NSScriptCommandDescriptionDictionaryTest.cs @@ -18,10 +18,10 @@ public void TestAddNullArgument () desc.Add (arg); using (var argKey = new NSString ("Arguments")) using (var nsName = new NSString (arg.Name)) { - Assert.IsTrue (desc.Dictionary.ContainsKey (argKey)); + Assert.That (desc.Dictionary.ContainsKey (argKey), Is.True); var argDict = desc.Dictionary [argKey] as NSDictionary; - Assert.IsNotNull (argDict); - Assert.IsTrue (argDict.ContainsKey (nsName)); + Assert.That (argDict, Is.Not.Null); + Assert.That (argDict.ContainsKey (nsName), Is.True); } } @@ -34,10 +34,10 @@ public void TestAddArgument () desc.Add (arg); using (var argKey = new NSString ("Arguments")) using (var nsName = new NSString (arg.Name)) { - Assert.IsTrue (desc.Dictionary.ContainsKey (argKey)); + Assert.That (desc.Dictionary.ContainsKey (argKey), Is.True); var argDict = desc.Dictionary [argKey] as NSDictionary; - Assert.IsNotNull (argDict); - Assert.IsTrue (argDict.ContainsKey (nsName)); + Assert.That (argDict, Is.Not.Null); + Assert.That (argDict.ContainsKey (nsName), Is.True); } } @@ -47,7 +47,7 @@ public void TestRemoveNoArguments () var arg = new NSScriptCommandArgumentDescription () { AppleEventCode = "frgt", Type = "text", Name = "Foo" }; var desc = new NSScriptCommandDescriptionDictionary (); // no exception should happen - Assert.IsFalse (desc.Remove (arg)); + Assert.That (desc.Remove (arg), Is.False); } [Test] @@ -56,7 +56,7 @@ public void TestRemoveMissingArgument () var arg = new NSScriptCommandArgumentDescription () { AppleEventCode = "frgt", Type = "text", Name = "Foo" }; var desc = new NSScriptCommandDescriptionDictionary () { Arguments = new NSMutableDictionary () }; // no exception should happen - Assert.IsFalse (desc.Remove (arg)); + Assert.That (desc.Remove (arg), Is.False); } [Test] @@ -68,18 +68,18 @@ public void RemoveArgument () desc.Add (arg); using (var argKey = new NSString ("Arguments")) using (var nsName = new NSString (arg.Name)) { - Assert.IsTrue (desc.Dictionary.ContainsKey (argKey)); + Assert.That (desc.Dictionary.ContainsKey (argKey), Is.True); var argDict = desc.Dictionary [argKey] as NSDictionary; - Assert.IsNotNull (argDict); - Assert.IsTrue (argDict.ContainsKey (nsName)); + Assert.That (argDict, Is.Not.Null); + Assert.That (argDict.ContainsKey (nsName), Is.True); } desc.Remove (arg); using (var argKey = new NSString ("Arguments")) using (var nsName = new NSString (arg.Name)) { - Assert.IsTrue (desc.Dictionary.ContainsKey (argKey)); + Assert.That (desc.Dictionary.ContainsKey (argKey), Is.True); var argDict = desc.Dictionary [argKey] as NSDictionary; - Assert.IsNotNull (argDict); - Assert.IsFalse (argDict.ContainsKey (nsName)); + Assert.That (argDict, Is.Not.Null); + Assert.That (argDict.ContainsKey (nsName), Is.False); } } } diff --git a/tests/monotouch-test/Foundation/NSScriptCommandDescriptionTest.cs b/tests/monotouch-test/Foundation/NSScriptCommandDescriptionTest.cs index 86106ddcdad2..ca89e366546a 100644 --- a/tests/monotouch-test/Foundation/NSScriptCommandDescriptionTest.cs +++ b/tests/monotouch-test/Foundation/NSScriptCommandDescriptionTest.cs @@ -130,48 +130,47 @@ public void TestCreateResultAppleEventWrongLength (string code) [Test] public void TestClassName () { - Assert.AreEqual (cmdClass, scriptDescription.ClassName); + Assert.That (scriptDescription.ClassName, Is.EqualTo (cmdClass)); } [Test] public void TestName () { - Assert.AreEqual (commandName, scriptDescription.Name); + Assert.That (scriptDescription.Name, Is.EqualTo (commandName)); } [Test] public void TestSuiteName () { - Assert.AreEqual (suiteName, scriptDescription.SuitName); + Assert.That (scriptDescription.SuitName, Is.EqualTo (suiteName)); } [Test] public void TestArgumentsNames () { - Assert.AreEqual (args.Keys.Count, scriptDescription.ArgumentNames.Length); + Assert.That (scriptDescription.ArgumentNames.Length, Is.EqualTo (args.Keys.Count)); foreach (var argName in scriptDescription.ArgumentNames) { - Assert.IsTrue (args.Keys.Contains (argName), "Arg {0} is missing", argName); + Assert.That (args.Keys.Contains (argName), Is.True, $"Arg {argName} is missing"); } } [Test] public void TestAppleEventClassCode () { - Assert.AreEqual (eventClass, scriptDescription.AppleEventClassCode); + Assert.That (scriptDescription.AppleEventClassCode, Is.EqualTo (eventClass)); } [Test] public void TestAppleEventCode () { - Assert.AreEqual (eventCode, scriptDescription.AppleEventCode); + Assert.That (scriptDescription.AppleEventCode, Is.EqualTo (eventCode)); } [Test] public void TestIsOptionalArgument () { foreach (KeyValuePair kvp in args) { - Assert.AreEqual (kvp.Value.IsOptional, scriptDescription.IsOptionalArgument (kvp.Key), - "Wrong apple event code for arg {0}", kvp.Key); + Assert.That (scriptDescription.IsOptionalArgument (kvp.Key), Is.EqualTo (kvp.Value.IsOptional), $"Wrong apple event code for arg {kvp.Key}"); } } @@ -179,15 +178,14 @@ public void TestIsOptionalArgument () public void TestGetAppleEventCodeForArgument () { foreach (KeyValuePair kvp in args) { - Assert.AreEqual (kvp.Value.AppleEventCode, scriptDescription.GetAppleEventCodeForArgument (kvp.Key), - "Wrong apple event code for arg {0}", kvp.Key); + Assert.That (scriptDescription.GetAppleEventCodeForArgument (kvp.Key), Is.EqualTo (kvp.Value.AppleEventCode), $"Wrong apple event code for arg {kvp.Key}"); } } [Test] public void TestReturnType () { - Assert.AreEqual (returnType, scriptDescription.ReturnType); + Assert.That (scriptDescription.ReturnType, Is.EqualTo (returnType)); } } } diff --git a/tests/monotouch-test/Foundation/NSSet1Test.cs b/tests/monotouch-test/Foundation/NSSet1Test.cs index 0def8ca1ebb3..782309ea9224 100644 --- a/tests/monotouch-test/Foundation/NSSet1Test.cs +++ b/tests/monotouch-test/Foundation/NSSet1Test.cs @@ -11,7 +11,7 @@ public class NSSet1Test { public void Ctor () { using (var arr = new NSSet ()) { - Assert.AreEqual ((nuint) 0, arr.Count, "Count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 0), "Count"); } } @@ -19,10 +19,10 @@ public void Ctor () public void Ctor_Params () { using (var arr = new NSSet ((NSString) "foo")) { - Assert.AreEqual ((nuint) 1, arr.Count, "Count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 1), "Count"); } using (var arr = new NSSet ((NSString) "foo", (NSString) "bar")) { - Assert.AreEqual ((nuint) 2, arr.Count, "Count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 2), "Count"); } } @@ -33,8 +33,8 @@ public void Ctor_OtherSet () using (var first = new NSSet (v1)) { using (var second = new NSSet (first)) { - Assert.AreEqual ((nuint) 1, first.Count, "1 count"); - Assert.AreEqual ((nuint) 1, second.Count, "2 count"); + Assert.That (first.Count, Is.EqualTo ((nuint) 1), "1 count"); + Assert.That (second.Count, Is.EqualTo ((nuint) 1), "2 count"); } } } @@ -46,8 +46,8 @@ public void Ctor_OtherMutableSet () using (var first = new NSMutableSet (v1)) { using (var second = new NSSet (first)) { - Assert.AreEqual ((nuint) 1, first.Count, "1 count"); - Assert.AreEqual ((nuint) 1, second.Count, "2 count"); + Assert.That (first.Count, Is.EqualTo ((nuint) 1), "1 count"); + Assert.That (second.Count, Is.EqualTo ((nuint) 1), "2 count"); } } } @@ -60,8 +60,8 @@ public void LookupMemberTest () using (var st = new NSSet (v1)) { Assert.Throws (() => st.LookupMember ((NSString) null), "LookupMember ANE 1"); - Assert.AreSame (v1, st.LookupMember (v1), "LookupMember 1"); - Assert.IsNull (st.LookupMember (v2), "LookupMember 2"); + Assert.That (st.LookupMember (v1), Is.SameAs (v1), "LookupMember 1"); + Assert.That (st.LookupMember (v2), Is.Null, "LookupMember 2"); } } @@ -72,11 +72,11 @@ public void AnyObjectTest () var v2 = (NSString) "2"; using (var st = new NSSet ()) { - Assert.IsNull (st.AnyObject, "AnyObject 1"); + Assert.That (st.AnyObject, Is.Null, "AnyObject 1"); } using (var st = new NSSet (v1)) { - Assert.AreSame (v1, st.AnyObject, "AnyObject 2"); + Assert.That (st.AnyObject, Is.SameAs (v1), "AnyObject 2"); } } @@ -88,8 +88,8 @@ public void ContainsTest () using (var st = new NSSet (v1)) { Assert.Throws (() => st.Contains ((NSString) null), "Contains ANE 1"); - Assert.IsTrue (st.Contains (v1), "Contains 1"); - Assert.IsFalse (st.Contains (v2), "Contains 2"); + Assert.That (st.Contains (v1), Is.True, "Contains 1"); + Assert.That (st.Contains (v2), Is.False, "Contains 2"); } } @@ -100,8 +100,8 @@ public void ToArrayTest () using (var st = new NSSet (v1)) { var arr = st.ToArray (); - Assert.AreEqual (1, arr.Length, "ToArray Length"); - Assert.AreSame (v1, arr [0], "ToArray () [0]"); + Assert.That (arr.Length, Is.EqualTo (1), "ToArray Length"); + Assert.That (arr [0], Is.SameAs (v1), "ToArray () [0]"); } } @@ -114,9 +114,9 @@ public void OperatorAddTest () using (var first = new NSSet (v1)) { using (var second = new NSSet (v2)) { using (var third = first + second) { - Assert.AreEqual ((nuint) 2, third.Count, "+ Count"); - Assert.IsTrue (third.Contains (v1), "+ 1"); - Assert.IsTrue (third.Contains (v2), "+ 2"); + Assert.That (third.Count, Is.EqualTo ((nuint) 2), "+ Count"); + Assert.That (third.Contains (v1), Is.True, "+ 1"); + Assert.That (third.Contains (v2), Is.True, "+ 2"); } } } @@ -131,8 +131,8 @@ public void OperatorSubtractTest () using (var first = new NSSet (v1, v2)) { using (var second = new NSSet (v2)) { using (var third = first - second) { - Assert.AreEqual ((nuint) 1, third.Count, "- Count"); - Assert.IsTrue (third.Contains (v1), "- 1"); + Assert.That (third.Count, Is.EqualTo ((nuint) 1), "- Count"); + Assert.That (third.Contains (v1), Is.True, "- 1"); } } } @@ -147,23 +147,23 @@ public void OperatorAddNullTest () // Both null -> null var result1 = nullSet + nullSet; - Assert.IsNull (result1, "null + null"); + Assert.That (result1, Is.Null, "null + null"); // First null, second non-null -> copy of second using (var second = new NSSet (v2)) { using (var result2 = nullSet + second) { - Assert.IsNotNull (result2, "null + non-null"); - Assert.AreEqual ((nuint) 1, result2.Count, "null + non-null Count"); - Assert.IsTrue (result2.Contains (v2), "null + non-null contains"); + Assert.That (result2, Is.Not.Null, "null + non-null"); + Assert.That (result2.Count, Is.EqualTo ((nuint) 1), "null + non-null Count"); + Assert.That (result2.Contains (v2), Is.True, "null + non-null contains"); } } // First non-null, second null -> copy of first using (var first = new NSSet (v1)) { using (var result3 = first + nullSet) { - Assert.IsNotNull (result3, "non-null + null"); - Assert.AreEqual ((nuint) 1, result3.Count, "non-null + null Count"); - Assert.IsTrue (result3.Contains (v1), "non-null + null contains"); + Assert.That (result3, Is.Not.Null, "non-null + null"); + Assert.That (result3.Count, Is.EqualTo ((nuint) 1), "non-null + null Count"); + Assert.That (result3.Contains (v1), Is.True, "non-null + null contains"); } } } @@ -178,9 +178,9 @@ public void OperatorAddEmptyTest () using (var first = new NSSet ()) { using (var second = new NSSet (v2)) { using (var result = first + second) { - Assert.IsNotNull (result, "empty + non-empty"); - Assert.AreEqual ((nuint) 1, result.Count, "empty + non-empty Count"); - Assert.IsTrue (result.Contains (v2), "empty + non-empty contains"); + Assert.That (result, Is.Not.Null, "empty + non-empty"); + Assert.That (result.Count, Is.EqualTo ((nuint) 1), "empty + non-empty Count"); + Assert.That (result.Contains (v2), Is.True, "empty + non-empty contains"); } } } @@ -189,9 +189,9 @@ public void OperatorAddEmptyTest () using (var first = new NSSet (v1)) { using (var second = new NSSet ()) { using (var result = first + second) { - Assert.IsNotNull (result, "non-empty + empty"); - Assert.AreEqual ((nuint) 1, result.Count, "non-empty + empty Count"); - Assert.IsTrue (result.Contains (v1), "non-empty + empty contains"); + Assert.That (result, Is.Not.Null, "non-empty + empty"); + Assert.That (result.Count, Is.EqualTo ((nuint) 1), "non-empty + empty Count"); + Assert.That (result.Contains (v1), Is.True, "non-empty + empty contains"); } } } @@ -206,21 +206,21 @@ public void OperatorSubtractNullTest () // null - null -> null var result1 = nullSet - nullSet; - Assert.IsNull (result1, "null - null"); + Assert.That (result1, Is.Null, "null - null"); // null - non-null -> null using (var second = new NSSet (v2)) { var result2 = nullSet - second; - Assert.IsNull (result2, "null - non-null"); + Assert.That (result2, Is.Null, "null - non-null"); } // non-null - null -> copy of first using (var first = new NSSet (v1, v2)) { using (var result3 = first - nullSet) { - Assert.IsNotNull (result3, "non-null - null"); - Assert.AreEqual ((nuint) 2, result3.Count, "non-null - null Count"); - Assert.IsTrue (result3.Contains (v1), "non-null - null contains v1"); - Assert.IsTrue (result3.Contains (v2), "non-null - null contains v2"); + Assert.That (result3, Is.Not.Null, "non-null - null"); + Assert.That (result3.Count, Is.EqualTo ((nuint) 2), "non-null - null Count"); + Assert.That (result3.Contains (v1), Is.True, "non-null - null contains v1"); + Assert.That (result3.Contains (v2), Is.True, "non-null - null contains v2"); } } } @@ -235,7 +235,7 @@ public void OperatorSubtractEmptyTest () using (var first = new NSSet ()) { using (var second = new NSSet (v2)) { var result = first - second; - Assert.IsNull (result, "empty - non-empty"); + Assert.That (result, Is.Null, "empty - non-empty"); } } @@ -243,10 +243,10 @@ public void OperatorSubtractEmptyTest () using (var first = new NSSet (v1, v2)) { using (var second = new NSSet ()) { using (var result = first - second) { - Assert.IsNotNull (result, "non-empty - empty"); - Assert.AreEqual ((nuint) 2, result.Count, "non-empty - empty Count"); - Assert.IsTrue (result.Contains (v1), "non-empty - empty contains v1"); - Assert.IsTrue (result.Contains (v2), "non-empty - empty contains v2"); + Assert.That (result, Is.Not.Null, "non-empty - empty"); + Assert.That (result.Count, Is.EqualTo ((nuint) 2), "non-empty - empty Count"); + Assert.That (result.Contains (v1), Is.True, "non-empty - empty contains v1"); + Assert.That (result.Contains (v2), Is.True, "non-empty - empty contains v2"); } } } @@ -255,8 +255,8 @@ public void OperatorSubtractEmptyTest () using (var first = new NSSet (v1)) { using (var second = new NSSet (v1)) { var result = first - second; - Assert.IsNotNull (result, "result is not null"); - Assert.AreEqual ((nuint) 0, result.Count, "result is empty"); + Assert.That (result, Is.Not.Null, "result is not null"); + Assert.That (result.Count, Is.EqualTo ((nuint) 0), "result is empty"); } } } @@ -270,16 +270,16 @@ public void IEnumerable1Test () values [i] = (NSString) i.ToString (); using (var st = new NSSet (values)) { - Assert.AreEqual ((nuint) C, st.Count, "Count 1"); + Assert.That (st.Count, Is.EqualTo ((nuint) C), "Count 1"); var lst = new List (); foreach (var a in (IEnumerable) st) { - Assert.IsNotNull (a, "null item iterator"); - Assert.IsFalse (lst.Contains (a), "duplicated item iterator"); + Assert.That (a, Is.Not.Null, "null item iterator"); + Assert.That (lst.Contains (a), Is.False, "duplicated item iterator"); lst.Add (a); - Assert.IsTrue (Array.IndexOf (values, a) >= 0, "different object"); + Assert.That (Array.IndexOf (values, a) >= 0, Is.True, "different object"); } - Assert.AreEqual (C, lst.Count, "iterator count"); + Assert.That (lst.Count, Is.EqualTo (C), "iterator count"); } } @@ -303,16 +303,16 @@ public void IEnumerableTest () values [i] = (NSString) i.ToString (); using (var st = new NSSet (values)) { - Assert.AreEqual ((nuint) C, st.Count, "Count 1"); + Assert.That (st.Count, Is.EqualTo ((nuint) C), "Count 1"); var lst = new List (); foreach (NSString a in (IEnumerable) st) { - Assert.IsNotNull (a, "null item iterator"); - Assert.IsFalse (lst.Contains (a), "duplicated item iterator"); + Assert.That (a, Is.Not.Null, "null item iterator"); + Assert.That (lst.Contains (a), Is.False, "duplicated item iterator"); lst.Add (a); - Assert.IsTrue (Array.IndexOf (values, a) >= 0, "different object"); + Assert.That (Array.IndexOf (values, a) >= 0, Is.True, "different object"); } - Assert.AreEqual (C, lst.Count, "iterator count"); + Assert.That (lst.Count, Is.EqualTo (C), "iterator count"); } } @@ -327,8 +327,8 @@ public void OperatorPlusReferenceTest () using (var sum3 = one + two) { } - Assert.AreNotEqual (IntPtr.Zero, one.Handle, "Handle must be != IntPtr.Zero"); - Assert.AreNotEqual (IntPtr.Zero, two.Handle, "Handle must be != IntPtr.Zero"); + Assert.That (one.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); + Assert.That (two.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); } [Test] diff --git a/tests/monotouch-test/Foundation/NSSetTest.cs b/tests/monotouch-test/Foundation/NSSetTest.cs index e1348a5113c7..007e46db6e58 100644 --- a/tests/monotouch-test/Foundation/NSSetTest.cs +++ b/tests/monotouch-test/Foundation/NSSetTest.cs @@ -9,9 +9,9 @@ public void SetCtors () { // The NSSet (params object [] args) var s = new NSSet (1); - Assert.AreEqual (s.Count, (nuint) 1); + Assert.That (s.Count, Is.EqualTo ((nuint) 1)); s = new NSSet (1, 2, 3); - Assert.AreEqual (s.Count, (nuint) 3); + Assert.That (s.Count, Is.EqualTo ((nuint) 3)); // The NSSet (params [] NSObject args) var objs = new NSObject [5]; @@ -19,11 +19,11 @@ public void SetCtors () objs [i] = new NSNumber (i); s = new NSSet (objs [0], objs [1], objs [2], objs [3], objs [4]); - Assert.AreEqual (s.Count, (nuint) 5); + Assert.That (s.Count, Is.EqualTo ((nuint) 5)); // Repeat the values s = new NSSet (objs [0], objs [1], objs [2], objs [0], objs [1]); - Assert.AreEqual (s.Count, (nuint) 3); + Assert.That (s.Count, Is.EqualTo ((nuint) 3)); } [Test] @@ -32,32 +32,32 @@ public void OperatorPlus () var one = new NSSet (1, 2, 3); var two = new NSSet (4, 5, 6); var sum = one + two; - Assert.AreEqual (sum.Count, (nuint) 6); + Assert.That (sum.Count, Is.EqualTo ((nuint) 6)); var objs = new NSObject [5]; for (int i = 0; i < objs.Length; i++) objs [i] = new NSNumber (i * 100); sum = new NSSet (objs) + one + two; - Assert.AreEqual (sum.Count, (nuint) 11); + Assert.That (sum.Count, Is.EqualTo ((nuint) 11)); sum = new NSSet (objs) + new NSSet (objs); - Assert.AreEqual (sum.Count, (nuint) 5); + Assert.That (sum.Count, Is.EqualTo ((nuint) 5)); - Assert.AreEqual ((one + one).Count, (nuint) 3); + Assert.That ((one + one).Count, Is.EqualTo ((nuint) 3)); var sub = one - one; - Assert.AreEqual (sub.Count, (nuint) 0); + Assert.That (sub.Count, Is.EqualTo ((nuint) 0)); var three = new NSSet (1, 2, 3, 4, 5, 6); var subt = three - two; - Assert.AreEqual (subt.Count, (nuint) 3); - Assert.True (three.Contains (1)); - Assert.True (three.Contains (2)); - Assert.True (three.Contains (3)); + Assert.That (subt.Count, Is.EqualTo ((nuint) 3)); + Assert.That (three.Contains (1), Is.True); + Assert.That (three.Contains (2), Is.True); + Assert.That (three.Contains (3), Is.True); subt = three - one; - Assert.AreEqual (subt.Count, (nuint) 3); - Assert.True (three.Contains (4)); - Assert.True (three.Contains (5)); - Assert.True (three.Contains (6)); + Assert.That (subt.Count, Is.EqualTo ((nuint) 3)); + Assert.That (three.Contains (4), Is.True); + Assert.That (three.Contains (5), Is.True); + Assert.That (three.Contains (6), Is.True); } @@ -72,8 +72,8 @@ public void OperatorPlusReferenceTest () using (var sum3 = one + two) { } - Assert.AreNotEqual (IntPtr.Zero, one.Handle, "Handle must be != IntPtr.Zero"); - Assert.AreNotEqual (IntPtr.Zero, two.Handle, "Handle must be != IntPtr.Zero"); + Assert.That (one.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); + Assert.That (two.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle must be != IntPtr.Zero"); } [Test] @@ -86,10 +86,10 @@ public void OperatorAddTest () using (var set1 = new NSSet (str1)) using (var set2 = new NSOrderedSet (str2, str3)) using (var result = set1 + set2) { - Assert.AreEqual ((nuint) 3, result.Count, "AddTest Count"); - Assert.IsTrue (result.Contains (str1), "AddTest Contains 1"); - Assert.IsTrue (result.Contains (str2), "AddTest Contains 2"); - Assert.IsTrue (result.Contains (str3), "AddTest Contains 3"); + Assert.That (result.Count, Is.EqualTo ((nuint) 3), "AddTest Count"); + Assert.That (result.Contains (str1), Is.True, "AddTest Contains 1"); + Assert.That (result.Contains (str2), Is.True, "AddTest Contains 2"); + Assert.That (result.Contains (str3), Is.True, "AddTest Contains 3"); } } @@ -103,10 +103,10 @@ public void OperatorAddTest2 () using (var set1 = new NSSet (str1)) using (var set2 = new NSMutableOrderedSet (str2, str3)) using (var result = set1 + set2) { - Assert.AreEqual ((nuint) 3, result.Count, "AddTest Count"); - Assert.IsTrue (result.Contains (str1), "AddTest Contains 1"); - Assert.IsTrue (result.Contains (str2), "AddTest Contains 2"); - Assert.IsTrue (result.Contains (str3), "AddTest Contains 3"); + Assert.That (result.Count, Is.EqualTo ((nuint) 3), "AddTest Count"); + Assert.That (result.Contains (str1), Is.True, "AddTest Contains 1"); + Assert.That (result.Contains (str2), Is.True, "AddTest Contains 2"); + Assert.That (result.Contains (str3), Is.True, "AddTest Contains 3"); } } @@ -122,11 +122,11 @@ public void OperatorSubtractTest () using (var second = new NSOrderedSet (str3, str4)) using (var third = first - second) { - Assert.AreEqual ((nuint) 2, third.Count, "OperatorSubtract Count"); - Assert.IsTrue (third.Contains (str1), "OperatorSubtract 1"); - Assert.IsTrue (third.Contains (str2), "OperatorSubtract 2"); - Assert.IsFalse (third.Contains (str3), "OperatorSubtract 3"); - Assert.IsFalse (third.Contains (str4), "OperatorSubtract 4"); + Assert.That (third.Count, Is.EqualTo ((nuint) 2), "OperatorSubtract Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorSubtract 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorSubtract 2"); + Assert.That (third.Contains (str3), Is.False, "OperatorSubtract 3"); + Assert.That (third.Contains (str4), Is.False, "OperatorSubtract 4"); } } @@ -142,11 +142,11 @@ public void OperatorSubtractTest2 () using (var second = new NSMutableOrderedSet (str3, str4)) using (var third = first - second) { - Assert.AreEqual ((nuint) 2, third.Count, "OperatorSubtract Count"); - Assert.IsTrue (third.Contains (str1), "OperatorSubtract 1"); - Assert.IsTrue (third.Contains (str2), "OperatorSubtract 2"); - Assert.IsFalse (third.Contains (str3), "OperatorSubtract 3"); - Assert.IsFalse (third.Contains (str4), "OperatorSubtract 4"); + Assert.That (third.Count, Is.EqualTo ((nuint) 2), "OperatorSubtract Count"); + Assert.That (third.Contains (str1), Is.True, "OperatorSubtract 1"); + Assert.That (third.Contains (str2), Is.True, "OperatorSubtract 2"); + Assert.That (third.Contains (str3), Is.False, "OperatorSubtract 3"); + Assert.That (third.Contains (str4), Is.False, "OperatorSubtract 4"); } } } diff --git a/tests/monotouch-test/Foundation/NSStreamTest.cs b/tests/monotouch-test/Foundation/NSStreamTest.cs index ee61e074b0e3..d6c441e6403a 100644 --- a/tests/monotouch-test/Foundation/NSStreamTest.cs +++ b/tests/monotouch-test/Foundation/NSStreamTest.cs @@ -21,12 +21,12 @@ public void BoundPairTest () var send = Encoding.ASCII.GetBytes ("hello, world"); nint n = send.Length; - Assert.AreEqual (n, write.Write (send)); + Assert.That (write.Write (send), Is.EqualTo (n)); var result = new byte [n + 10]; - Assert.AreEqual (n, read.Read (result, (uint) n)); + Assert.That (read.Read (result, (uint) n), Is.EqualTo (n)); for (int i = 0; i < n; i++) - Assert.AreEqual (send [i], result [i], "Item " + i); + Assert.That (result [i], Is.EqualTo (send [i]), "Item " + i); } @@ -69,11 +69,11 @@ public void ConnectToHost () read.Open (); write.Open (); var send = new byte [] { 1, 2, 3, 4, 5 }; - Assert.AreEqual ((nint) 5, write.Write (send)); + Assert.That (write.Write (send), Is.EqualTo ((nint) 5)); var result = new byte [5]; - Assert.AreEqual ((nint) 5, read.Read (result, 5)); + Assert.That (read.Read (result, 5), Is.EqualTo ((nint) 5)); for (int i = 0; i < 5; i++) - Assert.AreEqual (send [i] * 10, result [i]); + Assert.That (result [i], Is.EqualTo (send [i] * 10)); listenThread.Join (); listener.Stop (); read.Close (); @@ -106,11 +106,11 @@ public void ConnectToPeer () read.Open (); write.Open (); var send = new byte [] { 1, 2, 3, 4, 5 }; - Assert.AreEqual ((nint) 5, write.Write (send), "Write"); + Assert.That (write.Write (send), Is.EqualTo ((nint) 5), "Write"); var result = new byte [5]; - Assert.AreEqual ((nint) 5, read.Read (result, 5), "Read"); + Assert.That (read.Read (result, 5), Is.EqualTo ((nint) 5), "Read"); for (int i = 0; i < 5; i++) - Assert.AreEqual (send [i] * 10, result [i], "Item " + i); + Assert.That (result [i], Is.EqualTo (send [i] * 10), "Item " + i); listenThreadCompleted = listenThread.Join (TimeSpan.FromSeconds (5)); Assert.That (listenThreadCompleted, Is.True, "Listener thread"); } finally { @@ -126,7 +126,7 @@ public void ConnectToPeer () }; thread.Start (); Assert.That (thread.Join (TimeSpan.FromSeconds (10)), Is.True, "Background thread completion"); - Assert.IsNull (ex, "No exception"); + Assert.That (ex, Is.Null, "No exception"); } void DebugListener (object data) diff --git a/tests/monotouch-test/Foundation/NSString.cs b/tests/monotouch-test/Foundation/NSString.cs index dddc646ce258..f68282555005 100644 --- a/tests/monotouch-test/Foundation/NSString.cs +++ b/tests/monotouch-test/Foundation/NSString.cs @@ -18,7 +18,7 @@ public void NSString_LineRangeForRange () NSRange range = input.LineRangeForRange (new NSRange (index, 0)); index = (int) (range.Location + range.Length); } - Assert.AreEqual (4, numberOfLines); + Assert.That (numberOfLines, Is.EqualTo (4)); } [Test] @@ -27,9 +27,9 @@ public void NSString_GetLineStart () NSString input = new NSString ("Hey\nHow\nYou\nDoing"); nuint start, lineEnd, contentsEnd; input.GetLineStart (out start, out lineEnd, out contentsEnd, new NSRange (5, 11)); - Assert.AreEqual ((nuint) 4, start); - Assert.AreEqual ((nuint) 17, lineEnd); - Assert.AreEqual ((nuint) 17, contentsEnd); + Assert.That (start, Is.EqualTo ((nuint) 4)); + Assert.That (lineEnd, Is.EqualTo ((nuint) 17)); + Assert.That (contentsEnd, Is.EqualTo ((nuint) 17)); } [Test] @@ -37,8 +37,8 @@ public void NSString_BoundingRectWithSize () { NSString input = new NSString ("Hey\nHow\nYou\nDoing"); CGRect rect = input.BoundingRectWithSize (new CGSize (20, 30), NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading, new NSDictionary ()); - Assert.IsTrue (rect.Width > 0); - Assert.IsTrue (rect.Height > 0); + Assert.That (rect.Width > 0, Is.True); + Assert.That (rect.Height > 0, Is.True); } [Test] @@ -51,9 +51,9 @@ public void NSString_CompareTo () Array.Sort (tests); - Assert.AreSame (a, tests [0], "0"); - Assert.AreSame (b, tests [1], "1"); - Assert.AreSame (c, tests [2], "2"); + Assert.That (tests [0], Is.SameAs (a), "0"); + Assert.That (tests [1], Is.SameAs (b), "1"); + Assert.That (tests [2], Is.SameAs (c), "2"); } } } @@ -67,8 +67,8 @@ public void NSAttributedString_BoundingRectWithSize () NSFont font = NSFont.FromFontName ("Arial", 40); NSAttributedString str = new NSAttributedString ("Hello World", font); CGRect rect = str.BoundingRectWithSize (new CGSize (20, 30), NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading); - Assert.IsTrue (rect.Width > 0); - Assert.IsTrue (rect.Height > 0); + Assert.That (rect.Width > 0, Is.True); + Assert.That (rect.Height > 0, Is.True); } [Test] @@ -78,10 +78,10 @@ public void NSAttributedString_GetUrl () var str = new NSAttributedString ("Test string with url: http://www.google.com"); var url = str.GetUrl (42, out range); - Assert.IsNotNull (url); - Assert.IsTrue (url.AbsoluteString == "http://www.google.com"); - Assert.IsTrue (range.Location == 22); - Assert.IsTrue (range.Length == 21); + Assert.That (url, Is.Not.Null); + Assert.That (url.AbsoluteString, Is.EqualTo ("http://www.google.com")); + Assert.That (range.Location, Is.EqualTo ((nint) 22)); + Assert.That (range.Length, Is.EqualTo ((nint) 21)); } } } diff --git a/tests/monotouch-test/Foundation/NSStringTest.cs b/tests/monotouch-test/Foundation/NSStringTest.cs index 586e1ce364f1..e228909694b0 100644 --- a/tests/monotouch-test/Foundation/NSStringTest.cs +++ b/tests/monotouch-test/Foundation/NSStringTest.cs @@ -7,20 +7,20 @@ public class NSStringTest { public void LocalizedFormatTest () { // Strings and NSstring - Assert.AreEqual ("hello", NSString.LocalizedFormat ("hello").ToString ()); - Assert.AreEqual ("hello", NSString.LocalizedFormat (new NSString ("hello")).ToString ()); + Assert.That (NSString.LocalizedFormat ("hello").ToString (), Is.EqualTo ("hello")); + Assert.That (NSString.LocalizedFormat (new NSString ("hello")).ToString (), Is.EqualTo ("hello")); // Test the overloads with numbers - Assert.AreEqual ("hello", NSString.LocalizedFormat ("hello").ToString ()); - Assert.AreEqual ("hello0", NSString.LocalizedFormat ("hello%@", 0).ToString ()); - Assert.AreEqual ("hello01", NSString.LocalizedFormat ("hello%@%@", 0, 1).ToString ()); - Assert.AreEqual ("hello012", NSString.LocalizedFormat ("hello%@%@%@", 0, 1, 2).ToString ()); - Assert.AreEqual ("hello0123", NSString.LocalizedFormat ("hello%@%@%@%@", 0, 1, 2, 3).ToString ()); - Assert.AreEqual ("hello01234", NSString.LocalizedFormat ("hello%@%@%@%@%@", 0, 1, 2, 3, 4).ToString ()); - Assert.AreEqual ("hello012345", NSString.LocalizedFormat ("hello%@%@%@%@%@%@", 0, 1, 2, 3, 4, 5).ToString ()); - Assert.AreEqual ("hello0123456", NSString.LocalizedFormat ("hello%@%@%@%@%@%@%@", 0, 1, 2, 3, 4, 5, 6).ToString ()); - Assert.AreEqual ("hello01234567", NSString.LocalizedFormat ("hello%@%@%@%@%@%@%@%@", 0, 1, 2, 3, 4, 5, 6, 7).ToString ()); - Assert.AreEqual ("hello012345678", NSString.LocalizedFormat ("hello%@%@%@%@%@%@%@%@%@", 0, 1, 2, 3, 4, 5, 6, 7, 8).ToString ()); + Assert.That (NSString.LocalizedFormat ("hello").ToString (), Is.EqualTo ("hello")); + Assert.That (NSString.LocalizedFormat ("hello%@", 0).ToString (), Is.EqualTo ("hello0")); + Assert.That (NSString.LocalizedFormat ("hello%@%@", 0, 1).ToString (), Is.EqualTo ("hello01")); + Assert.That (NSString.LocalizedFormat ("hello%@%@%@", 0, 1, 2).ToString (), Is.EqualTo ("hello012")); + Assert.That (NSString.LocalizedFormat ("hello%@%@%@%@", 0, 1, 2, 3).ToString (), Is.EqualTo ("hello0123")); + Assert.That (NSString.LocalizedFormat ("hello%@%@%@%@%@", 0, 1, 2, 3, 4).ToString (), Is.EqualTo ("hello01234")); + Assert.That (NSString.LocalizedFormat ("hello%@%@%@%@%@%@", 0, 1, 2, 3, 4, 5).ToString (), Is.EqualTo ("hello012345")); + Assert.That (NSString.LocalizedFormat ("hello%@%@%@%@%@%@%@", 0, 1, 2, 3, 4, 5, 6).ToString (), Is.EqualTo ("hello0123456")); + Assert.That (NSString.LocalizedFormat ("hello%@%@%@%@%@%@%@%@", 0, 1, 2, 3, 4, 5, 6, 7).ToString (), Is.EqualTo ("hello01234567")); + Assert.That (NSString.LocalizedFormat ("hello%@%@%@%@%@%@%@%@%@", 0, 1, 2, 3, 4, 5, 6, 7, 8).ToString (), Is.EqualTo ("hello012345678")); } [TestCase ("asdf", -1, 0, "start")] @@ -31,11 +31,11 @@ public void NSStringSubstringExceptions (string input, int start, int length, st { var exception = Assert.Throws (() => new NSString (input, start, length)); - Assert.AreEqual (paramName, exception.ParamName); + Assert.That (exception.ParamName, Is.EqualTo (paramName)); exception = Assert.Throws (() => NSString.CreateNative (input, start, length)); - Assert.AreEqual (paramName, exception.ParamName); + Assert.That (exception.ParamName, Is.EqualTo (paramName)); } [TestCase ("asdf", 0, 4)] // Whole string @@ -48,10 +48,10 @@ public void TestNSStringSubstrings (string input, int start, int length) var substring = new NSString (input, start, length); var substringHandle = NSString.CreateNative (input, start, length); try { - Assert.AreEqual (str, substring); + Assert.That (substring, Is.EqualTo (str)); substring = (NSString) NSString.FromHandle (substringHandle); - Assert.AreEqual (str, substring); + Assert.That (substring, Is.EqualTo (str)); } finally { NSString.ReleaseNative (substringHandle); } @@ -66,7 +66,7 @@ public void TestFromHandle_owns (bool owns) for (var i = 0; i < 100; i++) { if (owns) str.DangerousRetain (); - Assert.AreEqual (testString, NSString.FromHandle (str.Handle, owns), $"true #{i}"); + Assert.That (NSString.FromHandle (str.Handle, owns), Is.EqualTo (testString), $"true #{i}"); } // If there was a leak, RetainCount would be 100+ because we looped 100 times above. Assert.That (str.RetainCount, Is.LessThan ((nuint) 10), "RetainCount"); diff --git a/tests/monotouch-test/Foundation/NSTextListTest.cs b/tests/monotouch-test/Foundation/NSTextListTest.cs index 763eb3473db5..35e746526213 100644 --- a/tests/monotouch-test/Foundation/NSTextListTest.cs +++ b/tests/monotouch-test/Foundation/NSTextListTest.cs @@ -18,9 +18,9 @@ public class NSTextListTest { public void Constructor_CustomFormat (string format) { var textList = new NSTextList (format); - Assert.AreEqual (format, textList.CustomMarkerFormat, "CustomMarkerFormat"); - Assert.AreEqual (NSTextListMarkerFormats.CustomString, textList.MarkerFormat, "MarkerFormat"); - Assert.AreEqual (NSTextListOptions.None, textList.ListOptions, "ListOptions"); + Assert.That (textList.CustomMarkerFormat, Is.EqualTo (format), "CustomMarkerFormat"); + Assert.That (textList.MarkerFormat, Is.EqualTo (NSTextListMarkerFormats.CustomString), "MarkerFormat"); + Assert.That (textList.ListOptions, Is.EqualTo (NSTextListOptions.None), "ListOptions"); } [TestCase ("{decimal}.", NSTextListOptions.None)] @@ -28,9 +28,9 @@ public void Constructor_CustomFormat (string format) public void Constructor_CustomFormat_2 (string format, NSTextListOptions options) { var textList = new NSTextList (format, options); - Assert.AreEqual (format, textList.CustomMarkerFormat, "CustomMarkerFormat"); - Assert.AreEqual (NSTextListMarkerFormats.CustomString, textList.MarkerFormat, "MarkerFormat"); - Assert.AreEqual (options, textList.ListOptions, "ListOptions"); + Assert.That (textList.CustomMarkerFormat, Is.EqualTo (format), "CustomMarkerFormat"); + Assert.That (textList.MarkerFormat, Is.EqualTo (NSTextListMarkerFormats.CustomString), "MarkerFormat"); + Assert.That (textList.ListOptions, Is.EqualTo (options), "ListOptions"); } @@ -39,9 +39,9 @@ public void Constructor_CustomFormat_2 (string format, NSTextListOptions options public void Constructor_TypedFormat_2 (NSTextListMarkerFormats format, NSTextListOptions options) { var textList = new NSTextList (format, options); - Assert.AreEqual ((string) format.GetConstant ()!, textList.CustomMarkerFormat, "CustomMarkerFormat"); - Assert.AreEqual (format, textList.MarkerFormat, "MarkerFormat"); - Assert.AreEqual (options, textList.ListOptions, "ListOptions"); + Assert.That (textList.CustomMarkerFormat, Is.EqualTo ((string) format.GetConstant ()!), "CustomMarkerFormat"); + Assert.That (textList.MarkerFormat, Is.EqualTo (format), "MarkerFormat"); + Assert.That (textList.ListOptions, Is.EqualTo (options), "ListOptions"); } [TestCase (NSTextListMarkerFormats.Circle)] @@ -49,9 +49,9 @@ public void Constructor_TypedFormat_2 (NSTextListMarkerFormats format, NSTextLis public void Constructor_TypedFormat (NSTextListMarkerFormats format) { var textList = new NSTextList (format); - Assert.AreEqual ((string) format.GetConstant ()!, textList.CustomMarkerFormat, "CustomMarkerFormat"); - Assert.AreEqual (format, textList.MarkerFormat, "MarkerFormat"); - Assert.AreEqual (NSTextListOptions.None, textList.ListOptions, "ListOptions"); + Assert.That (textList.CustomMarkerFormat, Is.EqualTo ((string) format.GetConstant ()!), "CustomMarkerFormat"); + Assert.That (textList.MarkerFormat, Is.EqualTo (format), "MarkerFormat"); + Assert.That (textList.ListOptions, Is.EqualTo (NSTextListOptions.None), "ListOptions"); } } } diff --git a/tests/monotouch-test/Foundation/NSThread.cs b/tests/monotouch-test/Foundation/NSThread.cs index a788dfca7b7c..f00f88e09dbe 100644 --- a/tests/monotouch-test/Foundation/NSThread.cs +++ b/tests/monotouch-test/Foundation/NSThread.cs @@ -12,8 +12,8 @@ public class NSThreadTests { public void NSThread_CallStack_Test () { string [] stack = NSThread.NativeCallStack; - Assert.IsNotNull (stack); - Assert.IsTrue (stack.Length > 0); + Assert.That (stack, Is.Not.Null); + Assert.That (stack.Length > 0, Is.True); } } } diff --git a/tests/monotouch-test/Foundation/NSTimeZoneTest.cs b/tests/monotouch-test/Foundation/NSTimeZoneTest.cs index c4175eff8dcc..8db92af08b88 100644 --- a/tests/monotouch-test/Foundation/NSTimeZoneTest.cs +++ b/tests/monotouch-test/Foundation/NSTimeZoneTest.cs @@ -31,7 +31,7 @@ public void AbbreviationsTest () public void AbbreviationTest () { var timezone = NSTimeZone.LocalTimeZone; - Assert.NotNull (timezone.Abbreviation ()); + Assert.That (timezone.Abbreviation (), Is.Not.Null); } [Test] @@ -47,10 +47,10 @@ public void All_28300 () } #endif TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById (name); - Assert.NotNull (tzi.GetUtcOffset (DateTime.Now), name); + Assert.That (tzi.GetUtcOffset (DateTime.Now), Is.Not.Null, name); } - Assert.NotNull (TimeZoneInfo.Local.GetUtcOffset (DateTime.Now), "Local"); + Assert.That (TimeZoneInfo.Local.GetUtcOffset (DateTime.Now), Is.Not.Null, "Local"); } } } diff --git a/tests/monotouch-test/Foundation/NSUrlSessionConfiguration.cs b/tests/monotouch-test/Foundation/NSUrlSessionConfiguration.cs index 97305a6ef7c7..0ea8e826d817 100644 --- a/tests/monotouch-test/Foundation/NSUrlSessionConfiguration.cs +++ b/tests/monotouch-test/Foundation/NSUrlSessionConfiguration.cs @@ -9,21 +9,21 @@ public class NSUrlSessionConfigurationTest { public void TestSessionTypeDefault () { using (var config = NSUrlSessionConfiguration.DefaultSessionConfiguration) - Assert.AreEqual (NSUrlSessionConfiguration.SessionConfigurationType.Default, config.SessionType); + Assert.That (config.SessionType, Is.EqualTo (NSUrlSessionConfiguration.SessionConfigurationType.Default)); } [Test] public void TestSessionTypeBackground () { using (var config = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration ("my.identifier.test")) - Assert.AreEqual (NSUrlSessionConfiguration.SessionConfigurationType.Background, config.SessionType); + Assert.That (config.SessionType, Is.EqualTo (NSUrlSessionConfiguration.SessionConfigurationType.Background)); } [Test] public void TestSessionTypeEphemeral () { using (var config = NSUrlSessionConfiguration.EphemeralSessionConfiguration) - Assert.AreEqual (NSUrlSessionConfiguration.SessionConfigurationType.Ephemeral, config.SessionType); + Assert.That (config.SessionType, Is.EqualTo (NSUrlSessionConfiguration.SessionConfigurationType.Ephemeral)); } } } diff --git a/tests/monotouch-test/Foundation/NetServiceTest.cs b/tests/monotouch-test/Foundation/NetServiceTest.cs index 15a5ea4db6cf..ca5f4fd01262 100644 --- a/tests/monotouch-test/Foundation/NetServiceTest.cs +++ b/tests/monotouch-test/Foundation/NetServiceTest.cs @@ -35,9 +35,9 @@ public void DefaultCtor () Assert.That (ns.Port, Is.EqualTo ((nint) 1234), "Port"); NSInputStream input; NSOutputStream output; - Assert.True (ns.GetStreams (out input, out output), "GetStreams"); - Assert.NotNull (input, "input"); - Assert.NotNull (output, "output"); + Assert.That (ns.GetStreams (out input, out output), Is.True, "GetStreams"); + Assert.That (input, Is.Not.Null, "input"); + Assert.That (output, Is.Not.Null, "output"); } } } diff --git a/tests/monotouch-test/Foundation/NotificationCenter.cs b/tests/monotouch-test/Foundation/NotificationCenter.cs index 0b3ee34de7f2..cab2406ee854 100644 --- a/tests/monotouch-test/Foundation/NotificationCenter.cs +++ b/tests/monotouch-test/Foundation/NotificationCenter.cs @@ -30,9 +30,9 @@ public void Free () GC.Collect (GC.MaxGeneration); Thread.Sleep (10); } - Assert.True (a, "a"); - Assert.True (b, "b"); - Assert.True (freed, "freed"); + Assert.That (a, Is.True, "a"); + Assert.That (b, Is.True, "b"); + Assert.That (freed, Is.True, "freed"); } void FreeLeaf (Action destroyedCallback) @@ -97,10 +97,10 @@ public void TargetedNotificationsTest () using (var txt = new global::UIKit.UITextField ()) using (var notification = global::UIKit.UITextField.Notifications.ObserveTextFieldTextDidChange (txt, (sender, e) => called = true)) { NSNotificationCenter.DefaultCenter.PostNotificationName (global::UIKit.UITextField.TextFieldTextDidChangeNotification, null); - Assert.False (called, "Notification should not be called"); + Assert.That (called, Is.False, "Notification should not be called"); NSNotificationCenter.DefaultCenter.PostNotificationName (global::UIKit.UITextField.TextFieldTextDidChangeNotification, txt); - Assert.True (called, "Notification should have been called"); + Assert.That (called, Is.True, "Notification should have been called"); } } #endif @@ -142,7 +142,7 @@ public void ThreadSafe () for (var i = 0; i < threadCount; i++) { threads [i].Join (); } - Assert.IsNull (ex, "Exception"); + Assert.That (ex, Is.Null, "Exception"); } } } diff --git a/tests/monotouch-test/Foundation/NumberTest.cs b/tests/monotouch-test/Foundation/NumberTest.cs index 696f938c03f9..d58a8ff75c1c 100644 --- a/tests/monotouch-test/Foundation/NumberTest.cs +++ b/tests/monotouch-test/Foundation/NumberTest.cs @@ -69,8 +69,8 @@ public void Equals () using (var a = new NSNumber (1)) using (var b = new NSNumber (1d)) { // Two objects that are equal return hash codes that are equal. - Assert.True (a.Equals (b), "Equals(NSNumber)"); - Assert.True (b.Equals ((object) a), "Equals(Object)"); + Assert.That (a.Equals (b), Is.True, "Equals(NSNumber)"); + Assert.That (b.Equals ((object) a), Is.True, "Equals(Object)"); Assert.That (a.GetHashCode (), Is.EqualTo (b.GetHashCode ()), "GetHashCode"); } } diff --git a/tests/monotouch-test/Foundation/ObjectTest.cs b/tests/monotouch-test/Foundation/ObjectTest.cs index 4453222bd8f4..61a613419cb6 100644 --- a/tests/monotouch-test/Foundation/ObjectTest.cs +++ b/tests/monotouch-test/Foundation/ObjectTest.cs @@ -51,10 +51,10 @@ public bool GetIsDirectBinding () public void IsDirectBinding () { using (var o1 = new NSObject ()) { - Assert.True (GetIsDirectBinding (o1), "inside monotouch.dll"); + Assert.That (GetIsDirectBinding (o1), Is.True, "inside monotouch.dll"); } using (var o2 = new MyObject ()) { - Assert.False (o2.GetIsDirectBinding (), "outside monotouch.dll"); + Assert.That (o2.GetIsDirectBinding (), Is.False, "outside monotouch.dll"); } } @@ -72,15 +72,15 @@ public void FromObject_INativeObject () { // https://bugzilla.xamarin.com/show_bug.cgi?id=8458 using (CGPath p = CGPath.FromRect (new CGRect (1, 2, 3, 4))) { - Assert.IsNotNull (NSObject.FromObject (p), "CGPath"); + Assert.That (NSObject.FromObject (p), Is.Not.Null, "CGPath"); } using (CGColor c = new CGColor (CGColorSpace.CreateDeviceRGB (), new nfloat [] { 0.1f, 0.2f, 0.3f, 1.0f })) { - Assert.IsNotNull (NSObject.FromObject (c), "CGColor"); + Assert.That (NSObject.FromObject (c), Is.Not.Null, "CGColor"); } var hasSecAccessControl = TestRuntime.CheckXcodeVersion (6, 0); if (hasSecAccessControl) { using (var sac = new SecAccessControl (SecAccessible.WhenPasscodeSetThisDeviceOnly)) { - Assert.IsNotNull (NSObject.FromObject (sac), "SecAccessControl"); + Assert.That (NSObject.FromObject (sac), Is.Not.Null, "SecAccessControl"); } } } @@ -89,10 +89,10 @@ public void FromObject_INativeObject () public void FromObject_Handle () { using (CGPath p = CGPath.FromRect (new CGRect (1, 2, 3, 4))) { - Assert.IsNotNull (NSObject.FromObject (p.Handle), "CGPath"); + Assert.That (NSObject.FromObject (p.Handle), Is.Not.Null, "CGPath"); } using (CGColor c = new CGColor (CGColorSpace.CreateDeviceRGB (), new nfloat [] { 0.1f, 0.2f, 0.3f, 1.0f })) { - Assert.IsNotNull (NSObject.FromObject (c.Handle), "CGColor"); + Assert.That (NSObject.FromObject (c.Handle), Is.Not.Null, "CGColor"); } } @@ -133,31 +133,31 @@ public void Copy () // NSObject does not conform to NSCopying using (var o = new NSObject ()) { - Assert.False (o.ConformsToProtocol (nscopying), "NSObject/NSCopying"); - Assert.False (o.ConformsToProtocol (nsmutablecopying), "NSObject/NSMutableCopying"); + Assert.That (o.ConformsToProtocol (nscopying), Is.False, "NSObject/NSCopying"); + Assert.That (o.ConformsToProtocol (nsmutablecopying), Is.False, "NSObject/NSMutableCopying"); } // NSNumber conforms to NSCopying - but not NSMutableCopying using (var n = new NSNumber (-1)) { - Assert.True (n.ConformsToProtocol (nscopying), "NSNumber/NSCopying"); + Assert.That (n.ConformsToProtocol (nscopying), Is.True, "NSNumber/NSCopying"); using (var xn = n.Copy ()) { - Assert.NotNull (xn, "NSNumber/Copy/NotNull"); - Assert.AreSame (n, xn, "NSNumber/Copy/NotSame"); + Assert.That (xn, Is.Not.Null, "NSNumber/Copy/NotNull"); + Assert.That (xn, Is.SameAs (n), "NSNumber/Copy/NotSame"); } - Assert.False (n.ConformsToProtocol (nsmutablecopying), "NSNumber/NSMutableCopying"); + Assert.That (n.ConformsToProtocol (nsmutablecopying), Is.False, "NSNumber/NSMutableCopying"); } // NSMutableString conforms to NSCopying - but not NSMutableCopying using (var s = new NSMutableString (1)) { - Assert.True (s.ConformsToProtocol (nscopying), "NSMutableString/NSCopying"); + Assert.That (s.ConformsToProtocol (nscopying), Is.True, "NSMutableString/NSCopying"); using (var xs = s.Copy ()) { - Assert.NotNull (xs, "NSMutableString/Copy/NotNull"); - Assert.AreNotSame (s, xs, "NSMutableString/Copy/NotSame"); + Assert.That (xs, Is.Not.Null, "NSMutableString/Copy/NotNull"); + Assert.That (xs, Is.Not.SameAs (s), "NSMutableString/Copy/NotSame"); } - Assert.True (s.ConformsToProtocol (nsmutablecopying), "NSMutableString/NSMutableCopying"); + Assert.That (s.ConformsToProtocol (nsmutablecopying), Is.True, "NSMutableString/NSMutableCopying"); using (var xs = s.MutableCopy ()) { - Assert.NotNull (xs, "NSMutableString/MutableCopy/NotNull"); - Assert.AreNotSame (s, xs, "NSMutableString/MutableCopy/NotSame"); + Assert.That (xs, Is.Not.Null, "NSMutableString/MutableCopy/NotNull"); + Assert.That (xs, Is.Not.SameAs (s), "NSMutableString/MutableCopy/NotSame"); } } } @@ -170,7 +170,7 @@ public void Encode () // NSNumber conforms to NSCoding using (var n = new NSNumber (-1)) { - Assert.True (n.ConformsToProtocol (nscoding), "NSNumber/NSCoding"); + Assert.That (n.ConformsToProtocol (nscoding), Is.True, "NSNumber/NSCoding"); using (var d = new NSMutableData ()) using (var a = new NSKeyedArchiver (d)) { n.EncodeTo (a); @@ -184,19 +184,19 @@ public void Equality () { using (var o1 = new NSObject ()) using (var o2 = new NSObject ()) { - Assert.False (o1.Equals ((object) null), "Equals(object) null"); - Assert.False (o1.Equals ((object) o2), "Equals(object) 1-2"); - Assert.False (o2.Equals ((object) o1), "Equals(object) 2-1"); + Assert.That (o1.Equals ((object) null), Is.False, "Equals(object) null"); + Assert.That (o1.Equals ((object) o2), Is.False, "Equals(object) 1-2"); + Assert.That (o2.Equals ((object) o1), Is.False, "Equals(object) 2-1"); - Assert.False (o1.Equals (3), "Equals(object) 1-3"); + Assert.That (o1.Equals (3), Is.False, "Equals(object) 1-3"); - Assert.False (o1.Equals ((NSObject) null), "Equals(NSObject) null"); - Assert.False (o1.Equals ((NSObject) o2), "Equals(NSObject) 1-2"); - Assert.False (o2.Equals ((NSObject) o1), "Equals(NSObject) 2-1"); + Assert.That (o1.Equals ((NSObject) null), Is.False, "Equals(NSObject) null"); + Assert.That (o1.Equals ((NSObject) o2), Is.False, "Equals(NSObject) 1-2"); + Assert.That (o2.Equals ((NSObject) o1), Is.False, "Equals(NSObject) 2-1"); // on a more positive note... - Assert.True (o1.Equals ((object) o1), "Equals(object) 1-1"); - Assert.True (o2.Equals ((NSObject) o2), "Equals(NSObject) 2-2"); + Assert.That (o1.Equals ((object) o1), Is.True, "Equals(object) 1-1"); + Assert.That (o2.Equals ((NSObject) o2), Is.True, "Equals(NSObject) 2-2"); } } @@ -233,15 +233,15 @@ public void SubclassEquality () using (var o2 = new NSOverrideEqualObject (true)) using (var o3 = new NSOverrideEqualObject (false)) { // true, same object - Assert.True (o1.Equals (o1), "direct - direct / same"); - Assert.True (o3.Equals (o3), "indirect - indirect / same"); + Assert.That (o1.Equals (o1), Is.True, "direct - direct / same"); + Assert.That (o3.Equals (o3), Is.True, "indirect - indirect / same"); // false, good since there's state in o2 and o3 that does not exists in o1 (direct / native only) - Assert.False (o1.Equals (o2), "direct - indirect"); - Assert.False (o3.Equals (o1), "indirect - direct"); + Assert.That (o1.Equals (o2), Is.False, "direct - indirect"); + Assert.That (o3.Equals (o1), Is.False, "indirect - direct"); // default is false, which is good since the managed state (Throw) differs between o2 and o3 - Assert.False (o3.Equals (o2), "indirect - indirect"); + Assert.That (o3.Equals (o2), Is.False, "indirect - indirect"); // throws (as implemented above) Assert.Throws (() => { o2.Equals ((object) o1); }, "Equals(object) 2-1"); @@ -259,18 +259,17 @@ public void ObserverTest () using (var observer = o.AddObserver ("frame", NSKeyValueObservingOptions.OldNew, change => { var old = ((NSValue) change.OldValue).CGRectValue; var @new = ((NSValue) change.NewValue).CGRectValue; - Assert.AreEqual ("{{0, 0}, {0, 0}}", old.ToString (), "#old"); - Assert.AreEqual ("{{0, 0}, {123, 234}}", @new.ToString (), "#new"); + Assert.That (old.ToString (), Is.EqualTo ("{{0, 0}, {0, 0}}"), "#old"); + Assert.That (@new.ToString (), Is.EqualTo ("{{0, 0}, {123, 234}}"), "#new"); observed = true; })) { o.Frame = new CGRect (0, 0, 123, 234); } } - Assert.IsTrue (observed, "observed"); + Assert.That (observed, Is.True, "observed"); } [Test] - [Timeout (5000)] public void InvokeTest () { var evt = new ManualResetEvent (false); @@ -279,7 +278,7 @@ public void InvokeTest () while (!evt.WaitOne (1)) NSRunLoop.Current.RunUntil (NSRunLoopMode.Default, NSDate.Now.AddSeconds (1)); - Assert.True (evt.WaitOne (1), "Our invoke was not fired?"); + Assert.That (evt.WaitOne (1), Is.True, "Our invoke was not fired?"); } } } diff --git a/tests/monotouch-test/Foundation/OutputStreamTest.cs b/tests/monotouch-test/Foundation/OutputStreamTest.cs index 8c0fe89b87d0..30a815057dfb 100644 --- a/tests/monotouch-test/Foundation/OutputStreamTest.cs +++ b/tests/monotouch-test/Foundation/OutputStreamTest.cs @@ -38,10 +38,10 @@ public unsafe void Write () s.Open (); s.Write (new byte [] { 1, 2, 3 }, 3); using (var obj = s [NSStream.DataWrittenToMemoryStreamKey] as NSData) { - Assert.IsNotNull (obj, "a"); - Assert.AreEqual (1, Marshal.ReadByte (obj.Bytes, 0), "a[0]"); - Assert.AreEqual (2, Marshal.ReadByte (obj.Bytes, 1), "a[1]"); - Assert.AreEqual (3, Marshal.ReadByte (obj.Bytes, 2), "a[2]"); + Assert.That (obj, Is.Not.Null, "a"); + Assert.That (Marshal.ReadByte (obj.Bytes, 0), Is.EqualTo (1), "a[0]"); + Assert.That (Marshal.ReadByte (obj.Bytes, 1), Is.EqualTo (2), "a[1]"); + Assert.That (Marshal.ReadByte (obj.Bytes, 2), Is.EqualTo (3), "a[2]"); } } @@ -49,10 +49,10 @@ public unsafe void Write () s.Open (); s.Write (new byte [] { 1, 2, 3 }); using (var obj = s [NSStream.DataWrittenToMemoryStreamKey] as NSData) { - Assert.IsNotNull (obj, "a"); - Assert.AreEqual (1, Marshal.ReadByte (obj.Bytes, 0), "b[0]"); - Assert.AreEqual (2, Marshal.ReadByte (obj.Bytes, 1), "b[1]"); - Assert.AreEqual (3, Marshal.ReadByte (obj.Bytes, 2), "b[2]"); + Assert.That (obj, Is.Not.Null, "a"); + Assert.That (Marshal.ReadByte (obj.Bytes, 0), Is.EqualTo (1), "b[0]"); + Assert.That (Marshal.ReadByte (obj.Bytes, 1), Is.EqualTo (2), "b[1]"); + Assert.That (Marshal.ReadByte (obj.Bytes, 2), Is.EqualTo (3), "b[2]"); } } @@ -60,8 +60,8 @@ public unsafe void Write () s.Open (); s.Write (new byte [] { 1, 2, 3 }, 2, 1); using (var obj = s [NSStream.DataWrittenToMemoryStreamKey] as NSData) { - Assert.IsNotNull (obj, "a"); - Assert.AreEqual (3, Marshal.ReadByte (obj.Bytes, 0), "c[0]"); + Assert.That (obj, Is.Not.Null, "a"); + Assert.That (Marshal.ReadByte (obj.Bytes, 0), Is.EqualTo (3), "c[0]"); } } } diff --git a/tests/monotouch-test/Foundation/RegularExpressionTest.cs b/tests/monotouch-test/Foundation/RegularExpressionTest.cs index e04c9ad2aba2..277e9e308654 100644 --- a/tests/monotouch-test/Foundation/RegularExpressionTest.cs +++ b/tests/monotouch-test/Foundation/RegularExpressionTest.cs @@ -21,9 +21,9 @@ public void GetMatches () var matches = detector.GetMatches (new NSString (text), 0, range); - Assert.AreEqual ((nint) 10, matches [0].Range.Location, "Range.Location"); - Assert.AreEqual ((nint) 21, matches [0].Range.Length, "Range.Length"); - Assert.AreEqual ("https://microsoft.com", matches [0].Url.AbsoluteString, "Url"); + Assert.That (matches [0].Range.Location, Is.EqualTo ((nint) 10), "Range.Location"); + Assert.That (matches [0].Range.Length, Is.EqualTo ((nint) 21), "Range.Length"); + Assert.That (matches [0].Url.AbsoluteString, Is.EqualTo ("https://microsoft.com"), "Url"); } } } diff --git a/tests/monotouch-test/Foundation/StringTest.cs b/tests/monotouch-test/Foundation/StringTest.cs index fe3f19bee01b..4ae5c1ecfba9 100644 --- a/tests/monotouch-test/Foundation/StringTest.cs +++ b/tests/monotouch-test/Foundation/StringTest.cs @@ -204,10 +204,10 @@ public void Equality () // since ObjC thinks it's different Assert.That (s1.GetHashCode (), Is.Not.EqualTo (s2.GetHashCode ()), "GetHashCode"); // then it's "correct" to return false for equality - Assert.False (s1.Equals ((object) s2), "Equal(object)"); - Assert.False (s1.Equals ((NSObject) s2), "Equal(NSObject)"); - Assert.False (s1.Equals ((NSString) s2), "Equal(NSString)"); - Assert.False (NSString.Equals (s1, s2), "static"); + Assert.That (s1.Equals ((object) s2), Is.False, "Equal(object)"); + Assert.That (s1.Equals ((NSObject) s2), Is.False, "Equal(NSObject)"); + Assert.That (s1.Equals ((NSString) s2), Is.False, "Equal(NSString)"); + Assert.That (NSString.Equals (s1, s2), Is.False, "static"); // and people need to call compare Assert.That (s1.Compare (s2), Is.EqualTo (NSComparisonResult.Same), "Same"); } @@ -220,7 +220,7 @@ public void FromData () UIImage img = UIImage.FromFile (Path.Combine (NSBundle.MainBundle.ResourcePath, "basn3p08.png")); using (NSData imageData = img.AsPNG ()) { using (var str = NSString.FromData (imageData, NSStringEncoding.UTF8)) { - Assert.IsNull (str, "NSDataFromImage"); + Assert.That (str, Is.Null, "NSDataFromImage"); } } Assert.Throws (() => { diff --git a/tests/monotouch-test/Foundation/ThreadTest.cs b/tests/monotouch-test/Foundation/ThreadTest.cs index 848bc80053bb..120d545ebc14 100644 --- a/tests/monotouch-test/Foundation/ThreadTest.cs +++ b/tests/monotouch-test/Foundation/ThreadTest.cs @@ -19,15 +19,15 @@ public class ThreadTest { [Test] public void MainThread () { - Assert.True (NSThread.IsMain, "IsMain"); - Assert.True (NSThread.MainThread.IsMainThread, "IsMainThread"); + Assert.That (NSThread.IsMain, Is.True, "IsMain"); + Assert.That (NSThread.MainThread.IsMainThread, Is.True, "IsMainThread"); } [Test] public void GetEntryAssemblyReturnsOk () { - Assert.IsNotNull (Assembly.GetEntryAssembly ()); - Assert.IsTrue (NSThread.IsMain); + Assert.That (Assembly.GetEntryAssembly (), Is.Not.Null); + Assert.That (NSThread.IsMain, Is.True); int rv = -1; var t = new Thread (() => { if (NSThread.IsMain) @@ -41,7 +41,7 @@ public void GetEntryAssemblyReturnsOk () }; t.Start (); t.Join (); - Assert.AreEqual (0, rv); + Assert.That (rv, Is.EqualTo (0)); } [Test] @@ -50,7 +50,7 @@ public void InitWithDataTest () var obj = new InitWithDataObject (); var thread = new NSThread (obj, new Selector ("start:"), null); thread.Start (); - Assert.IsTrue (obj.StartedEvent.WaitOne (TimeSpan.FromSeconds (5)), "thread start"); + Assert.That (obj.StartedEvent.WaitOne (TimeSpan.FromSeconds (5)), Is.True, "thread start"); GC.Collect (); } diff --git a/tests/monotouch-test/Foundation/TimerTest.cs b/tests/monotouch-test/Foundation/TimerTest.cs index 5b9db4c1f220..7e7ad52f4db4 100644 --- a/tests/monotouch-test/Foundation/TimerTest.cs +++ b/tests/monotouch-test/Foundation/TimerTest.cs @@ -41,7 +41,7 @@ public void Bug17793 () }; thread.Start (); - Assert.IsTrue (evt.Wait (TimeSpan.FromSeconds (5)), "Not signalled twice in 5s"); + Assert.That (evt.Wait (TimeSpan.FromSeconds (5)), Is.True, "Not signalled twice in 5s"); thread.Join (); } } @@ -69,7 +69,7 @@ public void Bug2443 () }; thread.Start (); - Assert.IsTrue (evt.Wait (TimeSpan.FromSeconds (5)), "Not signalled twice in 5s"); + Assert.That (evt.Wait (TimeSpan.FromSeconds (5)), Is.True, "Not signalled twice in 5s"); thread.Join (); } } @@ -99,8 +99,8 @@ public void CreateTimer_NewSignature () }; thread.Start (); - Assert.IsTrue (evt.WaitOne (TimeSpan.FromSeconds (5)), "WaitOne"); - Assert.IsTrue (result, "result"); + Assert.That (evt.WaitOne (TimeSpan.FromSeconds (5)), Is.True, "WaitOne"); + Assert.That (result, Is.True, "result"); thread.Join (); } } diff --git a/tests/monotouch-test/Foundation/UbiquitousKeyValueStoreTest.cs b/tests/monotouch-test/Foundation/UbiquitousKeyValueStoreTest.cs index 0a6da9374478..b6ea04b883cc 100644 --- a/tests/monotouch-test/Foundation/UbiquitousKeyValueStoreTest.cs +++ b/tests/monotouch-test/Foundation/UbiquitousKeyValueStoreTest.cs @@ -31,16 +31,16 @@ public void Indexer () store [key] = value; if (expectNull) { - Assert.Null (store [key], "key 1"); + Assert.That (store [key], Is.Null, "key 1"); } else { - Assert.AreEqual (value, store [key], "key 1"); + Assert.That (store [key], Is.EqualTo (value), "key 1"); } store [(string) key] = value; if (expectNull) { - Assert.Null (store [key], "key 2"); + Assert.That (store [key], Is.Null, "key 2"); } else { - Assert.AreEqual (value, store [key], "key 2"); + Assert.That (store [key], Is.EqualTo (value), "key 2"); } } } diff --git a/tests/monotouch-test/Foundation/UrlConnectionTest.cs b/tests/monotouch-test/Foundation/UrlConnectionTest.cs index 13787f4989a3..6625779b618c 100644 --- a/tests/monotouch-test/Foundation/UrlConnectionTest.cs +++ b/tests/monotouch-test/Foundation/UrlConnectionTest.cs @@ -50,9 +50,9 @@ public void SendSynchronousRequest () using var request = new NSUrlRequest (url); using var data = NSUrlConnection.SendSynchronousRequest (request, out var response, out var error); TestRuntime.IgnoreInCIIfBadNetwork (error); - Assert.IsNull (error, $"Error: {error?.Description}"); - Assert.IsNotNull (data, "Data"); - Assert.IsNotNull (response, "Response"); + Assert.That (error, Is.Null, $"Error: {error?.Description}"); + Assert.That (data, Is.Not.Null, "Data"); + Assert.That (response, Is.Not.Null, "Response"); response?.Dispose (); error?.Dispose (); } catch (Exception e) { @@ -63,7 +63,7 @@ public void SendSynchronousRequest () var timedOut = !thread.Join (TimeSpan.FromSeconds (15)); if (timedOut) { TestRuntime.IgnoreInCI ("Timed out"); - Assert.IsFalse (timedOut, "Timed out"); + Assert.That (timedOut, Is.False, "Timed out"); } TestRuntime.IgnoreInCIIfBadNetwork (ex); TestRuntime.AssertNoNonNUnitException (ex, "Exception"); diff --git a/tests/monotouch-test/Foundation/UrlCredentialTest.cs b/tests/monotouch-test/Foundation/UrlCredentialTest.cs index b4eecb06740f..4e1fd5cbc6a0 100644 --- a/tests/monotouch-test/Foundation/UrlCredentialTest.cs +++ b/tests/monotouch-test/Foundation/UrlCredentialTest.cs @@ -36,12 +36,12 @@ public void Ctor_Trust () { using (var trust = GetTrust ()) using (var creds = new NSUrlCredential (trust)) { - Assert.Null (creds.Certificates, "Certificates"); - Assert.False (creds.HasPassword, "HasPassword"); - Assert.Null (creds.SecIdentity, "SecIdentity"); - Assert.Null (creds.Password, "Password"); + Assert.That (creds.Certificates, Is.Null, "Certificates"); + Assert.That (creds.HasPassword, Is.False, "HasPassword"); + Assert.That (creds.SecIdentity, Is.Null, "SecIdentity"); + Assert.That (creds.Password, Is.Null, "Password"); Assert.That (creds.Persistence, Is.EqualTo (NSUrlCredentialPersistence.ForSession), "Persistence"); - Assert.Null (creds.User, "User"); + Assert.That (creds.User, Is.Null, "User"); } } @@ -50,12 +50,12 @@ public void FromTrust () { using (var trust = GetTrust ()) using (var creds = NSUrlCredential.FromTrust (trust)) { - Assert.Null (creds.Certificates, "Certificates"); - Assert.False (creds.HasPassword, "HasPassword"); - Assert.Null (creds.SecIdentity, "SecIdentity"); - Assert.Null (creds.Password, "Password"); + Assert.That (creds.Certificates, Is.Null, "Certificates"); + Assert.That (creds.HasPassword, Is.False, "HasPassword"); + Assert.That (creds.SecIdentity, Is.Null, "SecIdentity"); + Assert.That (creds.Password, Is.Null, "Password"); Assert.That (creds.Persistence, Is.EqualTo (NSUrlCredentialPersistence.ForSession), "Persistence"); - Assert.Null (creds.User, "User"); + Assert.That (creds.User, Is.Null, "User"); } } } diff --git a/tests/monotouch-test/Foundation/UrlProtectionSpaceTest.cs b/tests/monotouch-test/Foundation/UrlProtectionSpaceTest.cs index 6cc3ddc0cea4..f6a810a9401e 100644 --- a/tests/monotouch-test/Foundation/UrlProtectionSpaceTest.cs +++ b/tests/monotouch-test/Foundation/UrlProtectionSpaceTest.cs @@ -28,15 +28,15 @@ public void Http () { using (var ps = new NSUrlProtectionSpace ("www.xamarin.com", 80, NSUrlProtectionSpace.HTTP, null, null)) { Assert.That (ps.AuthenticationMethod, Is.EqualTo ("NSURLAuthenticationMethodDefault"), "AuthenticationMethod"); - Assert.Null (ps.DistinguishedNames, "DistinguishedNames"); + Assert.That (ps.DistinguishedNames, Is.Null, "DistinguishedNames"); Assert.That (ps.Host, Is.EqualTo ("www.xamarin.com"), "Host"); - Assert.False (ps.IsProxy, "IsProxy"); + Assert.That (ps.IsProxy, Is.False, "IsProxy"); Assert.That (ps.Port, Is.EqualTo ((nint) 80), "Port"); Assert.That (ps.Protocol, Is.EqualTo ("http"), "Protocol"); - Assert.Null (ps.ProxyType, "ProxyType"); - Assert.Null (ps.Realm, "Realm"); - Assert.False (ps.ReceivesCredentialSecurely, "ReceivesCredentialSecurely"); - Assert.Null (ps.ServerSecTrust, "ServerSecTrust"); + Assert.That (ps.ProxyType, Is.Null, "ProxyType"); + Assert.That (ps.Realm, Is.Null, "Realm"); + Assert.That (ps.ReceivesCredentialSecurely, Is.False, "ReceivesCredentialSecurely"); + Assert.That (ps.ServerSecTrust, Is.Null, "ServerSecTrust"); } } @@ -49,15 +49,15 @@ public void Https () } else { Assert.That (ps.AuthenticationMethod, Is.EqualTo ("NSURLAuthenticationMethodDefault"), "AuthenticationMethod"); } - Assert.Null (ps.DistinguishedNames, "DistinguishedNames"); + Assert.That (ps.DistinguishedNames, Is.Null, "DistinguishedNames"); Assert.That (ps.Host, Is.EqualTo ("mail.google.com"), "Host"); - Assert.False (ps.IsProxy, "IsProxy"); + Assert.That (ps.IsProxy, Is.False, "IsProxy"); Assert.That (ps.Port, Is.EqualTo ((nint) 443), "Port"); Assert.That (ps.Protocol, Is.EqualTo ("https"), "Protocol"); - Assert.Null (ps.ProxyType, "ProxyType"); - Assert.Null (ps.Realm, "Realm"); - Assert.True (ps.ReceivesCredentialSecurely, "ReceivesCredentialSecurely"); - Assert.Null (ps.ServerSecTrust, "ServerSecTrust"); + Assert.That (ps.ProxyType, Is.Null, "ProxyType"); + Assert.That (ps.Realm, Is.Null, "Realm"); + Assert.That (ps.ReceivesCredentialSecurely, Is.True, "ReceivesCredentialSecurely"); + Assert.That (ps.ServerSecTrust, Is.Null, "ServerSecTrust"); } } @@ -66,15 +66,15 @@ public void HttpProxy () { using (var ps = new NSUrlProtectionSpace ("www.xamarin.com", 80, NSUrlProtectionSpace.HTTPProxy, "default", NSUrlProtectionSpace.AuthenticationMethodHTTPDigest, false)) { Assert.That (ps.AuthenticationMethod, Is.EqualTo ("NSURLAuthenticationMethodHTTPDigest"), "AuthenticationMethod"); - Assert.Null (ps.DistinguishedNames, "DistinguishedNames"); + Assert.That (ps.DistinguishedNames, Is.Null, "DistinguishedNames"); Assert.That (ps.Host, Is.EqualTo ("www.xamarin.com"), "Host"); - Assert.False (ps.IsProxy, "IsProxy"); + Assert.That (ps.IsProxy, Is.False, "IsProxy"); Assert.That (ps.Port, Is.EqualTo ((nint) 80), "Port"); Assert.That (ps.Protocol, Is.EqualTo ("http"), "Protocol"); - Assert.Null (ps.ProxyType, "ProxyType"); + Assert.That (ps.ProxyType, Is.Null, "ProxyType"); Assert.That (ps.Realm, Is.EqualTo ("default"), "Realm"); - Assert.True (ps.ReceivesCredentialSecurely, "ReceivesCredentialSecurely"); - Assert.Null (ps.ServerSecTrust, "ServerSecTrust"); + Assert.That (ps.ReceivesCredentialSecurely, Is.True, "ReceivesCredentialSecurely"); + Assert.That (ps.ServerSecTrust, Is.Null, "ServerSecTrust"); } } @@ -83,15 +83,15 @@ public void HttpProxy_Proxy () { using (var ps = new NSUrlProtectionSpace ("www.xamarin.com", 80, NSUrlProtectionSpace.HTTPProxy, "default", NSUrlProtectionSpace.AuthenticationMethodHTTPDigest, true)) { Assert.That (ps.AuthenticationMethod, Is.EqualTo ("NSURLAuthenticationMethodHTTPDigest"), "AuthenticationMethod"); - Assert.Null (ps.DistinguishedNames, "DistinguishedNames"); + Assert.That (ps.DistinguishedNames, Is.Null, "DistinguishedNames"); Assert.That (ps.Host, Is.EqualTo ("www.xamarin.com"), "Host"); - Assert.True (ps.IsProxy, "IsProxy"); + Assert.That (ps.IsProxy, Is.True, "IsProxy"); Assert.That (ps.Port, Is.EqualTo ((nint) 80), "Port"); Assert.That (ps.Protocol, Is.EqualTo ("http"), "Protocol"); Assert.That (ps.ProxyType, Is.EqualTo ("http"), "ProxyType"); - Assert.Null (ps.Realm, "Realm"); - Assert.True (ps.ReceivesCredentialSecurely, "ReceivesCredentialSecurely"); - Assert.Null (ps.ServerSecTrust, "ServerSecTrust"); + Assert.That (ps.Realm, Is.Null, "Realm"); + Assert.That (ps.ReceivesCredentialSecurely, Is.True, "ReceivesCredentialSecurely"); + Assert.That (ps.ServerSecTrust, Is.Null, "ServerSecTrust"); } } } diff --git a/tests/monotouch-test/Foundation/UrlProtocolTest.cs b/tests/monotouch-test/Foundation/UrlProtocolTest.cs index e9c8d5ef9c1c..6b27f39d437d 100644 --- a/tests/monotouch-test/Foundation/UrlProtocolTest.cs +++ b/tests/monotouch-test/Foundation/UrlProtocolTest.cs @@ -47,7 +47,7 @@ public void CanInitWithTask () { // NSInvalidArgumentException Reason: *** -canInitWithRequest: cannot be sent to an abstract object of class NSURLProtocol: Create a concrete instance! using (var t = new NSUrlSessionTask ()) { - Assert.False (NSUrlProtocol.CanInitWithTask (t), "CanInitWithTask"); + Assert.That (NSUrlProtocol.CanInitWithTask (t), Is.False, "CanInitWithTask"); } } @@ -56,7 +56,7 @@ public void Task () { // NSInvalidArgumentException -[MonoTouchFixtures_Foundation_UrlProtocolTest_CustomProtocol task]: unrecognized selector sent to instance 0x7ff4c910 using (var p = new CustomProtocol ()) { - Assert.Null (p.Task, "Task"); + Assert.That (p.Task, Is.Null, "Task"); } } #endif @@ -80,9 +80,9 @@ public void RegistrarTest () // Use the completion check overload so RunAsync also waits for // StopLoading to fire (State reaches 5) instead of returning as // soon as the download task completes (State may still be 4). - Assert.IsTrue (TestRuntime.RunAsync (TimeSpan.FromSeconds (10), task, () => CustomUrlProtocol.State >= 5), "Timed out"); + Assert.That (TestRuntime.RunAsync (TimeSpan.FromSeconds (10), task, () => CustomUrlProtocol.State >= 5), Is.True, "Timed out"); Assert.That (CustomUrlProtocol.State, Is.EqualTo (5), "State"); - Assert.IsTrue (success, "Success"); + Assert.That (success, Is.True, "Success"); } public class CustomUrlProtocol : NSUrlProtocol, INSUrlSessionDelegate, INSUrlSessionTaskDelegate, INSUrlSessionDataDelegate { diff --git a/tests/monotouch-test/Foundation/UrlRequestTest.cs b/tests/monotouch-test/Foundation/UrlRequestTest.cs index 9b35a268133a..06eef4700677 100644 --- a/tests/monotouch-test/Foundation/UrlRequestTest.cs +++ b/tests/monotouch-test/Foundation/UrlRequestTest.cs @@ -22,8 +22,8 @@ public void Mutability_30744 () using (var md = NSMutableDictionary.FromObjectAndKey (s2, s1)) using (var ur = new NSUrlRequest ()) using (var mur = (NSMutableUrlRequest) ur.MutableCopy ()) { - Assert.Null (ur.Headers, "NSUrlRequest / Headers / null"); - Assert.Null (mur.Headers, "NSMutableUrlRequest / Headers / null"); + Assert.That (ur.Headers, Is.Null, "NSUrlRequest / Headers / null"); + Assert.That (mur.Headers, Is.Null, "NSMutableUrlRequest / Headers / null"); mur.Headers = md; @@ -48,7 +48,7 @@ public void Mutability_30744 () Assert.That (md.Count, Is.EqualTo ((nuint) 1), "3"); Assert.That (mur.Headers.Count, Is.EqualTo ((nuint) 1), "40"); - Assert.AreNotSame (md, mur.Headers, "!same"); + Assert.That (mur.Headers, Is.Not.SameAs (md), "!same"); // https://www.bignerdranch.com/blog/about-mutability/ Assert.That (mur.Headers.Class.Name, Is.EqualTo ("__NSCFDictionary"), "__NSCFDictionary"); diff --git a/tests/monotouch-test/Foundation/UrlSessionConfigurationTest.cs b/tests/monotouch-test/Foundation/UrlSessionConfigurationTest.cs index 74f16ec9e0de..fab307db63d6 100644 --- a/tests/monotouch-test/Foundation/UrlSessionConfigurationTest.cs +++ b/tests/monotouch-test/Foundation/UrlSessionConfigurationTest.cs @@ -41,35 +41,35 @@ public void Default_Properties () // in iOS9 those selectors do not respond - but they do work (forwarded to __NSCFURLSessionConfiguration type ?) - Assert.True (config.AllowsCellularAccess, "allowsCellularAccess"); + Assert.That (config.AllowsCellularAccess, Is.True, "allowsCellularAccess"); config.AllowsCellularAccess = config.AllowsCellularAccess; // setAllowsCellularAccess: - Assert.Null (config.ConnectionProxyDictionary, "connectionProxyDictionary"); + Assert.That (config.ConnectionProxyDictionary, Is.Null, "connectionProxyDictionary"); config.ConnectionProxyDictionary = null; // setConnectionProxyDictionary: - Assert.False (config.Discretionary, "isDiscretionary"); + Assert.That (config.Discretionary, Is.False, "isDiscretionary"); config.Discretionary = config.Discretionary; // setDiscretionary: - Assert.Null (config.HttpAdditionalHeaders, "HTTPAdditionalHeaders"); + Assert.That (config.HttpAdditionalHeaders, Is.Null, "HTTPAdditionalHeaders"); config.HttpAdditionalHeaders = config.HttpAdditionalHeaders; // setHTTPAdditionalHeaders: Assert.That (config.HttpCookieAcceptPolicy, Is.EqualTo (NSHttpCookieAcceptPolicy.OnlyFromMainDocumentDomain), "HTTPCookieAcceptPolicy"); config.HttpCookieAcceptPolicy = config.HttpCookieAcceptPolicy; // setHTTPCookieAcceptPolicy: - Assert.NotNull (config.HttpCookieStorage, "HTTPCookieStorage"); + Assert.That (config.HttpCookieStorage, Is.Not.Null, "HTTPCookieStorage"); config.HttpCookieStorage = config.HttpCookieStorage; // setHTTPCookieStorage: // iOS 7.x returned 6 (instead of 4) Assert.That (config.HttpMaximumConnectionsPerHost, Is.GreaterThanOrEqualTo ((nint) 4), "HTTPMaximumConnectionsPerHost"); config.HttpMaximumConnectionsPerHost = config.HttpMaximumConnectionsPerHost; // setHTTPMaximumConnectionsPerHost: - Assert.True (config.HttpShouldSetCookies, "HTTPShouldSetCookies"); + Assert.That (config.HttpShouldSetCookies, Is.True, "HTTPShouldSetCookies"); config.HttpShouldSetCookies = config.HttpShouldSetCookies; // setHTTPShouldSetCookies: - Assert.False (config.HttpShouldUsePipelining, "HTTPShouldUsePipelining"); + Assert.That (config.HttpShouldUsePipelining, Is.False, "HTTPShouldUsePipelining"); config.HttpShouldUsePipelining = config.HttpShouldUsePipelining; // setHTTPShouldUsePipelining: - Assert.Null (config.Identifier, "identifier"); + Assert.That (config.Identifier, Is.Null, "identifier"); Assert.That (config.NetworkServiceType, Is.EqualTo (NSUrlRequestNetworkServiceType.Default), "networkServiceType"); config.NetworkServiceType = config.NetworkServiceType; // setNetworkServiceType: @@ -77,7 +77,7 @@ public void Default_Properties () Assert.That (config.RequestCachePolicy, Is.EqualTo (NSUrlRequestCachePolicy.UseProtocolCachePolicy), "requestCachePolicy"); config.RequestCachePolicy = config.RequestCachePolicy; // setRequestCachePolicy: - Assert.False (config.SessionSendsLaunchEvents, "sessionSendsLaunchEvents"); + Assert.That (config.SessionSendsLaunchEvents, Is.False, "sessionSendsLaunchEvents"); config.SessionSendsLaunchEvents = config.SessionSendsLaunchEvents; // setSessionSendsLaunchEvents: var hasSharedContainerIdentifier = true; @@ -87,7 +87,7 @@ public void Default_Properties () hasSharedContainerIdentifier = TestRuntime.CheckXcodeVersion (6, 0); #endif if (hasSharedContainerIdentifier) { - Assert.Null (config.SharedContainerIdentifier, "sharedContainerIdentifier"); + Assert.That (config.SharedContainerIdentifier, Is.Null, "sharedContainerIdentifier"); config.SharedContainerIdentifier = config.SharedContainerIdentifier; // setSharedContainerIdentifier: } @@ -104,10 +104,10 @@ public void Default_Properties () Assert.That (config.TLSMinimumSupportedProtocol, Is.GreaterThanOrEqualTo (SslProtocol.Ssl_3_0), "TLSMinimumSupportedProtocol"); config.TLSMinimumSupportedProtocol = config.TLSMinimumSupportedProtocol; // setTLSMinimumSupportedProtocol: - Assert.NotNull (config.URLCache, "URLCache"); + Assert.That (config.URLCache, Is.Not.Null, "URLCache"); config.URLCache = config.URLCache; // setURLCache: - Assert.NotNull (config.URLCredentialStorage, "URLCredentialStorage"); + Assert.That (config.URLCredentialStorage, Is.Not.Null, "URLCredentialStorage"); config.URLCredentialStorage = config.URLCredentialStorage; // setURLCredentialStorage: var hasProtocolClasses = true; @@ -117,9 +117,9 @@ public void Default_Properties () hasProtocolClasses = TestRuntime.CheckXcodeVersion (6, 0); #endif if (hasProtocolClasses) { - Assert.NotNull (config.WeakProtocolClasses, "protocolClasses"); + Assert.That (config.WeakProtocolClasses, Is.Not.Null, "protocolClasses"); } else { - Assert.Null (config.WeakProtocolClasses, "protocolClasses"); + Assert.That (config.WeakProtocolClasses, Is.Null, "protocolClasses"); } config.WeakProtocolClasses = config.WeakProtocolClasses; // setProtocolClasses: } diff --git a/tests/monotouch-test/Foundation/UrlSessionTaskMetricsTest.cs b/tests/monotouch-test/Foundation/UrlSessionTaskMetricsTest.cs index b7053a0f57c4..298dde7cb834 100644 --- a/tests/monotouch-test/Foundation/UrlSessionTaskMetricsTest.cs +++ b/tests/monotouch-test/Foundation/UrlSessionTaskMetricsTest.cs @@ -28,7 +28,7 @@ public void Properties () // in iOS10 those selectors do not respond - but they do work (forwarded to __NSCFURLSessionTaskMetrics type ?) Assert.That (stm.RedirectCount, Is.EqualTo ((nuint) 0), "RedirectCount"); Assert.That (stm.TaskInterval.Duration, Is.EqualTo (0), "TaskInterval"); - Assert.Null (stm.TransactionMetrics, "TransactionMetrics"); + Assert.That (stm.TransactionMetrics, Is.Null, "TransactionMetrics"); } } } diff --git a/tests/monotouch-test/Foundation/UrlSessionTaskTest.cs b/tests/monotouch-test/Foundation/UrlSessionTaskTest.cs index 63b16cf303de..8de57b4e4e47 100644 --- a/tests/monotouch-test/Foundation/UrlSessionTaskTest.cs +++ b/tests/monotouch-test/Foundation/UrlSessionTaskTest.cs @@ -36,21 +36,21 @@ public void Properties () Assert.That (task.BytesExpectedToSend, Is.EqualTo (0), "countOfBytesExpectedToSend"); Assert.That (task.BytesReceived, Is.EqualTo (0), "countOfBytesReceived"); Assert.That (task.BytesSent, Is.EqualTo (0), "countOfBytesSent"); - Assert.NotNull (task.CurrentRequest, "currentRequest"); - Assert.Null (task.Error, "error"); - Assert.NotNull (task.OriginalRequest, "originalRequest"); - Assert.Null (task.Response, "response"); + Assert.That (task.CurrentRequest, Is.Not.Null, "currentRequest"); + Assert.That (task.Error, Is.Null, "error"); + Assert.That (task.OriginalRequest, Is.Not.Null, "originalRequest"); + Assert.That (task.Response, Is.Null, "response"); Assert.That (task.State, Is.EqualTo (NSUrlSessionTaskState.Suspended), "state"); - Assert.Null (task.TaskDescription, "taskDescription"); + Assert.That (task.TaskDescription, Is.Null, "taskDescription"); task.TaskDescription = "descriptive label"; Assert.That ((string) task.TaskDescription, Is.EqualTo ("descriptive label"), "setTaskDescription:"); Assert.That (task.TaskIdentifier, Is.GreaterThanOrEqualTo ((nuint) 0), "taskIdentifier"); if (TestRuntime.CheckXcodeVersion (9, 0)) { - Assert.Null (task.EarliestBeginDate, "earliestBeginDate"); + Assert.That (task.EarliestBeginDate, Is.Null, "earliestBeginDate"); Assert.That (task.CountOfBytesClientExpectsToSend, Is.EqualTo (-1), "countOfBytesClientExpectsToSend"); Assert.That (task.CountOfBytesClientExpectsToReceive, Is.EqualTo (-1), "countOfBytesClientExpectsToReceive"); - Assert.NotNull (task.Progress, "progress"); + Assert.That (task.Progress, Is.Not.Null, "progress"); } } } @@ -63,29 +63,29 @@ public void NSUrlSessionDownloadTaskTest () using (var ur = new NSUrlRequest ()) { NSUrlSessionDownloadTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateDownloadTask (ur), "Should not throw InvalidCastException"); - Assert.IsNotNull (task, "task should not be null"); - Assert.IsInstanceOf (typeof (NSUrlSessionDownloadTask), task, "task should be an instance of NSUrlSessionDownloadTask"); + Assert.That (task, Is.Not.Null, "task should not be null"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionDownloadTask)), "task should be an instance of NSUrlSessionDownloadTask"); } using (var ur = new NSUrlRequest ()) { NSUrlSessionDownloadTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateDownloadTask (ur, null), "Should not throw InvalidCastException 2"); - Assert.IsNotNull (task, "task should not be null 2"); - Assert.IsInstanceOf (typeof (NSUrlSessionDownloadTask), task, "task should be an instance of NSUrlSessionDownloadTask 2"); + Assert.That (task, Is.Not.Null, "task should not be null 2"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionDownloadTask)), "task should be an instance of NSUrlSessionDownloadTask 2"); } using (var ur = new NSUrl (NetworkResources.MicrosoftUrl)) { NSUrlSessionDownloadTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateDownloadTask (ur), "Should not throw InvalidCastException 3"); - Assert.IsNotNull (task, "task should not be null 3"); - Assert.IsInstanceOf (typeof (NSUrlSessionDownloadTask), task, "task should be an instance of NSUrlSessionDownloadTask 3"); + Assert.That (task, Is.Not.Null, "task should not be null 3"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionDownloadTask)), "task should be an instance of NSUrlSessionDownloadTask 3"); } using (var ur = new NSUrl (NetworkResources.MicrosoftUrl)) { NSUrlSessionDownloadTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateDownloadTask (ur, null), "Should not throw InvalidCastException 4"); - Assert.IsNotNull (task, "task should not be null 4"); - Assert.IsInstanceOf (typeof (NSUrlSessionDownloadTask), task, "task should be an instance of NSUrlSessionDownloadTask 4"); + Assert.That (task, Is.Not.Null, "task should not be null 4"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionDownloadTask)), "task should be an instance of NSUrlSessionDownloadTask 4"); } } @@ -97,29 +97,29 @@ public void NSUrlSessionDataTaskTest () using (var ur = new NSUrlRequest ()) { NSUrlSessionDataTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateDataTask (ur), "Should not throw InvalidCastException"); - Assert.IsNotNull (task, "task should not be null"); - Assert.IsInstanceOf (typeof (NSUrlSessionDataTask), task, "task should be an instance of NSUrlSessionDataTask"); + Assert.That (task, Is.Not.Null, "task should not be null"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionDataTask)), "task should be an instance of NSUrlSessionDataTask"); } using (var ur = new NSUrlRequest ()) { NSUrlSessionDataTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateDataTask (ur, null), "Should not throw InvalidCastException 2"); - Assert.IsNotNull (task, "task should not be null 2"); - Assert.IsInstanceOf (typeof (NSUrlSessionDataTask), task, "task should be an instance of NSUrlSessionDataTask 2"); + Assert.That (task, Is.Not.Null, "task should not be null 2"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionDataTask)), "task should be an instance of NSUrlSessionDataTask 2"); } using (var ur = new NSUrl (NetworkResources.MicrosoftUrl)) { NSUrlSessionDataTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateDataTask (ur), "Should not throw InvalidCastException 3"); - Assert.IsNotNull (task, "task should not be null 3"); - Assert.IsInstanceOf (typeof (NSUrlSessionDataTask), task, "task should be an instance of NSUrlSessionDataTask 3"); + Assert.That (task, Is.Not.Null, "task should not be null 3"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionDataTask)), "task should be an instance of NSUrlSessionDataTask 3"); } using (var ur = new NSUrl (NetworkResources.MicrosoftUrl)) { NSUrlSessionDataTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateDataTask (ur, null), "Should not throw InvalidCastException 4"); - Assert.IsNotNull (task, "task should not be null 4"); - Assert.IsInstanceOf (typeof (NSUrlSessionDataTask), task, "task should be an instance of NSUrlSessionDataTask 4"); + Assert.That (task, Is.Not.Null, "task should not be null 4"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionDataTask)), "task should be an instance of NSUrlSessionDataTask 4"); } } @@ -131,40 +131,40 @@ public void NSUrlSessionUploadTaskTest () using (var ur = new NSUrlRequest ()) { NSUrlSessionUploadTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateUploadTask (ur), "Should not throw InvalidCastException"); - Assert.IsNotNull (task, "task should not be null"); - Assert.IsInstanceOf (typeof (NSUrlSessionUploadTask), task, "task should be an instance of NSUrlSessionUploadTask"); + Assert.That (task, Is.Not.Null, "task should not be null"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionUploadTask)), "task should be an instance of NSUrlSessionUploadTask"); } using (var data = NSData.FromString ("Hola")) using (var ur = new NSUrlRequest ()) { NSUrlSessionUploadTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateUploadTask (ur, data), "Should not throw InvalidCastException 2"); - Assert.IsNotNull (task, "task should not be null 2"); - Assert.IsInstanceOf (typeof (NSUrlSessionUploadTask), task, "task should be an instance of NSUrlSessionUploadTask 2"); + Assert.That (task, Is.Not.Null, "task should not be null 2"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionUploadTask)), "task should be an instance of NSUrlSessionUploadTask 2"); } using (var ur = new NSUrlRequest ()) using (var url = new NSUrl (NetworkResources.MicrosoftUrl)) { NSUrlSessionUploadTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateUploadTask (ur, url), "Should not throw InvalidCastException 3"); - Assert.IsNotNull (task, "task should not be null 3"); - Assert.IsInstanceOf (typeof (NSUrlSessionUploadTask), task, "task should be an instance of NSUrlSessionUploadTask 3"); + Assert.That (task, Is.Not.Null, "task should not be null 3"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionUploadTask)), "task should be an instance of NSUrlSessionUploadTask 3"); } using (var ur = new NSUrlRequest ()) using (var url = new NSUrl (NetworkResources.MicrosoftUrl)) { NSUrlSessionUploadTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateUploadTask (ur, url, (data, response, error) => { }), "Should not throw InvalidCastException 4"); - Assert.IsNotNull (task, "task should not be null 4"); - Assert.IsInstanceOf (typeof (NSUrlSessionUploadTask), task, "task should be an instance of NSUrlSessionUploadTask 4"); + Assert.That (task, Is.Not.Null, "task should not be null 4"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionUploadTask)), "task should be an instance of NSUrlSessionUploadTask 4"); } using (var ur = new NSUrlRequest ()) using (var data = NSData.FromString ("Hola")) { NSUrlSessionUploadTask task = null; Assert.DoesNotThrow (() => task = NSUrlSession.SharedSession.CreateUploadTask (ur, data, (d, response, error) => { }), "Should not throw InvalidCastException 5"); - Assert.IsNotNull (task, "task should not be null 5"); - Assert.IsInstanceOf (typeof (NSUrlSessionUploadTask), task, "task should be an instance of NSUrlSessionUploadTask 5"); + Assert.That (task, Is.Not.Null, "task should not be null 5"); + Assert.That (task, Is.InstanceOf (typeof (NSUrlSessionUploadTask)), "task should be an instance of NSUrlSessionUploadTask 5"); } } } diff --git a/tests/monotouch-test/Foundation/UrlSessionTaskTransactionMetricsTest.cs b/tests/monotouch-test/Foundation/UrlSessionTaskTransactionMetricsTest.cs index 52d2d1585d22..3ad892c687b0 100644 --- a/tests/monotouch-test/Foundation/UrlSessionTaskTransactionMetricsTest.cs +++ b/tests/monotouch-test/Foundation/UrlSessionTaskTransactionMetricsTest.cs @@ -26,37 +26,37 @@ public void Properties () using (var sttm = new NSUrlSessionTaskTransactionMetrics ()) { // in iOS10 those selectors do not respond - but they do work (forwarded to __NSCFURLSessionTaskMetrics type ?) - Assert.Null (sttm.ConnectEndDate, "RedirectCount"); - Assert.Null (sttm.ConnectStartDate, "TaskInterval"); - Assert.Null (sttm.DomainLookupEndDate, "TransactionMetrics"); - Assert.Null (sttm.DomainLookupStartDate, "TransactionMetrics"); + Assert.That (sttm.ConnectEndDate, Is.Null, "RedirectCount"); + Assert.That (sttm.ConnectStartDate, Is.Null, "TaskInterval"); + Assert.That (sttm.DomainLookupEndDate, Is.Null, "TransactionMetrics"); + Assert.That (sttm.DomainLookupStartDate, Is.Null, "TransactionMetrics"); if (TestRuntime.CheckXcodeVersion (11, 0)) { - Assert.NotNull (sttm.FetchStartDate, "TransactionMetrics"); + Assert.That (sttm.FetchStartDate, Is.Not.Null, "TransactionMetrics"); } else { - Assert.Null (sttm.FetchStartDate, "TransactionMetrics"); + Assert.That (sttm.FetchStartDate, Is.Null, "TransactionMetrics"); } - Assert.Null (sttm.NetworkProtocolName, "TransactionMetrics"); - Assert.False (sttm.ProxyConnection, "TransactionMetrics"); - Assert.NotNull (sttm.Request, "TransactionMetrics"); + Assert.That (sttm.NetworkProtocolName, Is.Null, "TransactionMetrics"); + Assert.That (sttm.ProxyConnection, Is.False, "TransactionMetrics"); + Assert.That (sttm.Request, Is.Not.Null, "TransactionMetrics"); if (TestRuntime.CheckXcodeVersion (11, 0)) { - Assert.NotNull (sttm.RequestEndDate, "TransactionMetrics"); - Assert.NotNull (sttm.RequestStartDate, "TransactionMetrics"); + Assert.That (sttm.RequestEndDate, Is.Not.Null, "TransactionMetrics"); + Assert.That (sttm.RequestStartDate, Is.Not.Null, "TransactionMetrics"); } else { - Assert.Null (sttm.RequestEndDate, "TransactionMetrics"); - Assert.Null (sttm.RequestStartDate, "TransactionMetrics"); + Assert.That (sttm.RequestEndDate, Is.Null, "TransactionMetrics"); + Assert.That (sttm.RequestStartDate, Is.Null, "TransactionMetrics"); } Assert.That (sttm.ResourceFetchType, Is.EqualTo (NSUrlSessionTaskMetricsResourceFetchType.Unknown), "ResourceFetchType"); - Assert.Null (sttm.Response, "Response"); + Assert.That (sttm.Response, Is.Null, "Response"); if (TestRuntime.CheckXcodeVersion (11, 0)) { - Assert.NotNull (sttm.ResponseEndDate, "ResponseEndDate"); - Assert.NotNull (sttm.ResponseStartDate, "ResponseStartDate"); + Assert.That (sttm.ResponseEndDate, Is.Not.Null, "ResponseEndDate"); + Assert.That (sttm.ResponseStartDate, Is.Not.Null, "ResponseStartDate"); } else { - Assert.Null (sttm.ResponseEndDate, "ResponseEndDate"); - Assert.Null (sttm.ResponseStartDate, "ResponseStartDate"); + Assert.That (sttm.ResponseEndDate, Is.Null, "ResponseEndDate"); + Assert.That (sttm.ResponseStartDate, Is.Null, "ResponseStartDate"); } Assert.That (sttm.ReusedConnection, Is.EqualTo (true).Or.EqualTo (false), "ReusedConnection"); - Assert.Null (sttm.SecureConnectionEndDate, "SecureConnectionEndDate"); - Assert.Null (sttm.SecureConnectionStartDate, "SecureConnectionStartDate"); + Assert.That (sttm.SecureConnectionEndDate, Is.Null, "SecureConnectionEndDate"); + Assert.That (sttm.SecureConnectionStartDate, Is.Null, "SecureConnectionStartDate"); } } } diff --git a/tests/monotouch-test/Foundation/UrlSessionTest.cs b/tests/monotouch-test/Foundation/UrlSessionTest.cs index fb646869334c..6cd40f773c95 100644 --- a/tests/monotouch-test/Foundation/UrlSessionTest.cs +++ b/tests/monotouch-test/Foundation/UrlSessionTest.cs @@ -29,12 +29,12 @@ void AssertTrueOrIgnoreInCI (Task task, string message) if (value) { TestRuntime.IgnoreInCIIfBadNetwork (ex); - Assert.IsNull (ex, message + " Exception"); + Assert.That (ex, Is.Null, message + " Exception"); return; } TestRuntime.IgnoreInCI ($"This test times out randomly in CI due to bad network: {message}"); - Assert.IsNull (ex, $"Exception - {message}"); + Assert.That (ex, Is.Null, $"Exception - {message}"); Assert.Fail (message); } @@ -91,8 +91,8 @@ public void DownloadDataAsync () }, out var ex); TestRuntime.IgnoreInCIIfBadNetwork (ex); - Assert.IsNull (ex, "Exception"); - Assert.AreEqual (-1, failed_iteration, "Failed"); + Assert.That (ex, Is.Null, "Exception"); + Assert.That (failed_iteration, Is.EqualTo (-1), "Failed"); } [Test] @@ -104,9 +104,9 @@ public void SharedSession () // in iOS9 those selectors do not respond - but they do work (forwarded to __NSURLSessionLocal type ?) // * delegateQueue, sessionDescription, setSessionDescription:, delegate var session = NSUrlSession.SharedSession; - Assert.Null (session.Delegate, "delegate"); - Assert.NotNull (session.DelegateQueue, "delegateQueue"); - Assert.Null (session.SessionDescription, "sessionDescription"); + Assert.That (session.Delegate, Is.Null, "delegate"); + Assert.That (session.DelegateQueue, Is.Not.Null, "delegateQueue"); + Assert.That (session.SessionDescription, Is.Null, "sessionDescription"); session.SessionDescription = "descriptive label"; Assert.That ((string) session.SessionDescription, Is.EqualTo ("descriptive label"), "setSessionDescription:"); session.SessionDescription = null; // the session instance is global, so revert value to to make sure the test can be re-run successfully. diff --git a/tests/monotouch-test/Foundation/UrlTest.cs b/tests/monotouch-test/Foundation/UrlTest.cs index 277195d2263a..287e997021ae 100644 --- a/tests/monotouch-test/Foundation/UrlTest.cs +++ b/tests/monotouch-test/Foundation/UrlTest.cs @@ -41,7 +41,7 @@ public void IsExcludedFromBackupKey () // was important to track this down NSObject value; - Assert.True (NSBundle.MainBundle.ExecutableUrl.TryGetResource (NSUrl.IsExcludedFromBackupKey, out value), "MainBundle"); + Assert.That (NSBundle.MainBundle.ExecutableUrl.TryGetResource (NSUrl.IsExcludedFromBackupKey, out value), Is.True, "MainBundle"); Assert.That (value, Is.TypeOf (typeof (NSNumber)), "NSNumber"); Assert.That ((int) (value as NSNumber), Is.EqualTo (0), "0"); @@ -50,17 +50,17 @@ public void IsExcludedFromBackupKey () try { File.WriteAllText (filename, "not worth a bit"); using (NSUrl url = NSUrl.FromFilename (filename)) { - Assert.True (url.TryGetResource (NSUrl.IsExcludedFromBackupKey, out value)); + Assert.That (url.TryGetResource (NSUrl.IsExcludedFromBackupKey, out value), Is.True); Assert.That ((int) (value as NSNumber), Is.EqualTo (0), "DoNotBackupMe-0"); url.SetResource (NSUrl.IsExcludedFromBackupKey, (NSNumber) 1); - Assert.True (url.TryGetResource (NSUrl.IsExcludedFromBackupKey, out value)); + Assert.That (url.TryGetResource (NSUrl.IsExcludedFromBackupKey, out value), Is.True); Assert.That ((int) (value as NSNumber), Is.EqualTo (1), "DoNotBackupMe-1"); NSError error; NSDictionary dict = url.GetResourceValues (new NSString [] { NSUrl.IsExcludedFromBackupKey }, out error); - Assert.Null (error, "error"); + Assert.That (error, Is.Null, "error"); Assert.That (dict.Keys [0], Is.EqualTo (NSUrl.IsExcludedFromBackupKey), "Key"); Assert.That ((int) (dict.Values [0] as NSNumber), Is.EqualTo (1), "Value"); } @@ -78,9 +78,9 @@ public void FromString () { if (TestRuntime.CheckXcodeVersion (15, 0)) { using (var url = NSUrl.FromString (bad_uri)) - Assert.NotNull (bad_uri, "invalid"); + Assert.That (bad_uri, Is.Not.Null, "invalid"); } else { - Assert.Null (NSUrl.FromString (bad_uri), "invalid"); + Assert.That (NSUrl.FromString (bad_uri), Is.Null, "invalid"); } using (var url = NSUrl.FromString (good_uri)) { @@ -88,7 +88,7 @@ public void FromString () Assert.That (url.PathExtension, Is.EqualTo (String.Empty), "PathExtension-1"); - Assert.NotNull (url.ToString (), "ToString"); // see #4763 + Assert.That (url.ToString (), Is.Not.Null, "ToString"); // see #4763 } using (var url = NSUrl.FromString ("file.extension")) { @@ -117,13 +117,13 @@ public void Unicode_6597 () const string bug6597 = "http://www.bing.com/images/search?q=雅詩蘭黛"; if (TestRuntime.CheckXcodeVersion (15, 0)) { - Assert.NotNull (NSUrl.FromString (bug6597), "1"); + Assert.That (NSUrl.FromString (bug6597), Is.Not.Null, "1"); using (var url = new NSUrl (bug6597)) - Assert.NotNull (url, "exception"); + Assert.That (url, Is.Not.Null, "exception"); } else { // does not work - From* static methods returns null for invalid URL - Assert.Null (NSUrl.FromString (bug6597), "1"); + Assert.That (NSUrl.FromString (bug6597), Is.Null, "1"); // does not work - handle is null (as a .NET .ctor can't return null like ObjC init can do) Assert.Throws (() => new NSUrl (bug6597), "exception"); @@ -161,7 +161,7 @@ public void InitWithSpaces () if (TestRuntime.CheckXcodeVersion (15, 0)) { using (var url = NSUrl.FromString (file)) - Assert.NotNull (url, "1"); + Assert.That (url, Is.Not.Null, "1"); } else { // initWithString: will fail with spaces Assert.Throws (() => new NSUrl (file), "1"); @@ -207,14 +207,14 @@ public void Equals () Assert.That (url2.GetHashCode (), Is.EqualTo (url3.GetHashCode ()), "GetHashCode 2-3"); // NSObject - Assert.False (url1.Equals ((NSObject) url2), "Equals(NSObject) 1-2"); - Assert.True (url2.Equals ((NSObject) url3), "Equals(NSObject) 2-3"); - Assert.False (url1.Equals ((NSObject) null), "Equals(NSObject) null"); + Assert.That (url1.Equals ((NSObject) url2), Is.False, "Equals(NSObject) 1-2"); + Assert.That (url2.Equals ((NSObject) url3), Is.True, "Equals(NSObject) 2-3"); + Assert.That (url1.Equals ((NSObject) null), Is.False, "Equals(NSObject) null"); // NSUrl / IEquatable - Assert.False (url1.Equals (url2), "Equals(NSUrl) 1-2"); - Assert.True (url2.Equals (url3), "Equals(NSUrl) 2-3"); - Assert.False (url1.Equals ((NSUrl) null), "Equals(NSUrl) null"); + Assert.That (url1.Equals (url2), Is.False, "Equals(NSUrl) 1-2"); + Assert.That (url2.Equals (url3), Is.True, "Equals(NSUrl) 2-3"); + Assert.That (url1.Equals ((NSUrl) null), Is.False, "Equals(NSUrl) null"); } } @@ -268,21 +268,21 @@ public void SubclassEquality () Assert.That (url1.GetHashCode (), Is.Not.EqualTo (url2.GetHashCode ()), "GetHashCode 1-2"); Assert.That (url2.GetHashCode (), Is.Not.EqualTo (url3.GetHashCode ()), "GetHashCode 2-3"); - Assert.False (url2.DirectBinding, "DirectBinding 2"); - Assert.False (url3.DirectBinding, "DirectBinding 3"); + Assert.That (url2.DirectBinding, Is.False, "DirectBinding 2"); + Assert.That (url3.DirectBinding, Is.False, "DirectBinding 3"); Assert.That (url2.GetHashCode (), Is.Not.EqualTo (url3.GetHashCode ()), "GetHashCode 2-3"); // NSObject - Assert.False (url1.Equals ((NSObject) url2), "Equals(NSObject) 1-2"); - Assert.False (url2.Equals ((NSObject) url3), "Equals(NSObject) 2-3"); + Assert.That (url1.Equals ((NSObject) url2), Is.False, "Equals(NSObject) 1-2"); + Assert.That (url2.Equals ((NSObject) url3), Is.False, "Equals(NSObject) 2-3"); // NSUrl / IEquatable - Assert.False (url1.Equals (url2), "Equals(NSUrl) 1-2"); - Assert.False (url2.Equals (url3), "Equals(NSUrl) 2-3"); + Assert.That (url1.Equals (url2), Is.False, "Equals(NSUrl) 1-2"); + Assert.That (url2.Equals (url3), Is.False, "Equals(NSUrl) 2-3"); // System.Object - Assert.False (url1.Equals ((object) url2), "Equals(object) 1-2"); - Assert.False (url2.Equals ((object) url3), "Equals(object) 2-3"); + Assert.That (url1.Equals ((object) url2), Is.False, "Equals(object) 1-2"); + Assert.That (url2.Equals ((object) url3), Is.False, "Equals(object) 2-3"); } } @@ -296,9 +296,9 @@ public void Invalid_29510 () #pragma warning restore if (TestRuntime.CheckXcodeVersion (15, 0)) { using (var url = NSUrl.FromString (bad_url)) - Assert.NotNull (bad_url, "bad"); + Assert.That (bad_url, Is.Not.Null, "bad"); } else { - Assert.Null (NSUrl.FromString (bad_url), "bad"); + Assert.That (NSUrl.FromString (bad_url), Is.Null, "bad"); } string converted = ((NSString) bad).CreateStringByAddingPercentEscapes (NSStringEncoding.UTF8); @@ -312,7 +312,7 @@ public void TestEqualOperatorSameInstace () { using (var url = NSUrl.FromString ("http://www.xamarin.com")) #pragma warning disable CS1718 // warning CS1718: Comparison made to same variable; did you mean to compare something else? - Assert.IsTrue (url == url); + Assert.That (url == url, Is.True); #pragma warning restore } @@ -321,8 +321,8 @@ public void TestEqualOperatorSameInstace () public void TestEqualOperatorNull () { using (var url = NSUrl.FromString ("http://www.xamarin.com")) { - Assert.IsFalse (url is null, "url is null"); - Assert.IsFalse (null == url, "null == url"); + Assert.That (url is null, Is.False, "url is null"); + Assert.That (null == url, Is.False, "null == url"); } } @@ -331,15 +331,15 @@ public void TestEqualOperator () { using (var url1 = NSUrl.FromString ("http://www.xamarin.com")) using (var url2 = NSUrl.FromString ("http://www.xamarin.com/foo")) - Assert.AreEqual (url1 == url2, url1.IsEqual (url2)); + Assert.That (url1.IsEqual (url2), Is.EqualTo (url1 == url2)); } [Test] public void TestNotEqualOperatorNull () { using (var url = NSUrl.FromString ("http://www.xamarin.com")) { - Assert.IsTrue (url is not null, "url is not null"); - Assert.IsTrue (null != url, "null != url"); + Assert.That (url is not null, Is.True, "url is not null"); + Assert.That (null != url, Is.True, "null != url"); } } @@ -348,7 +348,7 @@ public void TestNotEqualOperator () { using (var url1 = NSUrl.FromString ("http://www.xamarin.com")) using (var url2 = NSUrl.FromString ("http://www.xamarin.com/foo")) - Assert.AreEqual (url1 != url2, !url1.IsEqual (url2)); + Assert.That (!url1.IsEqual (url2), Is.EqualTo (url1 != url2)); } [TestCase ("http://microsoft.com/", UriKind.Absolute)] @@ -361,16 +361,16 @@ public void TestNotEqualOperator () public void ImplicitOperatorRoundTrip (string value, UriKind kind) { var nsurl = new NSUrl (value); - Assert.AreEqual (nsurl.ToString (), ((NSUrl) (Uri) nsurl).ToString (), "RoundTrip NSUrl"); + Assert.That (((NSUrl) (Uri) nsurl).ToString (), Is.EqualTo (nsurl.ToString ()), "RoundTrip NSUrl"); var url = new Uri (value, kind); - Assert.AreEqual (url.ToString (), ((Uri) (NSUrl) url).ToString (), "RoundTrip Uri"); + Assert.That (((Uri) (NSUrl) url).ToString (), Is.EqualTo (url.ToString ()), "RoundTrip Uri"); } [Test] public void FromNullString () { - Assert.IsNull (NSUrl.FromString (null)); + Assert.That (NSUrl.FromString (null), Is.Null); } } } diff --git a/tests/monotouch-test/Foundation/UserDefaultsTest.cs b/tests/monotouch-test/Foundation/UserDefaultsTest.cs index 09e77b56aacd..682f21c9086c 100644 --- a/tests/monotouch-test/Foundation/UserDefaultsTest.cs +++ b/tests/monotouch-test/Foundation/UserDefaultsTest.cs @@ -29,14 +29,14 @@ public void SetString () NSUserDefaults defaults = NSUserDefaults.StandardUserDefaults; var keyName = $"spid-{Process.GetCurrentProcess ().Id}"; defaults.RemoveObject (keyName); - Assert.Null (defaults.StringForKey (keyName), "StringForKey-1"); + Assert.That (defaults.StringForKey (keyName), Is.Null, "StringForKey-1"); defaults.SetString ("coucou", keyName); defaults.Synchronize (); Assert.That (defaults.StringForKey (keyName), Is.EqualTo ("coucou"), "StringForKey-2"); // Clean up after ourselves. defaults.RemoveObject (keyName); defaults.Synchronize (); - Assert.IsNull (defaults.StringForKey (keyName), "StringForKey-3"); + Assert.That (defaults.StringForKey (keyName), Is.Null, "StringForKey-3"); } [Test] @@ -59,7 +59,7 @@ public void Ctor_UserName () Assert.That (keyValue.ToString (), Is.EqualTo ("value"), "[key]-1"); ud.RemoveObject (keyName); ud.Synchronize (); - Assert.Null (ud [keyName], "[key]-2"); + Assert.That (ud [keyName], Is.Null, "[key]-2"); } } diff --git a/tests/monotouch-test/Foundation/UuidTest.cs b/tests/monotouch-test/Foundation/UuidTest.cs index 47315d5cad01..9ba081420dfa 100644 --- a/tests/monotouch-test/Foundation/UuidTest.cs +++ b/tests/monotouch-test/Foundation/UuidTest.cs @@ -46,7 +46,7 @@ public void ConstructorFailures () } catch (ArgumentNullException) { // good } catch (Exception e) { - Assert.Fail ("Unexpected exception {0}", e); + Assert.Fail ($"Unexpected exception {e}"); } try { @@ -55,7 +55,7 @@ public void ConstructorFailures () } catch (ArgumentException) { // ok } catch (Exception e) { - Assert.Fail ("Expected an ArgumentException {0}", e); + Assert.Fail ($"Expected an ArgumentException {e}"); } } } diff --git a/tests/monotouch-test/GameController/ExtendedGamepadSnapshotTest.cs b/tests/monotouch-test/GameController/ExtendedGamepadSnapshotTest.cs index b34fe6e2a747..b93551023f85 100644 --- a/tests/monotouch-test/GameController/ExtendedGamepadSnapshotTest.cs +++ b/tests/monotouch-test/GameController/ExtendedGamepadSnapshotTest.cs @@ -25,18 +25,18 @@ public void Nullability () Assert.Inconclusive ("GameController is iOS7+ or macOS 10.9+"); GCExtendedGamepadSnapShotDataV100 data; - Assert.False (GCExtendedGamepadSnapshot.TryGetSnapShotData (null, out data), "TryGetSnapshotData"); - Assert.True (data.Version == 0, "Version"); - Assert.True (data.Size == 0, "Size"); + Assert.That (GCExtendedGamepadSnapshot.TryGetSnapShotData (null, out data), Is.False, "TryGetSnapshotData"); + Assert.That (data.Version == 0, Is.True, "Version"); + Assert.That (data.Size == 0, Is.True, "Size"); data = new GCExtendedGamepadSnapShotDataV100 (); - Assert.True (data.Version == 0, "Version-2"); - Assert.True (data.Size == 0, "Size-2"); + Assert.That (data.Version == 0, Is.True, "Version-2"); + Assert.That (data.Size == 0, Is.True, "Size-2"); using (var nsd = data.ToNSData ()) { - Assert.True (GCExtendedGamepadSnapshot.TryGetSnapShotData (nsd, out data), "TryGetSnapshotData-2"); - Assert.True (data.Version == 0x100, "Version-3"); - Assert.True (data.Size == nsd.Length, "Size-3"); + Assert.That (GCExtendedGamepadSnapshot.TryGetSnapShotData (nsd, out data), Is.True, "TryGetSnapshotData-2"); + Assert.That (data.Version == 0x100, Is.True, "Version-3"); + Assert.That (data.Size == nsd.Length, Is.True, "Size-3"); } } } diff --git a/tests/monotouch-test/GameController/GCPoint2Test.cs b/tests/monotouch-test/GameController/GCPoint2Test.cs index 560c7686ee9e..eb7d3ba08c1b 100644 --- a/tests/monotouch-test/GameController/GCPoint2Test.cs +++ b/tests/monotouch-test/GameController/GCPoint2Test.cs @@ -48,8 +48,8 @@ public void TheTest () Assert.That (x, Is.EqualTo ((nfloat) 3), "X#5"); Assert.That (y, Is.EqualTo ((nfloat) 4), "Y#5"); - Assert.AreEqual (pnt.ToString (), "{3, 4}", "ToString A"); - Assert.AreEqual (GCPoint2.Zero.ToString (), "{0, 0}", "ToString B"); + Assert.That (pnt.ToString (), Is.EqualTo ("{3, 4}"), "ToString A"); + Assert.That (GCPoint2.Zero.ToString (), Is.EqualTo ("{0, 0}"), "ToString B"); }); } } diff --git a/tests/monotouch-test/GameController/GamepadSnapshotTest.cs b/tests/monotouch-test/GameController/GamepadSnapshotTest.cs index d3c673637f35..479fe23c9e75 100644 --- a/tests/monotouch-test/GameController/GamepadSnapshotTest.cs +++ b/tests/monotouch-test/GameController/GamepadSnapshotTest.cs @@ -25,18 +25,18 @@ public void Nullability () Assert.Inconclusive ("GameController is iOS7+ or macOS 10.9+"); GCGamepadSnapShotDataV100 data; - Assert.False (GCGamepadSnapshot.TryGetSnapshotData (null, out data), "TryGetSnapshotData"); - Assert.True (data.Version == 0, "Version"); - Assert.True (data.Size == 0, "Size"); + Assert.That (GCGamepadSnapshot.TryGetSnapshotData (null, out data), Is.False, "TryGetSnapshotData"); + Assert.That (data.Version == 0, Is.True, "Version"); + Assert.That (data.Size == 0, Is.True, "Size"); data = new GCGamepadSnapShotDataV100 (); - Assert.True (data.Version == 0, "Version-2"); - Assert.True (data.Size == 0, "Size-2"); + Assert.That (data.Version == 0, Is.True, "Version-2"); + Assert.That (data.Size == 0, Is.True, "Size-2"); using (var nsd = data.ToNSData ()) { - Assert.True (GCGamepadSnapshot.TryGetSnapshotData (nsd, out data), "TryGetSnapshotData-2"); - Assert.True (data.Version == 0x100, "Version-3"); - Assert.True (data.Size == nsd.Length, "Size-3"); + Assert.That (GCGamepadSnapshot.TryGetSnapshotData (nsd, out data), Is.True, "TryGetSnapshotData-2"); + Assert.That (data.Version == 0x100, Is.True, "Version-3"); + Assert.That (data.Size == nsd.Length, Is.True, "Size-3"); } } } diff --git a/tests/monotouch-test/GameKit/GKGameCenterViewControllerTest.cs b/tests/monotouch-test/GameKit/GKGameCenterViewControllerTest.cs index 71ec233dab1d..884e9a8557df 100644 --- a/tests/monotouch-test/GameKit/GKGameCenterViewControllerTest.cs +++ b/tests/monotouch-test/GameKit/GKGameCenterViewControllerTest.cs @@ -20,7 +20,7 @@ public void StringCtor () { TestRuntime.AssertXcodeVersion (12, 0); using var controller = new GKGameCenterViewController ("achievementId"); - Assert.AreEqual (controller.ViewState, GKGameCenterViewControllerState.Achievements, "ViewState"); + Assert.That (GKGameCenterViewControllerState.Achievements, Is.EqualTo (controller.ViewState), "ViewState"); } [Test] @@ -28,7 +28,7 @@ public void StringOptionCtor_AchievementId () { TestRuntime.AssertXcodeVersion (12, 0); using var controller = new GKGameCenterViewController ("achievementId", GKGameCenterViewControllerInitializationOption.Achievement); - Assert.AreEqual (controller.ViewState, GKGameCenterViewControllerState.Achievements, "ViewState"); + Assert.That (GKGameCenterViewControllerState.Achievements, Is.EqualTo (controller.ViewState), "ViewState"); } [Test] @@ -36,7 +36,7 @@ public void StringOptionCtor_LeaderboardSetId () { TestRuntime.AssertXcodeVersion (16, 0); using var controller = new GKGameCenterViewController ("achievementId", GKGameCenterViewControllerInitializationOption.LeaderboardSet); - Assert.AreEqual (controller.ViewState, GKGameCenterViewControllerState.Leaderboards, "ViewState"); + Assert.That (GKGameCenterViewControllerState.Leaderboards, Is.EqualTo (controller.ViewState), "ViewState"); } } } diff --git a/tests/monotouch-test/GameKit/LeaderboardTest.cs b/tests/monotouch-test/GameKit/LeaderboardTest.cs index 3801a94062ae..dfef03944b20 100644 --- a/tests/monotouch-test/GameKit/LeaderboardTest.cs +++ b/tests/monotouch-test/GameKit/LeaderboardTest.cs @@ -24,7 +24,7 @@ public class LeaderboardTest { void Check (GKLeaderboard lb) { #if !__TVOS__ - Assert.Null (lb.Category, "Category"); + Assert.That (lb.Category, Is.Null, "Category"); #endif #if __MACOS__ var hasGroupIdentifier = true; @@ -40,11 +40,11 @@ void Check (GKLeaderboard lb) var hasRange = true; #endif if (hasGroupIdentifier) { - Assert.Null (lb.GroupIdentifier, "GroupIdentifier"); + Assert.That (lb.GroupIdentifier, Is.Null, "GroupIdentifier"); if (hasIdentifier) - Assert.Null (lb.Identifier, "Identifier"); + Assert.That (lb.Identifier, Is.Null, "Identifier"); } - Assert.Null (lb.LocalPlayerScore, "LocalPlayerScore"); + Assert.That (lb.LocalPlayerScore, Is.Null, "LocalPlayerScore"); Assert.That (lb.MaxRange, Is.EqualTo ((nint) 0), "MaxRange"); Assert.That (lb.PlayerScope, Is.EqualTo (GKLeaderboardPlayerScope.Global), "PlayerScope"); if (hasRange) { @@ -52,9 +52,9 @@ void Check (GKLeaderboard lb) Assert.That (lb.Range.Location, Is.EqualTo ((nint) 1), "Range.Location"); Assert.That (lb.Range.Length, Is.EqualTo ((nint) 25), "Range.Length"); } - Assert.Null (lb.Scores, "Scores"); + Assert.That (lb.Scores, Is.Null, "Scores"); Assert.That (lb.TimeScope, Is.EqualTo (GKLeaderboardTimeScope.AllTime), "TimeScope"); - Assert.Null (lb.Title, "Title"); + Assert.That (lb.Title, Is.Null, "Title"); } [Test] diff --git a/tests/monotouch-test/GameKit/LeaderboardViewControllerTest.cs b/tests/monotouch-test/GameKit/LeaderboardViewControllerTest.cs index fe9a46d2d5cc..32165dd40bf3 100644 --- a/tests/monotouch-test/GameKit/LeaderboardViewControllerTest.cs +++ b/tests/monotouch-test/GameKit/LeaderboardViewControllerTest.cs @@ -32,8 +32,8 @@ public void DefaultCtor () Assert.Inconclusive ("'LeaderboardViewControllerTest' the native 'init' method returned nil."); #endif using (var vc = new GKLeaderboardViewController ()) { - Assert.Null (vc.Category, "Category"); - Assert.Null (vc.Delegate, "Delegate"); + Assert.That (vc.Category, Is.Null, "Category"); + Assert.That (vc.Delegate, Is.Null, "Delegate"); // default Scope vary by iOS version and can't be changed on iOS7 - not worth testing } } diff --git a/tests/monotouch-test/GameKit/ScoreTest.cs b/tests/monotouch-test/GameKit/ScoreTest.cs index e384fae47701..0e94d5de6120 100644 --- a/tests/monotouch-test/GameKit/ScoreTest.cs +++ b/tests/monotouch-test/GameKit/ScoreTest.cs @@ -36,13 +36,13 @@ public void Ctor_String () Assert.That (s.Category, Is.EqualTo ("category-or-identifier"), "Category"); #endif Assert.That (s.Context, Is.EqualTo (0), "Context"); - Assert.NotNull (s.Date, "Date"); - Assert.Null (s.FormattedValue, "FormattedValue"); + Assert.That (s.Date, Is.Not.Null, "Date"); + Assert.That (s.FormattedValue, Is.Null, "FormattedValue"); // this is a new API in iOS8 (it was private before that) and returned an empty instance like: // "<(playerID:(null) alias:(null) name:(null) status:(null))>" if (TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 8, 0, throwIfOtherPlatform: false)) { - Assert.Null (s.Player, "Player"); + Assert.That (s.Player, Is.Null, "Player"); } if (TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false)) { diff --git a/tests/monotouch-test/GameplayKit/GKComponentSystemTests.cs b/tests/monotouch-test/GameplayKit/GKComponentSystemTests.cs index 8cc086ceac85..86854a7318c1 100644 --- a/tests/monotouch-test/GameplayKit/GKComponentSystemTests.cs +++ b/tests/monotouch-test/GameplayKit/GKComponentSystemTests.cs @@ -26,25 +26,25 @@ public void Setup () public void InitWithComponentClassType () { var componentSystem = new GKComponentSystem (); - Assert.NotNull (componentSystem, "GKComponentSystem type ctor must not be null"); - Assert.AreEqual (typeof (MySubcomponent), componentSystem.ComponentType); + Assert.That (componentSystem, Is.Not.Null, "GKComponentSystem type ctor must not be null"); + Assert.That (componentSystem.ComponentType, Is.EqualTo (typeof (MySubcomponent))); } [Test] public void IndexerTest () { var componentSystem = new GKComponentSystem (); - Assert.NotNull (componentSystem, "GKComponentSystem type ctor must not be null"); - Assert.AreEqual (typeof (MySubcomponent), componentSystem.ComponentType); + Assert.That (componentSystem, Is.Not.Null, "GKComponentSystem type ctor must not be null"); + Assert.That (componentSystem.ComponentType, Is.EqualTo (typeof (MySubcomponent))); componentSystem.AddComponent (new MySubcomponent (0)); componentSystem.AddComponent (new MySubcomponent (1)); componentSystem.AddComponent (new MySubcomponent (2)); - Assert.IsTrue (componentSystem.Components.Length == 3, "componentSystem.Components must be 3"); + Assert.That (componentSystem.Components.Length == 3, Is.True, "componentSystem.Components must be 3"); var secondComponent = componentSystem [1] as MySubcomponent; - Assert.NotNull (secondComponent, "secondComponent must not be null"); - Assert.IsTrue (secondComponent.Id == 1, "secondComponent.Id must be 1"); + Assert.That (secondComponent, Is.Not.Null, "secondComponent must not be null"); + Assert.That (secondComponent.Id == 1, Is.True, "secondComponent.Id must be 1"); } } diff --git a/tests/monotouch-test/GameplayKit/GKEntityTests.cs b/tests/monotouch-test/GameplayKit/GKEntityTests.cs index 78c39b4fafa5..61c990a5c6a6 100644 --- a/tests/monotouch-test/GameplayKit/GKEntityTests.cs +++ b/tests/monotouch-test/GameplayKit/GKEntityTests.cs @@ -24,18 +24,18 @@ public void GetAndRemoveTest () var entity = GKEntity.GetEntity (); entity.AddComponent (new NumberComponent (10)); entity.AddComponent (new NameComponent ("Ten")); - Assert.IsTrue (entity.Components.Length == 2, "entity.Components length must be 2"); + Assert.That (entity.Components.Length == 2, Is.True, "entity.Components length must be 2"); // Test component retrieval by type var component = entity.GetComponent (typeof (NumberComponent)) as NumberComponent; - Assert.NotNull (component, "Component must not be null"); - Assert.IsTrue (component.Id == 10, "Component Id must be 10"); + Assert.That (component, Is.Not.Null, "Component must not be null"); + Assert.That (component.Id == 10, Is.True, "Component Id must be 10"); // Test component removal by type - Assert.NotNull (entity.GetComponent (typeof (NameComponent)), "Component typeof NameComponent must not be null"); + Assert.That (entity.GetComponent (typeof (NameComponent)), Is.Not.Null, "Component typeof NameComponent must not be null"); entity.RemoveComponent (typeof (NameComponent)); - Assert.IsTrue (entity.Components.Length == 1, "entity.Components length must be 1"); - Assert.IsNull (entity.GetComponent (typeof (NameComponent)), "Component typeof NameComponent must be null"); + Assert.That (entity.Components.Length == 1, Is.True, "entity.Components length must be 1"); + Assert.That (entity.GetComponent (typeof (NameComponent)), Is.Null, "Component typeof NameComponent must be null"); } [Test] diff --git a/tests/monotouch-test/GameplayKit/GKGridGraphTests.cs b/tests/monotouch-test/GameplayKit/GKGridGraphTests.cs index 97f39e4cf798..df1c6eaf7778 100644 --- a/tests/monotouch-test/GameplayKit/GKGridGraphTests.cs +++ b/tests/monotouch-test/GameplayKit/GKGridGraphTests.cs @@ -44,7 +44,7 @@ public void FromGridStartingAtTest () TestRuntime.AssertXcodeVersion (7, 0); var graph = GKGridGraph.FromGridStartingAt (Vector2i.Zero, 10, 10, false); - Assert.NotNull (graph, "GKGridGraph.FromGridStartingAt should not be null"); + Assert.That (graph, Is.Not.Null, "GKGridGraph.FromGridStartingAt should not be null"); var walls = new List (10 * 10); var spawnPoints = new List (); @@ -75,8 +75,8 @@ public void FromGridStartingAtTest () if (TestRuntime.CheckXcodeVersion (7, 3)) graph.RemoveNodes (walls.ToArray ()); - Assert.NotNull (startPosition, "startPosition must not be null"); - Assert.AreEqual (new Vector2i (1, 1), startPosition.GridPosition, "GridPosition must be (1,1)"); + Assert.That (startPosition, Is.Not.Null, "startPosition must not be null"); + Assert.That (startPosition.GridPosition, Is.EqualTo (new Vector2i (1, 1)), "GridPosition must be (1,1)"); Assert.That (walls.Count > 0, "walls list must be higher than zero"); Assert.That (spawnPoints.Count > 0, "spawnPoints list must be higher than zero"); } @@ -87,7 +87,7 @@ public void InitFromGridStartingAtTest () TestRuntime.AssertXcodeVersion (7, 0); var graph = new GKGridGraph (Vector2i.Zero, 10, 10, false); - Assert.NotNull (graph, "GKGridGraph.FromGridStartingAt should not be null"); + Assert.That (graph, Is.Not.Null, "GKGridGraph.FromGridStartingAt should not be null"); var walls = new List (10 * 10); var spawnPoints = new List (); @@ -118,8 +118,8 @@ public void InitFromGridStartingAtTest () if (TestRuntime.CheckXcodeVersion (7, 3)) graph.RemoveNodes (walls.ToArray ()); - Assert.NotNull (startPosition, "startPosition must not be null"); - Assert.AreEqual (new Vector2i (1, 1), startPosition.GridPosition, "GridPosition must be (1,1)"); + Assert.That (startPosition, Is.Not.Null, "startPosition must not be null"); + Assert.That (startPosition.GridPosition, Is.EqualTo (new Vector2i (1, 1)), "GridPosition must be (1,1)"); Assert.That (walls.Count > 0, "walls list must be higher than zero"); Assert.That (spawnPoints.Count > 0, "spawnPoints list must be higher than zero"); } diff --git a/tests/monotouch-test/GameplayKit/GKMeshGraphTests.cs b/tests/monotouch-test/GameplayKit/GKMeshGraphTests.cs index 1ef416fbb6e1..7cc09ea15d6c 100644 --- a/tests/monotouch-test/GameplayKit/GKMeshGraphTests.cs +++ b/tests/monotouch-test/GameplayKit/GKMeshGraphTests.cs @@ -29,7 +29,7 @@ public void GKTriangleTest () var def = new GKTriangle (); using (var mesh = new GKMeshGraph (2, min, max, typeof (GKGraphNode2D))) { - Assert.NotNull (mesh, "mesh is null"); + Assert.That (mesh, Is.Not.Null, "mesh is null"); mesh.AddObstacles (new [] { new GKPolygonObstacle (new [] { new Vector2 (3,1), @@ -47,7 +47,7 @@ public void GKTriangleTest () mesh.Triangulate (); Assert.That (mesh.TriangleCount, Is.GreaterThan ((nuint) 0), "No Triangles"); var triangle = mesh.GetTriangle (0); - Assert.AreNotEqual (def, triangle, "Default triangle"); + Assert.That (triangle, Is.Not.EqualTo (def), "Default triangle"); } } } diff --git a/tests/monotouch-test/GameplayKit/GKNoiseMapTests.cs b/tests/monotouch-test/GameplayKit/GKNoiseMapTests.cs index 5502cd009630..bad86239241d 100644 --- a/tests/monotouch-test/GameplayKit/GKNoiseMapTests.cs +++ b/tests/monotouch-test/GameplayKit/GKNoiseMapTests.cs @@ -31,15 +31,15 @@ public void Vector2dTest () using (var noise = new GKNoise (GKCylindersNoiseSource.Create (1))) using (var baseMap = new GKNoiseMap (noise)) using (var map = new GKNoiseMap (noise, size, origin, sample, false)) { - Assert.NotNull (baseMap, "baseMap is null"); - Assert.NotNull (map, "baseMap is null"); + Assert.That (baseMap, Is.Not.Null, "baseMap is null"); + Assert.That (map, Is.Not.Null, "baseMap is null"); - Assert.AreEqual (size, map.Size, "map size is different"); - Assert.AreEqual (size, baseMap.Size, "baseMap size is different"); - Assert.AreEqual (origin, map.Origin, "map origin is different"); - Assert.AreEqual (origin, baseMap.Origin, "baseMap origin is different"); - Assert.AreEqual (sample, map.SampleCount, "map sample is different"); - Assert.AreEqual (sample, baseMap.SampleCount, "baseMap sample is different"); + Assert.That (map.Size, Is.EqualTo (size), "map size is different"); + Assert.That (baseMap.Size, Is.EqualTo (size), "baseMap size is different"); + Assert.That (map.Origin, Is.EqualTo (origin), "map origin is different"); + Assert.That (baseMap.Origin, Is.EqualTo (origin), "baseMap origin is different"); + Assert.That (map.SampleCount, Is.EqualTo (sample), "map sample is different"); + Assert.That (baseMap.SampleCount, Is.EqualTo (sample), "baseMap sample is different"); } } } diff --git a/tests/monotouch-test/GameplayKit/GKObstacleGraphTest.cs b/tests/monotouch-test/GameplayKit/GKObstacleGraphTest.cs index e0781d060ed5..fcab3c12094a 100644 --- a/tests/monotouch-test/GameplayKit/GKObstacleGraphTest.cs +++ b/tests/monotouch-test/GameplayKit/GKObstacleGraphTest.cs @@ -26,7 +26,7 @@ public void GetNodes_ReturnsNullForUnknownObstacle () }; var obstacle = GKPolygonObstacle.FromPoints (points); var graph = GKObstacleGraph.FromObstacles (new GKPolygonObstacle [] { obstacle }, 1.0f); - Assert.IsNotNull (graph, "graph"); + Assert.That (graph, Is.Not.Null, "graph"); var nodes = graph!.GetNodes (obstacle); // May return null or a valid array depending on the graph state @@ -43,7 +43,7 @@ public void GetNodes_ReturnsNullForUnknownObstacle () var otherNodes = graph.GetNodes (otherObstacle); // An obstacle not in the graph may return null or an empty array if (otherNodes is not null) - Assert.AreEqual (0, otherNodes.Length, "otherNodes/empty"); + Assert.That (otherNodes.Length, Is.EqualTo (0), "otherNodes/empty"); } } } diff --git a/tests/monotouch-test/GameplayKit/GKOctreeTests.cs b/tests/monotouch-test/GameplayKit/GKOctreeTests.cs index 9db3feef3eca..15e96b570607 100644 --- a/tests/monotouch-test/GameplayKit/GKOctreeTests.cs +++ b/tests/monotouch-test/GameplayKit/GKOctreeTests.cs @@ -29,12 +29,12 @@ public void GKBoxTest () }; var foo = new NSString ("Foo"); using (var octree = new GKOctree (box, 1)) { - Assert.NotNull (octree, "octree is null"); + Assert.That (octree, Is.Not.Null, "octree is null"); var node = octree.AddElement (foo, box); - Assert.AreEqual (box, node.Box, "boxes are different"); + Assert.That (node.Box, Is.EqualTo (box), "boxes are different"); var strs = octree.GetElements (box); Assert.That (strs.Length, Is.GreaterThan (0), "Must have elements"); - Assert.AreSame (foo, strs [0], "must be the same object"); + Assert.That (strs [0], Is.SameAs (foo), "must be the same object"); } } } diff --git a/tests/monotouch-test/GameplayKit/GKPathTests.cs b/tests/monotouch-test/GameplayKit/GKPathTests.cs index 8933153ff7d6..9f6ec38c92d5 100644 --- a/tests/monotouch-test/GameplayKit/GKPathTests.cs +++ b/tests/monotouch-test/GameplayKit/GKPathTests.cs @@ -41,7 +41,7 @@ public void FromPointsTest () TestRuntime.AssertXcodeVersion (7, 0); var path = GKPath.FromPoints (points, 1, false); - Assert.NotNull (path, "GKPath.FromPoints should not be null"); + Assert.That (path, Is.Not.Null, "GKPath.FromPoints should not be null"); } [Test] @@ -50,7 +50,7 @@ public void InitWithPointsTest () TestRuntime.AssertXcodeVersion (7, 0); var path = new GKPath (points, 1, false); - Assert.NotNull (path, "GKPath.FromPoints should not be null"); + Assert.That (path, Is.Not.Null, "GKPath.FromPoints should not be null"); } [Test] @@ -59,7 +59,7 @@ public void FromPointsVector3Test () TestRuntime.AssertXcodeVersion (8, 0); var path = GKPath.FromPoints (test_vectors3, 1, false); - Assert.NotNull (path, "GKPath.FromPoints should not be null"); + Assert.That (path, Is.Not.Null, "GKPath.FromPoints should not be null"); for (int i = 0; i < test_vectors3.Length; i++) Asserts.AreEqual (path.GetVector3Point ((nuint) i), test_vectors3 [i], $"FromPointsVector3 iter {i}"); @@ -71,7 +71,7 @@ public void InitWithPointsVector3Test () TestRuntime.AssertXcodeVersion (8, 0); var path = new GKPath (test_vectors3, 1, false); - Assert.NotNull (path, "GKPath.FromPoints should not be null"); + Assert.That (path, Is.Not.Null, "GKPath.FromPoints should not be null"); for (int i = 0; i < test_vectors3.Length; i++) Asserts.AreEqual (path.GetVector3Point ((nuint) i), test_vectors3 [i], $"InitWithVector3 iter {i}"); diff --git a/tests/monotouch-test/GameplayKit/GKPolygonObstacleTests.cs b/tests/monotouch-test/GameplayKit/GKPolygonObstacleTests.cs index ffffbffabb6b..8cef81bb582a 100644 --- a/tests/monotouch-test/GameplayKit/GKPolygonObstacleTests.cs +++ b/tests/monotouch-test/GameplayKit/GKPolygonObstacleTests.cs @@ -29,13 +29,13 @@ public void FromPointsTest () TestRuntime.AssertXcodeVersion (7, 0); var obstacle = GKPolygonObstacle.FromPoints (points); - Assert.NotNull (obstacle, "GKPolygonObstacle.FromPoints should not be null"); + Assert.That (obstacle, Is.Not.Null, "GKPolygonObstacle.FromPoints should not be null"); var count = obstacle.VertexCount; - Assert.AreEqual (points.Length, (int) count, "GKPolygonObstacle lengt should be equal"); + Assert.That ((int) count, Is.EqualTo (points.Length), "GKPolygonObstacle lengt should be equal"); for (nuint i = 0; i < count; i++) - Assert.AreEqual (points [(int) i], obstacle.GetVertex (i), "GKPolygonObstacle vectors should be equal"); + Assert.That (obstacle.GetVertex (i), Is.EqualTo (points [(int) i]), "GKPolygonObstacle vectors should be equal"); } [Test] @@ -44,13 +44,13 @@ public void InitWithPointsTest () TestRuntime.AssertXcodeVersion (7, 0); var obstacle = new GKPolygonObstacle (points); - Assert.NotNull (obstacle, "GKPolygonObstacle ctor should not be null"); + Assert.That (obstacle, Is.Not.Null, "GKPolygonObstacle ctor should not be null"); var count = obstacle.VertexCount; - Assert.AreEqual (points.Length, (int) count, "GKPolygonObstacle lengt should be equal"); + Assert.That ((int) count, Is.EqualTo (points.Length), "GKPolygonObstacle lengt should be equal"); for (nuint i = 0; i < count; i++) - Assert.AreEqual (points [(int) i], obstacle.GetVertex (i), "GKPolygonObstacle vectors should be equal"); + Assert.That (obstacle.GetVertex (i), Is.EqualTo (points [(int) i]), "GKPolygonObstacle vectors should be equal"); } } } diff --git a/tests/monotouch-test/GameplayKit/GKQuadTreeTests.cs b/tests/monotouch-test/GameplayKit/GKQuadTreeTests.cs index f87e7ee1c2bb..e437816ab242 100644 --- a/tests/monotouch-test/GameplayKit/GKQuadTreeTests.cs +++ b/tests/monotouch-test/GameplayKit/GKQuadTreeTests.cs @@ -34,12 +34,12 @@ public void GKQuadTest () }; var foo = new NSString ("Foo"); using (var quadTree = new GKQuadTree (quad, 1)) { - Assert.NotNull (quadTree, "quadTree is null"); + Assert.That (quadTree, Is.Not.Null, "quadTree is null"); var node = quadTree.AddElement (foo, quad); - Assert.AreEqual (expectedQuad, node.Quad, $"quads are different"); + Assert.That (node.Quad, Is.EqualTo (expectedQuad), $"quads are different"); var strs = quadTree.GetElements (quad); Assert.That (strs.Length, Is.GreaterThan (0), "Must have elements"); - Assert.AreSame (foo, strs [0], "must be the same object"); + Assert.That (strs [0], Is.SameAs (foo), "must be the same object"); } } } diff --git a/tests/monotouch-test/GameplayKit/GKStateMachineTests.cs b/tests/monotouch-test/GameplayKit/GKStateMachineTests.cs index b05a54d7ca1a..6f59231c07b7 100644 --- a/tests/monotouch-test/GameplayKit/GKStateMachineTests.cs +++ b/tests/monotouch-test/GameplayKit/GKStateMachineTests.cs @@ -30,17 +30,17 @@ public void StateMachineTests () new FleeState () }); - Assert.Null (sm.CurrentState, "CurrentState"); + Assert.That (sm.CurrentState, Is.Null, "CurrentState"); - Assert.NotNull (sm, "StateMachine must not be null"); + Assert.That (sm, Is.Not.Null, "StateMachine must not be null"); sm.EnterState (typeof (ChaseState)); var chaseState = sm.GetState (typeof (ChaseState)); - Assert.NotNull (chaseState, "ChaseState must not be null"); - Assert.AreSame (chaseState, sm.CurrentState, "Must be same state"); + Assert.That (chaseState, Is.Not.Null, "ChaseState must not be null"); + Assert.That (sm.CurrentState, Is.SameAs (chaseState), "Must be same state"); var canEnterState = sm.EnterState (typeof (UndefinedState)); - Assert.IsFalse (canEnterState, "Should not be able to enter that state since we did not allow it"); + Assert.That (canEnterState, Is.False, "Should not be able to enter that state since we did not allow it"); } } diff --git a/tests/monotouch-test/GameplayKit/GKStateTests.cs b/tests/monotouch-test/GameplayKit/GKStateTests.cs index bc933c317bd5..2b97ab13dd44 100644 --- a/tests/monotouch-test/GameplayKit/GKStateTests.cs +++ b/tests/monotouch-test/GameplayKit/GKStateTests.cs @@ -27,14 +27,14 @@ public void IsValidNextState () { var chaseState = new ValidState (); var isValid = chaseState.IsValidNextState (typeof (InvalidState)); - Assert.IsFalse (isValid, "Type"); + Assert.That (isValid, Is.False, "Type"); var invalid = new InvalidState (); isValid = chaseState.IsValidNextState (invalid); - Assert.IsFalse (isValid, "Instance"); + Assert.That (isValid, Is.False, "Instance"); isValid = chaseState.IsValidNextState (invalid.Class); - Assert.IsFalse (isValid, "Class"); + Assert.That (isValid, Is.False, "Class"); } [Test] @@ -54,8 +54,8 @@ public void Concrete () // GKState is an abstract type - but it does implement IsValidNextState (and accept anything) using (var s1 = new ValidState ()) using (var s2 = new InvalidState ()) { - Assert.True (s2.IsValidNextState (s2), "self"); - Assert.True (s2.IsValidNextState (s1), "different"); + Assert.That (s2.IsValidNextState (s2), Is.True, "self"); + Assert.That (s2.IsValidNextState (s1), Is.True, "different"); } } } diff --git a/tests/monotouch-test/GameplayKit/NSArrayGameplayKitTest.cs b/tests/monotouch-test/GameplayKit/NSArrayGameplayKitTest.cs index 971f06e6ef24..476789a3f93d 100644 --- a/tests/monotouch-test/GameplayKit/NSArrayGameplayKitTest.cs +++ b/tests/monotouch-test/GameplayKit/NSArrayGameplayKitTest.cs @@ -28,8 +28,8 @@ public void GetShuffledArray_WithRandomSource () var randomSource = new GKMersenneTwisterRandomSource (); var shuffled = array.GetShuffledArray (randomSource); - Assert.IsNotNull (shuffled, "shuffled"); - Assert.AreEqual (5, shuffled.Length, "shuffled/length"); + Assert.That (shuffled, Is.Not.Null, "shuffled"); + Assert.That (shuffled.Length, Is.EqualTo (5), "shuffled/length"); } [Test] @@ -44,8 +44,8 @@ public void GetShuffledArray_NoArgs () ); var shuffled = array.GetShuffledArray (); - Assert.IsNotNull (shuffled, "shuffled"); - Assert.AreEqual (3, shuffled.Length, "shuffled/length"); + Assert.That (shuffled, Is.Not.Null, "shuffled"); + Assert.That (shuffled.Length, Is.EqualTo (3), "shuffled/length"); } } } diff --git a/tests/monotouch-test/HealthKit/CdaDocumentSampleTest.cs b/tests/monotouch-test/HealthKit/CdaDocumentSampleTest.cs index 418a20aa3df9..3d1999bf4fd7 100644 --- a/tests/monotouch-test/HealthKit/CdaDocumentSampleTest.cs +++ b/tests/monotouch-test/HealthKit/CdaDocumentSampleTest.cs @@ -37,7 +37,7 @@ public void Error () using (var d = new NSData ()) { TestDelegate action = () => { using (var s = HKCdaDocumentSample.Create (d, NSDate.DistantPast, NSDate.DistantFuture, (NSDictionary) null, out error)) { - Assert.NotNull (error, "error"); + Assert.That (error, Is.Not.Null, "error"); var details = new HKDetailedCdaErrors (error.UserInfo); Assert.That (details.ValidationError.Length, Is.EqualTo ((nint) 0), "Length"); } @@ -56,7 +56,7 @@ public void Error () "Objective-C exception thrown. Name: _HKObjectValidationFailureException Reason: Type HKSample can not have endDate of NSDate.distantFuture", }; var success = possibleMessages.Any (v => Regex.IsMatch (ex.Message, v, RegexOptions.IgnoreCase)); - Assert.IsTrue (success, $"The exception message:\n{ex.Message}\nDoes not match any of the expected messages:\n\t{string.Join ("\n\t", possibleMessages)}"); + Assert.That (success, Is.True, $"The exception message:\n{ex.Message}\nDoes not match any of the expected messages:\n\t{string.Join ("\n\t", possibleMessages)}"); } else { action (); } diff --git a/tests/monotouch-test/HealthKit/HKAppleSleepingBreathingDisturbancesTest.cs b/tests/monotouch-test/HealthKit/HKAppleSleepingBreathingDisturbancesTest.cs index 5f9cafa778ea..7f79a7bb902d 100644 --- a/tests/monotouch-test/HealthKit/HKAppleSleepingBreathingDisturbancesTest.cs +++ b/tests/monotouch-test/HealthKit/HKAppleSleepingBreathingDisturbancesTest.cs @@ -14,7 +14,7 @@ public void RoundtripTest () var minimum = HKAppleSleepingBreathingDisturbances.GetMinimumQuantity (HKAppleSleepingBreathingDisturbancesClassification.Elevated); var classification = HKAppleSleepingBreathingDisturbances.GetClassification (minimum); - Assert.AreEqual (HKAppleSleepingBreathingDisturbancesClassification.Elevated, classification, "Classification"); + Assert.That (classification, Is.EqualTo (HKAppleSleepingBreathingDisturbancesClassification.Elevated), "Classification"); } } } diff --git a/tests/monotouch-test/HealthKit/HKAppleWalkingSteadinessTest.cs b/tests/monotouch-test/HealthKit/HKAppleWalkingSteadinessTest.cs index 50ce1e5e0c4f..50cc4767a6da 100644 --- a/tests/monotouch-test/HealthKit/HKAppleWalkingSteadinessTest.cs +++ b/tests/monotouch-test/HealthKit/HKAppleWalkingSteadinessTest.cs @@ -24,18 +24,18 @@ public void SetUp () public void TryGetClassificationTest () { var max = HKAppleWalkingSteadiness.GetMaximumQuantity (HKAppleWalkingSteadinessClassification.Ok); - Assert.True (HKAppleWalkingSteadiness.TryGetClassification (max, out var classification, out var error)); - Assert.Null (error, "error"); - Assert.AreEqual (classification, HKAppleWalkingSteadinessClassification.Ok, "classification"); + Assert.That (HKAppleWalkingSteadiness.TryGetClassification (max, out var classification, out var error), Is.True); + Assert.That (error, Is.Null, "error"); + Assert.That (HKAppleWalkingSteadinessClassification.Ok, Is.EqualTo (classification), "classification"); } [Test] public void GetMinimumQuantityTest () - => Assert.NotNull (HKAppleWalkingSteadiness.GetMinimumQuantity (HKAppleWalkingSteadinessClassification.Ok)); + => Assert.That (HKAppleWalkingSteadiness.GetMinimumQuantity (HKAppleWalkingSteadinessClassification.Ok), Is.Not.Null); [Test] public void GetMaximumQuantityTest () - => Assert.NotNull (HKAppleWalkingSteadiness.GetMaximumQuantity (HKAppleWalkingSteadinessClassification.Ok)); + => Assert.That (HKAppleWalkingSteadiness.GetMaximumQuantity (HKAppleWalkingSteadinessClassification.Ok), Is.Not.Null); } } diff --git a/tests/monotouch-test/HealthKit/HKCategoryValueSleepAnalysisTest.cs b/tests/monotouch-test/HealthKit/HKCategoryValueSleepAnalysisTest.cs index 67ced897d5d3..efaf7d462507 100644 --- a/tests/monotouch-test/HealthKit/HKCategoryValueSleepAnalysisTest.cs +++ b/tests/monotouch-test/HealthKit/HKCategoryValueSleepAnalysisTest.cs @@ -23,7 +23,7 @@ public void GetAsleepValuesTest () TestRuntime.AssertXcodeVersion (14, 0); var sleepValues = HKCategoryValueSleepAnalysisAsleep.GetAsleepValues (); - Assert.IsNotNull (sleepValues, "Asleep Values should not return null."); + Assert.That (sleepValues, Is.Not.Null, "Asleep Values should not return null."); } } } diff --git a/tests/monotouch-test/HealthKit/HKHealthStoreTest.cs b/tests/monotouch-test/HealthKit/HKHealthStoreTest.cs index 90070d899a88..5fc926aa77ce 100644 --- a/tests/monotouch-test/HealthKit/HKHealthStoreTest.cs +++ b/tests/monotouch-test/HealthKit/HKHealthStoreTest.cs @@ -35,7 +35,7 @@ public void GetBiologicalSexNullReturnTest () { var store = new HKHealthStore (); var ret = store.GetBiologicalSex (out _); - Assert.IsNull (ret, "GetBiologicalSex should return a null value if biological sex is not set."); + Assert.That (ret, Is.Null, "GetBiologicalSex should return a null value if biological sex is not set."); } [Test] @@ -43,7 +43,7 @@ public void GetBloodTypeNullReturnTest () { var store = new HKHealthStore (); var ret = store.GetBloodType (out _); - Assert.IsNull (ret, "GetBloodType should return a null value if blood type is not set."); + Assert.That (ret, Is.Null, "GetBloodType should return a null value if blood type is not set."); } } } diff --git a/tests/monotouch-test/HealthKit/HKWorkoutBuilderTest.cs b/tests/monotouch-test/HealthKit/HKWorkoutBuilderTest.cs index f0e223ec21ce..7de1ef21b0ca 100644 --- a/tests/monotouch-test/HealthKit/HKWorkoutBuilderTest.cs +++ b/tests/monotouch-test/HealthKit/HKWorkoutBuilderTest.cs @@ -32,7 +32,7 @@ public void GetSeriesBuilderNullReturnTest () var store = new HKHealthStore (); var seriesBuilder = new HKWorkoutBuilder (new HKHealthStore (), new HKWorkoutConfiguration (), HKDevice.LocalDevice); var ret = seriesBuilder.GetSeriesBuilder (HKSeriesType.HeartbeatSeriesType); - Assert.IsNull (ret, "GetSeriesBuilder should return a null value without proper configuration."); + Assert.That (ret, Is.Null, "GetSeriesBuilder should return a null value without proper configuration."); } } } diff --git a/tests/monotouch-test/HomeKit/HMMutableSignificantTimeEventTest.cs b/tests/monotouch-test/HomeKit/HMMutableSignificantTimeEventTest.cs index 88cab32713ed..763b2962bc2b 100644 --- a/tests/monotouch-test/HomeKit/HMMutableSignificantTimeEventTest.cs +++ b/tests/monotouch-test/HomeKit/HMMutableSignificantTimeEventTest.cs @@ -29,9 +29,9 @@ public void Setup () public void SignificantEventPropertyTest () { using (var obj = new HMMutableSignificantTimeEvent (HMSignificantEvent.Sunrise, null)) { - Assert.AreEqual (HMSignificantEvent.Sunrise, obj.SignificantEvent, "1 SignificantEvent Getter"); + Assert.That (obj.SignificantEvent, Is.EqualTo (HMSignificantEvent.Sunrise), "1 SignificantEvent Getter"); obj.SignificantEvent = HMSignificantEvent.Sunset; - Assert.AreEqual (HMSignificantEvent.Sunset, obj.SignificantEvent, "2 PresenceType Setter"); + Assert.That (obj.SignificantEvent, Is.EqualTo (HMSignificantEvent.Sunset), "2 PresenceType Setter"); } } } diff --git a/tests/monotouch-test/HomeKit/HMSignificantTimeEventTest.cs b/tests/monotouch-test/HomeKit/HMSignificantTimeEventTest.cs index 211546ec3991..a32cb9cc2583 100644 --- a/tests/monotouch-test/HomeKit/HMSignificantTimeEventTest.cs +++ b/tests/monotouch-test/HomeKit/HMSignificantTimeEventTest.cs @@ -29,7 +29,7 @@ public void Setup () public void SignificantEventPropertyTest () { using (var obj = new HMSignificantTimeEvent (HMSignificantEvent.Sunrise, null)) { - Assert.AreEqual (HMSignificantEvent.Sunrise, obj.SignificantEvent, "1 SignificantEvent Getter"); + Assert.That (obj.SignificantEvent, Is.EqualTo (HMSignificantEvent.Sunrise), "1 SignificantEvent Getter"); } } } diff --git a/tests/monotouch-test/ImageIO/CGImageAnimationTest.cs b/tests/monotouch-test/ImageIO/CGImageAnimationTest.cs index 8072b7a0cdeb..01c3a76acd4f 100644 --- a/tests/monotouch-test/ImageIO/CGImageAnimationTest.cs +++ b/tests/monotouch-test/ImageIO/CGImageAnimationTest.cs @@ -94,40 +94,40 @@ void CallAnimateImage (bool useUrl, CGImageAnimation.CGImageSourceAnimationHandl public void AnimateImageWithUrl () { CallAnimateImage ( /* useUrl */ true, MyHandlerSetValueZero); - Assert.AreEqual (CGImageAnimationStatus.Ok, status, "status ok: handler called with url"); - Assert.AreEqual (0, testValue, "handler called with url"); + Assert.That (status, Is.EqualTo (CGImageAnimationStatus.Ok), "status ok: handler called with url"); + Assert.That (testValue, Is.EqualTo (0), "handler called with url"); } [Test] public void AnimateImageWithData () { CallAnimateImage ( /* useUrl */ false, MyHandlerSetValueZero); - Assert.AreEqual (CGImageAnimationStatus.Ok, status, "status ok: handler called with data"); - Assert.AreEqual (0, testValue, "handler called with data"); + Assert.That (status, Is.EqualTo (CGImageAnimationStatus.Ok), "status ok: handler called with data"); + Assert.That (testValue, Is.EqualTo (0), "handler called with data"); } [Test] public void AnimateImageWithUrlChangeHandler () { CallAnimateImage ( /* useUrl */ true, MyHandlerSetValueZero); - Assert.AreEqual (CGImageAnimationStatus.Ok, status, "status ok: first handler called with url"); - Assert.AreEqual (0, testValue, "first handler called with url"); + Assert.That (status, Is.EqualTo (CGImageAnimationStatus.Ok), "status ok: first handler called with url"); + Assert.That (testValue, Is.EqualTo (0), "first handler called with url"); CallAnimateImage ( /* useUrl */ true, MyHandlerSetValueOne); - Assert.AreEqual (CGImageAnimationStatus.Ok, status, "status ok: second handler called with url"); - Assert.AreEqual (1, testValue, "second handler called with url"); + Assert.That (status, Is.EqualTo (CGImageAnimationStatus.Ok), "status ok: second handler called with url"); + Assert.That (testValue, Is.EqualTo (1), "second handler called with url"); } [Test] public void AnimateImageWithDataChangeHandler () { CallAnimateImage ( /* useUrl */ false, MyHandlerSetValueZero); - Assert.AreEqual (CGImageAnimationStatus.Ok, status, "status ok: first handler called with data"); - Assert.AreEqual (0, testValue, "first handler called with data"); + Assert.That (status, Is.EqualTo (CGImageAnimationStatus.Ok), "status ok: first handler called with data"); + Assert.That (testValue, Is.EqualTo (0), "first handler called with data"); CallAnimateImage ( /* useUrl */ false, MyHandlerSetValueOne); - Assert.AreEqual (CGImageAnimationStatus.Ok, status, "status ok: second handler called with data"); - Assert.AreEqual (1, testValue, "second handler called with data"); + Assert.That (status, Is.EqualTo (CGImageAnimationStatus.Ok), "status ok: second handler called with data"); + Assert.That (testValue, Is.EqualTo (1), "second handler called with data"); } [Test] diff --git a/tests/monotouch-test/ImageIO/CGImageSourceTest.cs b/tests/monotouch-test/ImageIO/CGImageSourceTest.cs index 1a12ae1bbb11..24a9fe3512d3 100644 --- a/tests/monotouch-test/ImageIO/CGImageSourceTest.cs +++ b/tests/monotouch-test/ImageIO/CGImageSourceTest.cs @@ -15,15 +15,15 @@ public class CGImageSourceTest { public void FromUrlTest () { using (var img = CGImageSource.FromUrl (fileUrl)) { - Assert.NotNull (img, "#a1"); + Assert.That (img, Is.Not.Null, "#a1"); } using (var img = CGImageSource.FromUrl (fileUrl, new CGImageOptions ())) { - Assert.NotNull (img, "#b1"); + Assert.That (img, Is.Not.Null, "#b1"); } using (var img = CGImageSource.FromUrl (fileUrl, null)) { - Assert.NotNull (img, "#c1"); + Assert.That (img, Is.Not.Null, "#c1"); } } @@ -33,19 +33,19 @@ public void FromDataProviderTest () var file = NSBundle.MainBundle.PathForResource ("xamarin2", "png"); using (var dp = new CGDataProvider (file)) { using (var img = CGImageSource.FromDataProvider (dp)) { - Assert.NotNull (img, "#a1"); + Assert.That (img, Is.Not.Null, "#a1"); } } using (var dp = new CGDataProvider (file)) { using (var img = CGImageSource.FromDataProvider (dp, new CGImageOptions ())) { - Assert.NotNull (img, "#b1"); + Assert.That (img, Is.Not.Null, "#b1"); } } using (var dp = new CGDataProvider (file)) { using (var img = CGImageSource.FromDataProvider (dp, null)) { - Assert.NotNull (img, "#c1"); + Assert.That (img, Is.Not.Null, "#c1"); } } } @@ -56,15 +56,15 @@ public void FromDataTest () NSData data = NSData.FromFile (NSBundle.MainBundle.PathForResource ("xamarin2", "png")); using (var img = CGImageSource.FromData (data)) { - Assert.NotNull (img, "#a1"); + Assert.That (img, Is.Not.Null, "#a1"); } using (var img = CGImageSource.FromData (data, new CGImageOptions ())) { - Assert.NotNull (img, "#b1"); + Assert.That (img, Is.Not.Null, "#b1"); } using (var img = CGImageSource.FromData (data, null)) { - Assert.NotNull (img, "#c1"); + Assert.That (img, Is.Not.Null, "#c1"); } } @@ -73,10 +73,10 @@ public void CreateImageTest () { using (var imgsrc = CGImageSource.FromUrl (fileUrl)) { using (var img = imgsrc.CreateImage (0, null)) { - Assert.NotNull (img, "#a1"); + Assert.That (img, Is.Not.Null, "#a1"); } using (var img = imgsrc.CreateImage (0, new CGImageOptions ())) { - Assert.NotNull (img, "#b1"); + Assert.That (img, Is.Not.Null, "#b1"); } } } @@ -98,11 +98,11 @@ public void CreateThumbnailTest () public void CreateIncrementalTest () { using (var img = CGImageSource.CreateIncremental (null)) { - Assert.NotNull (img, "#a1"); + Assert.That (img, Is.Not.Null, "#a1"); } using (var img = CGImageSource.CreateIncremental (new CGImageOptions ())) { - Assert.NotNull (img, "#b1"); + Assert.That (img, Is.Not.Null, "#b1"); } } @@ -120,8 +120,8 @@ public void CopyProperties () using (var dict = new NSMutableDictionary ()) { dict [kCGImageSourceShouldCache] = NSNumber.FromBoolean (false); using (var props = imageSource.CopyProperties (dict)) { - Assert.Null (props.ValueForKey (kCGImagePropertyPixelWidth), "kCGImagePropertyPixelWidth"); - Assert.Null (props.ValueForKey (kCGImagePropertyPixelHeight), "kCGImagePropertyPixelHeight"); + Assert.That (props.ValueForKey (kCGImagePropertyPixelWidth), Is.Null, "kCGImagePropertyPixelWidth"); + Assert.That (props.ValueForKey (kCGImagePropertyPixelHeight), Is.Null, "kCGImagePropertyPixelHeight"); NSNumber n = (NSNumber) props ["FileSize"]; // image is "optimized" for devices (and a lot bigger at 10351 bytes ;-) Assert.That ((int) n, Is.AtLeast (7318), "FileSize"); @@ -140,16 +140,16 @@ public void GetProperties () CGImageOptions options = new CGImageOptions () { ShouldCache = false }; var props = imageSource.GetProperties (options); - Assert.Null (props.PixelWidth, "PixelHeight-0"); - Assert.Null (props.PixelHeight, "PixelWidth-0"); + Assert.That (props.PixelWidth, Is.Null, "PixelHeight-0"); + Assert.That (props.PixelHeight, Is.Null, "PixelWidth-0"); // image is "optimized" for devices (and a lot bigger at 10351 bytes ;-) Assert.That (props.FileSize, Is.AtLeast (7318), "FileSize"); props = imageSource.GetProperties (0, options); - Assert.AreEqual (57, props.PixelWidth, "PixelHeight"); - Assert.AreEqual (57, props.PixelHeight, "PixelWidth"); - Assert.AreEqual (CGImageColorModel.RGB, props.ColorModel, "ColorModel"); - Assert.AreEqual (8, props.Depth, "Depth"); + Assert.That (props.PixelWidth, Is.EqualTo (57), "PixelHeight"); + Assert.That (props.PixelHeight, Is.EqualTo (57), "PixelWidth"); + Assert.That (props.ColorModel, Is.EqualTo (CGImageColorModel.RGB), "ColorModel"); + Assert.That (props.Depth, Is.EqualTo (8), "Depth"); } } diff --git a/tests/monotouch-test/ImageIO/ImageDestinationTest.cs b/tests/monotouch-test/ImageIO/ImageDestinationTest.cs index 9a27a9f48df2..151959515a43 100644 --- a/tests/monotouch-test/ImageIO/ImageDestinationTest.cs +++ b/tests/monotouch-test/ImageIO/ImageDestinationTest.cs @@ -29,8 +29,8 @@ public class ImageDestinationTest { public void FromData_BadITU () { using (NSMutableData destData = new NSMutableData ()) { - Assert.Null (CGImageDestination.Create (destData, BadUti, 1), "FromData-1"); - Assert.Null (CGImageDestination.Create (destData, BadUti, 1, new CGImageDestinationOptions ()), "FromData-2"); + Assert.That (CGImageDestination.Create (destData, BadUti, 1), Is.Null, "FromData-1"); + Assert.That (CGImageDestination.Create (destData, BadUti, 1, new CGImageDestinationOptions ()), Is.Null, "FromData-2"); } } @@ -52,8 +52,8 @@ public void Create_DataConsumer_BadUTI () { using (NSMutableData destData = new NSMutableData ()) using (var consumer = new CGDataConsumer (destData)) { - Assert.Null (CGImageDestination.Create (consumer, BadUti, 1), "Create-1"); - Assert.Null (CGImageDestination.Create (consumer, BadUti, 1, new CGImageDestinationOptions ()), "Create-2"); + Assert.That (CGImageDestination.Create (consumer, BadUti, 1), Is.Null, "Create-1"); + Assert.That (CGImageDestination.Create (consumer, BadUti, 1, new CGImageDestinationOptions ()), Is.Null, "Create-2"); } } @@ -75,7 +75,7 @@ public void Create_DataConsumer_GoodUTI () public void FromUrl_BadITU () { using (NSUrl url = NSUrl.FromString ("file://local")) { - Assert.Null (CGImageDestination.Create (url, BadUti, 1), "FromUrl-1"); + Assert.That (CGImageDestination.Create (url, BadUti, 1), Is.Null, "FromUrl-1"); } } @@ -125,15 +125,15 @@ public void CopyImageSource () using (var id = CGImageDestination.Create (destData, GoodUti, 1)) { NSError err; // testing that null is allowed (no crash) so the fact that is return false and an error does not matter - Assert.False (id.CopyImageSource (source, (NSDictionary) null, out err), "CopyImageSource"); - Assert.NotNull (err, "NSError"); + Assert.That (id.CopyImageSource (source, (NSDictionary) null, out err), Is.False, "CopyImageSource"); + Assert.That (err, Is.Not.Null, "NSError"); } } [Test] public void TypeIdentifiers () { - Assert.NotNull (CGImageDestination.TypeIdentifiers, "TypeIdentifiers"); + Assert.That (CGImageDestination.TypeIdentifiers, Is.Not.Null, "TypeIdentifiers"); } } } diff --git a/tests/monotouch-test/ImageIO/ImageMetadataTagTest.cs b/tests/monotouch-test/ImageIO/ImageMetadataTagTest.cs index 8f32f08f2021..168706c22ffb 100644 --- a/tests/monotouch-test/ImageIO/ImageMetadataTagTest.cs +++ b/tests/monotouch-test/ImageIO/ImageMetadataTagTest.cs @@ -42,7 +42,7 @@ public void Ctor_NSString () Assert.That (tag.Prefix.ToString (), Is.EqualTo ("exif"), "Prefix"); Assert.That (tag.Type, Is.EqualTo (CGImageMetadataType.String), "Type"); Assert.That (tag.Value.ToString (), Is.EqualTo ("value"), "Value"); - Assert.Null (tag.GetQualifiers (), "GetQualifiers"); + Assert.That (tag.GetQualifiers (), Is.Null, "GetQualifiers"); } } @@ -58,7 +58,7 @@ public void Ctor_NSNumber () Assert.That (tag.Prefix.ToString (), Is.EqualTo ("exif"), "Prefix"); Assert.That (tag.Type, Is.EqualTo (CGImageMetadataType.String), "Type"); Assert.That (tag.Value.ToString (), Is.EqualTo ("255"), "Value"); - Assert.Null (tag.GetQualifiers (), "GetQualifiers"); + Assert.That (tag.GetQualifiers (), Is.Null, "GetQualifiers"); } } @@ -75,7 +75,7 @@ public void Ctor_NSArray () Assert.That (tag.Type, Is.EqualTo (CGImageMetadataType.ArrayOrdered), "Type"); // an NSArray before iOS 10, NSMutableArray then Assert.That (tag.Value, Is.InstanceOf (), "Value"); - Assert.Null (tag.GetQualifiers (), "GetQualifiers"); + Assert.That (tag.GetQualifiers (), Is.Null, "GetQualifiers"); } } @@ -95,7 +95,7 @@ public void Ctor_NSDictionary () } else { Assert.That (tag.Value, Is.TypeOf (), "Value"); } - Assert.Null (tag.GetQualifiers (), "GetQualifiers"); + Assert.That (tag.GetQualifiers (), Is.Null, "GetQualifiers"); } } @@ -112,7 +112,7 @@ public void Ctor_Bool_True () Assert.That (tag.Prefix.ToString (), Is.EqualTo ("exif"), "Prefix"); Assert.That (tag.Type, Is.EqualTo (CGImageMetadataType.String), "Type"); Assert.That (tag.Value.ToString (), Is.EqualTo ("True"), "Value"); - Assert.Null (tag.GetQualifiers (), "GetQualifiers"); + Assert.That (tag.GetQualifiers (), Is.Null, "GetQualifiers"); } } @@ -130,7 +130,7 @@ public void Ctor_Bool_False () Assert.That (tag.Prefix.ToString (), Is.EqualTo ("exif"), "Prefix"); Assert.That (tag.Type, Is.EqualTo (CGImageMetadataType.String), "Type"); Assert.That (tag.Value.ToString (), Is.EqualTo ("False"), "Value"); - Assert.Null (tag.GetQualifiers (), "GetQualifiers"); + Assert.That (tag.GetQualifiers (), Is.Null, "GetQualifiers"); } } } diff --git a/tests/monotouch-test/ImageIO/ImageMetadataTest.cs b/tests/monotouch-test/ImageIO/ImageMetadataTest.cs index 01aa540eb821..aeb6b40b22b1 100644 --- a/tests/monotouch-test/ImageIO/ImageMetadataTest.cs +++ b/tests/monotouch-test/ImageIO/ImageMetadataTest.cs @@ -35,7 +35,7 @@ public void Defaults () using (var meta = new CGImageMetadata (mutable.CreateXMPData ())) { // not surprising since it's all empty - Assert.Null (meta.CopyTagMatchingImageProperty (CGImageProperties.ExifDictionary, CGImageProperties.ExifDateTimeOriginal), "CopyTagMatchingImageProperty"); + Assert.That (meta.CopyTagMatchingImageProperty (CGImageProperties.ExifDictionary, CGImageProperties.ExifDateTimeOriginal), Is.Null, "CopyTagMatchingImageProperty"); } } } diff --git a/tests/monotouch-test/ImageIO/MutableImageMetadataTest.cs b/tests/monotouch-test/ImageIO/MutableImageMetadataTest.cs index bea6c7d70f86..f33c69600549 100644 --- a/tests/monotouch-test/ImageIO/MutableImageMetadataTest.cs +++ b/tests/monotouch-test/ImageIO/MutableImageMetadataTest.cs @@ -30,26 +30,26 @@ public void Defaults () using (var meta = new CGMutableImageMetadata ()) { Console.WriteLine (meta); NSError err; - Assert.True (meta.RegisterNamespace (CGImageMetadataTagNamespaces.Exif, CGImageMetadataTagPrefixes.Exif, out err), "RegisterNamespace"); - Assert.Null (err, "NSError"); + Assert.That (meta.RegisterNamespace (CGImageMetadataTagNamespaces.Exif, CGImageMetadataTagPrefixes.Exif, out err), Is.True, "RegisterNamespace"); + Assert.That (err, Is.Null, "NSError"); // nothing to see at this stage using (var data = meta.CreateXMPData ()) { - Assert.Null (data, "CreateXMPData-1"); + Assert.That (data, Is.Null, "CreateXMPData-1"); } using (var tag = new CGImageMetadataTag (nspace, prefix, name, CGImageMetadataType.Default, true)) { - Assert.True (meta.SetTag (null, path, tag), "SetTag"); + Assert.That (meta.SetTag (null, path, tag), Is.True, "SetTag"); } // now we're talking using (var data = meta.CreateXMPData ()) { - Assert.NotNull (data, "CreateXMPData-2"); + Assert.That (data, Is.Not.Null, "CreateXMPData-2"); } - Assert.True (meta.SetValue (null, path, false), "SetValue"); + Assert.That (meta.SetValue (null, path, false), Is.True, "SetValue"); - Assert.True (meta.SetValueMatchingImageProperty (CGImageProperties.ExifDictionary, CGImageProperties.ExifDateTimeOriginal, (NSDate) DateTime.Now), "SetValueMatchingImageProperty"); + Assert.That (meta.SetValueMatchingImageProperty (CGImageProperties.ExifDictionary, CGImageProperties.ExifDateTimeOriginal, (NSDate) DateTime.Now), Is.True, "SetValueMatchingImageProperty"); } } } diff --git a/tests/monotouch-test/Intents/INIntentResolutionResultTests.cs b/tests/monotouch-test/Intents/INIntentResolutionResultTests.cs index 3d44cfb7f0e4..c33d6f5c7c13 100644 --- a/tests/monotouch-test/Intents/INIntentResolutionResultTests.cs +++ b/tests/monotouch-test/Intents/INIntentResolutionResultTests.cs @@ -38,13 +38,13 @@ public void INCallRecordTypeResolutionResultPropertyTest () using (var needsValue = INCallRecordTypeResolutionResult.NeedsValue) using (var notRequired = INCallRecordTypeResolutionResult.NotRequired) using (var unsupported = INCallRecordTypeResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INCallRecordTypeResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INCallRecordTypeResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INCallRecordTypeResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INCallRecordTypeResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INCallRecordTypeResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INCallRecordTypeResolutionResult)), "Unsupported"); } } @@ -54,13 +54,13 @@ public void INDateComponentsRangeResolutionResultPropertyTest () using (var needsValue = INDateComponentsRangeResolutionResult.NeedsValue) using (var notRequired = INDateComponentsRangeResolutionResult.NotRequired) using (var unsupported = INDateComponentsRangeResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INDateComponentsRangeResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INDateComponentsRangeResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INDateComponentsRangeResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INDateComponentsRangeResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INDateComponentsRangeResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INDateComponentsRangeResolutionResult)), "Unsupported"); } } @@ -70,13 +70,13 @@ public void INMessageAttributeOptionsResolutionResultPropertyTest () using (var needsValue = INMessageAttributeOptionsResolutionResult.NeedsValue) using (var notRequired = INMessageAttributeOptionsResolutionResult.NotRequired) using (var unsupported = INMessageAttributeOptionsResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INMessageAttributeOptionsResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INMessageAttributeOptionsResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INMessageAttributeOptionsResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INMessageAttributeOptionsResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INMessageAttributeOptionsResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INMessageAttributeOptionsResolutionResult)), "Unsupported"); } } @@ -86,13 +86,13 @@ public void INMessageAttributeResolutionResultPropertyTest () using (var needsValue = INMessageAttributeResolutionResult.NeedsValue) using (var notRequired = INMessageAttributeResolutionResult.NotRequired) using (var unsupported = INMessageAttributeResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INMessageAttributeResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INMessageAttributeResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INMessageAttributeResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INMessageAttributeResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INMessageAttributeResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INMessageAttributeResolutionResult)), "Unsupported"); } } @@ -102,13 +102,13 @@ public void INPersonResolutionResultPropertyTest () using (var needsValue = INPersonResolutionResult.NeedsValue) using (var notRequired = INPersonResolutionResult.NotRequired) using (var unsupported = INPersonResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INPersonResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INPersonResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INPersonResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INPersonResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INPersonResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INPersonResolutionResult)), "Unsupported"); } } @@ -118,13 +118,13 @@ public void INPlacemarkResolutionResultPropertyTest () using (var needsValue = INPlacemarkResolutionResult.NeedsValue) using (var notRequired = INPlacemarkResolutionResult.NotRequired) using (var unsupported = INPlacemarkResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INPlacemarkResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INPlacemarkResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INPlacemarkResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INPlacemarkResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INPlacemarkResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INPlacemarkResolutionResult)), "Unsupported"); } } @@ -134,13 +134,13 @@ public void INSpeakableStringResolutionResultPropertyTest () using (var needsValue = INSpeakableStringResolutionResult.NeedsValue) using (var notRequired = INSpeakableStringResolutionResult.NotRequired) using (var unsupported = INSpeakableStringResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INSpeakableStringResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INSpeakableStringResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INSpeakableStringResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INSpeakableStringResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INSpeakableStringResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INSpeakableStringResolutionResult)), "Unsupported"); } } @@ -150,13 +150,13 @@ public void INStringResolutionResultPropertyTest () using (var needsValue = INStringResolutionResult.NeedsValue) using (var notRequired = INStringResolutionResult.NotRequired) using (var unsupported = INStringResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INStringResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INStringResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INStringResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INStringResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INStringResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INStringResolutionResult)), "Unsupported"); } } @@ -167,13 +167,13 @@ public void INBooleanResolutionResultPropertyTest () using (var needsValue = INBooleanResolutionResult.NeedsValue) using (var notRequired = INBooleanResolutionResult.NotRequired) using (var unsupported = INBooleanResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INBooleanResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INBooleanResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INBooleanResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INBooleanResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INBooleanResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INBooleanResolutionResult)), "Unsupported"); } } @@ -183,13 +183,13 @@ public void INCarAirCirculationModeResolutionResultPropertyTest () using (var needsValue = INCarAirCirculationModeResolutionResult.NeedsValue) using (var notRequired = INCarAirCirculationModeResolutionResult.NotRequired) using (var unsupported = INCarAirCirculationModeResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INCarAirCirculationModeResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INCarAirCirculationModeResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INCarAirCirculationModeResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INCarAirCirculationModeResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INCarAirCirculationModeResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INCarAirCirculationModeResolutionResult)), "Unsupported"); } } @@ -199,13 +199,13 @@ public void INCarAudioSourceResolutionResultPropertyTest () using (var needsValue = INCarAudioSourceResolutionResult.NeedsValue) using (var notRequired = INCarAudioSourceResolutionResult.NotRequired) using (var unsupported = INCarAudioSourceResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INCarAudioSourceResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INCarAudioSourceResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INCarAudioSourceResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INCarAudioSourceResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INCarAudioSourceResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INCarAudioSourceResolutionResult)), "Unsupported"); } } @@ -215,13 +215,13 @@ public void INCarDefrosterResolutionResultPropertyTest () using (var needsValue = INCarDefrosterResolutionResult.NeedsValue) using (var notRequired = INCarDefrosterResolutionResult.NotRequired) using (var unsupported = INCarDefrosterResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INCarDefrosterResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INCarDefrosterResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INCarDefrosterResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INCarDefrosterResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INCarDefrosterResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INCarDefrosterResolutionResult)), "Unsupported"); } } @@ -231,13 +231,13 @@ public void INCarSeatResolutionResultPropertyTest () using (var needsValue = INCarSeatResolutionResult.NeedsValue) using (var notRequired = INCarSeatResolutionResult.NotRequired) using (var unsupported = INCarSeatResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INCarSeatResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INCarSeatResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INCarSeatResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INCarSeatResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INCarSeatResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INCarSeatResolutionResult)), "Unsupported"); } } @@ -247,13 +247,13 @@ public void INCurrencyAmountResolutionResultPropertyTest () using (var needsValue = INCurrencyAmountResolutionResult.NeedsValue) using (var notRequired = INCurrencyAmountResolutionResult.NotRequired) using (var unsupported = INCurrencyAmountResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INCurrencyAmountResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INCurrencyAmountResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INCurrencyAmountResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INCurrencyAmountResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INCurrencyAmountResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INCurrencyAmountResolutionResult)), "Unsupported"); } } @@ -263,13 +263,13 @@ public void INDoubleResolutionResultPropertyTest () using (var needsValue = INDoubleResolutionResult.NeedsValue) using (var notRequired = INDoubleResolutionResult.NotRequired) using (var unsupported = INDoubleResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INDoubleResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INDoubleResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INDoubleResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INDoubleResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INDoubleResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INDoubleResolutionResult)), "Unsupported"); } } @@ -279,13 +279,13 @@ public void INDateComponentsResolutionResultPropertyTest () using (var needsValue = INDateComponentsResolutionResult.NeedsValue) using (var notRequired = INDateComponentsResolutionResult.NotRequired) using (var unsupported = INDateComponentsResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INDateComponentsResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INDateComponentsResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INDateComponentsResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INDateComponentsResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INDateComponentsResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INDateComponentsResolutionResult)), "Unsupported"); } } @@ -295,13 +295,13 @@ public void INIntegerResolutionResultPropertyTest () using (var needsValue = INIntegerResolutionResult.NeedsValue) using (var notRequired = INIntegerResolutionResult.NotRequired) using (var unsupported = INIntegerResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INIntegerResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INIntegerResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INIntegerResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INIntegerResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INIntegerResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INIntegerResolutionResult)), "Unsupported"); } } @@ -311,13 +311,13 @@ public void INRadioTypeResolutionResultPropertyTest () using (var needsValue = INRadioTypeResolutionResult.NeedsValue) using (var notRequired = INRadioTypeResolutionResult.NotRequired) using (var unsupported = INRadioTypeResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INRadioTypeResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INRadioTypeResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INRadioTypeResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INRadioTypeResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INRadioTypeResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INRadioTypeResolutionResult)), "Unsupported"); } } @@ -327,13 +327,13 @@ public void INRelativeReferenceResolutionResultPropertyTest () using (var needsValue = INRelativeReferenceResolutionResult.NeedsValue) using (var notRequired = INRelativeReferenceResolutionResult.NotRequired) using (var unsupported = INRelativeReferenceResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INRelativeReferenceResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INRelativeReferenceResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INRelativeReferenceResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INRelativeReferenceResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INRelativeReferenceResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INRelativeReferenceResolutionResult)), "Unsupported"); } } @@ -343,13 +343,13 @@ public void INRelativeSettingResolutionResultPropertyTest () using (var needsValue = INRelativeSettingResolutionResult.NeedsValue) using (var notRequired = INRelativeSettingResolutionResult.NotRequired) using (var unsupported = INRelativeSettingResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INRelativeSettingResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INRelativeSettingResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INRelativeSettingResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INRelativeSettingResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INRelativeSettingResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INRelativeSettingResolutionResult)), "Unsupported"); } } @@ -359,13 +359,13 @@ public void INRestaurantGuestResolutionResultPropertyTest () using (var needsValue = INRestaurantGuestResolutionResult.NeedsValue) using (var notRequired = INRestaurantGuestResolutionResult.NotRequired) using (var unsupported = INRestaurantGuestResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INRestaurantGuestResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INRestaurantGuestResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INRestaurantGuestResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INRestaurantGuestResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INRestaurantGuestResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INRestaurantGuestResolutionResult)), "Unsupported"); } } @@ -375,13 +375,13 @@ public void INRestaurantResolutionResultPropertyTest () using (var needsValue = INRestaurantResolutionResult.NeedsValue) using (var notRequired = INRestaurantResolutionResult.NotRequired) using (var unsupported = INRestaurantResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INRestaurantResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INRestaurantResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INRestaurantResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INRestaurantResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INRestaurantResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INRestaurantResolutionResult)), "Unsupported"); } } @@ -391,13 +391,13 @@ public void INTemperatureResolutionResultPropertyTest () using (var needsValue = INTemperatureResolutionResult.NeedsValue) using (var notRequired = INTemperatureResolutionResult.NotRequired) using (var unsupported = INTemperatureResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INTemperatureResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INTemperatureResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INTemperatureResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INTemperatureResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INTemperatureResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INTemperatureResolutionResult)), "Unsupported"); } } @@ -407,13 +407,13 @@ public void INWorkoutGoalUnitTypeResolutionResultPropertyTest () using (var needsValue = INWorkoutGoalUnitTypeResolutionResult.NeedsValue) using (var notRequired = INWorkoutGoalUnitTypeResolutionResult.NotRequired) using (var unsupported = INWorkoutGoalUnitTypeResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INWorkoutGoalUnitTypeResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INWorkoutGoalUnitTypeResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INWorkoutGoalUnitTypeResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INWorkoutGoalUnitTypeResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INWorkoutGoalUnitTypeResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INWorkoutGoalUnitTypeResolutionResult)), "Unsupported"); } } @@ -423,13 +423,13 @@ public void INWorkoutLocationTypeResolutionResultPropertyTest () using (var needsValue = INWorkoutLocationTypeResolutionResult.NeedsValue) using (var notRequired = INWorkoutLocationTypeResolutionResult.NotRequired) using (var unsupported = INWorkoutLocationTypeResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INWorkoutLocationTypeResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INWorkoutLocationTypeResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INWorkoutLocationTypeResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INWorkoutLocationTypeResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INWorkoutLocationTypeResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INWorkoutLocationTypeResolutionResult)), "Unsupported"); } } #endif @@ -442,13 +442,13 @@ public void INBillPayeeResolutionResultPropertyTest () using (var needsValue = INBillPayeeResolutionResult.NeedsValue) using (var notRequired = INBillPayeeResolutionResult.NotRequired) using (var unsupported = INBillPayeeResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INBillPayeeResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INBillPayeeResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INBillPayeeResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INBillPayeeResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INBillPayeeResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INBillPayeeResolutionResult)), "Unsupported"); } } @@ -460,13 +460,13 @@ public void INBillTypeResolutionResultPropertyTest () using (var needsValue = INBillTypeResolutionResult.NeedsValue) using (var notRequired = INBillTypeResolutionResult.NotRequired) using (var unsupported = INBillTypeResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INBillTypeResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INBillTypeResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INBillTypeResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INBillTypeResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INBillTypeResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INBillTypeResolutionResult)), "Unsupported"); } } @@ -478,13 +478,13 @@ public void INCarSignalOptionsResolutionResultPropertyTest () using (var needsValue = INCarSignalOptionsResolutionResult.NeedsValue) using (var notRequired = INCarSignalOptionsResolutionResult.NotRequired) using (var unsupported = INCarSignalOptionsResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INCarSignalOptionsResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INCarSignalOptionsResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INCarSignalOptionsResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INCarSignalOptionsResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INCarSignalOptionsResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INCarSignalOptionsResolutionResult)), "Unsupported"); } } @@ -496,13 +496,13 @@ public void INPaymentAmountResolutionResultPropertyTest () using (var needsValue = INPaymentAmountResolutionResult.NeedsValue) using (var notRequired = INPaymentAmountResolutionResult.NotRequired) using (var unsupported = INPaymentAmountResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INPaymentAmountResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INPaymentAmountResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INPaymentAmountResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INPaymentAmountResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INPaymentAmountResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INPaymentAmountResolutionResult)), "Unsupported"); } } @@ -514,13 +514,13 @@ public void INPaymentStatusResolutionResultPropertyTest () using (var needsValue = INPaymentStatusResolutionResult.NeedsValue) using (var notRequired = INPaymentStatusResolutionResult.NotRequired) using (var unsupported = INPaymentStatusResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INPaymentStatusResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INPaymentStatusResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INPaymentStatusResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INPaymentStatusResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INPaymentStatusResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INPaymentStatusResolutionResult)), "Unsupported"); } } @@ -532,13 +532,13 @@ public void INPaymentAccountResolutionResultPropertyTest () using (var needsValue = INPaymentAccountResolutionResult.NeedsValue) using (var notRequired = INPaymentAccountResolutionResult.NotRequired) using (var unsupported = INPaymentAccountResolutionResult.Unsupported) { - Assert.NotNull (needsValue, "NeedsValue Null"); - Assert.NotNull (notRequired, "NotRequired Null"); - Assert.NotNull (unsupported, "Unsupported Null"); + Assert.That (needsValue, Is.Not.Null, "NeedsValue Null"); + Assert.That (notRequired, Is.Not.Null, "NotRequired Null"); + Assert.That (unsupported, Is.Not.Null, "Unsupported Null"); - Assert.IsInstanceOf (typeof (INPaymentAccountResolutionResult), needsValue, "NeedsValue"); - Assert.IsInstanceOf (typeof (INPaymentAccountResolutionResult), notRequired, "NotRequired"); - Assert.IsInstanceOf (typeof (INPaymentAccountResolutionResult), unsupported, "Unsupported"); + Assert.That (needsValue, Is.InstanceOf (typeof (INPaymentAccountResolutionResult)), "NeedsValue"); + Assert.That (notRequired, Is.InstanceOf (typeof (INPaymentAccountResolutionResult)), "NotRequired"); + Assert.That (unsupported, Is.InstanceOf (typeof (INPaymentAccountResolutionResult)), "Unsupported"); } } } diff --git a/tests/monotouch-test/JavascriptCore/JSExportTest.cs b/tests/monotouch-test/JavascriptCore/JSExportTest.cs index 22f50633ef2b..b9f45043f8df 100644 --- a/tests/monotouch-test/JavascriptCore/JSExportTest.cs +++ b/tests/monotouch-test/JavascriptCore/JSExportTest.cs @@ -29,8 +29,8 @@ public void ExportTest () var obj = new MyJavaExporter (); context [(NSString) "obj"] = JSValue.From (obj, context); context.EvaluateScript ("obj.myFunc ();"); - Assert.IsNull (exc, "JS exception"); - Assert.IsTrue (obj.MyFuncCalled, "Called"); + Assert.That (exc, Is.Null, "JS exception"); + Assert.That (obj.MyFuncCalled, Is.True, "Called"); context.EvaluateScript ("obj.hello (42);"); context.EvaluateScript ("obj.callMeBack (function() { return 314; });"); @@ -61,15 +61,15 @@ public void MyFunc () public void Hello (JSValue val) { - Assert.IsTrue (val.IsNumber, "Hello - IsNumber"); - Assert.AreEqual (42, val.ToNumber ().Int32Value, "Hello - Number"); + Assert.That (val.IsNumber, Is.True, "Hello - IsNumber"); + Assert.That (val.ToNumber ().Int32Value, Is.EqualTo (42), "Hello - Number"); } public void CallMeBack (JSValue callbackFunc) { var rv = callbackFunc.Call (); - Assert.IsTrue (rv.IsNumber, "CallMeBack - IsNumber"); - Assert.AreEqual (314, rv.ToNumber ().Int32Value, "CallMeBack - Number"); + Assert.That (rv.IsNumber, Is.True, "CallMeBack - IsNumber"); + Assert.That (rv.ToNumber ().Int32Value, Is.EqualTo (314), "CallMeBack - Number"); } } } diff --git a/tests/monotouch-test/JavascriptCore/ValueTest.cs b/tests/monotouch-test/JavascriptCore/ValueTest.cs index 3f33fe90ca15..10297fdb1623 100644 --- a/tests/monotouch-test/JavascriptCore/ValueTest.cs +++ b/tests/monotouch-test/JavascriptCore/ValueTest.cs @@ -25,8 +25,8 @@ public void From () using (var c = new JSContext ()) { using (var d = JSValue.From (1.0, c)) { Assert.That (d.ToDouble (), Is.EqualTo (1.0d), "double"); - Assert.AreSame (d.Context, c, "double.Context"); - Assert.True (d.IsNumber, "double.IsNumber"); + Assert.That (c, Is.SameAs (d.Context), "double.Context"); + Assert.That (d.IsNumber, Is.True, "double.IsNumber"); } } } @@ -59,15 +59,15 @@ public void IsEqual () using (var c = new JSContext ()) using (var d = JSValue.From (1.0d, c)) using (var f = JSValue.From (1.0f, c)) { - Assert.True (d.IsEqualTo (d), "=== self"); - Assert.True (d.IsEqualTo (f), "=== double/float"); // it's a number now - Assert.True (d.IsEqualTo ((NSNumber) 1.0d), "=== NSNumber"); - Assert.False (d.IsEqualTo ((NSNumber) 2.0d), "=== NSNumber-2"); - - Assert.True (d.IsEqualWithTypeCoercionTo (d), "== self"); - Assert.True (d.IsEqualWithTypeCoercionTo (f), "== double/float"); - Assert.True (d.IsEqualWithTypeCoercionTo ((NSNumber) 1.0d), "== NSNumber"); - Assert.False (d.IsEqualWithTypeCoercionTo ((NSNumber) 2.0d), "== NSNumber-2"); + Assert.That (d.IsEqualTo (d), Is.True, "=== self"); + Assert.That (d.IsEqualTo (f), Is.True, "=== double/float"); // it's a number now + Assert.That (d.IsEqualTo ((NSNumber) 1.0d), Is.True, "=== NSNumber"); + Assert.That (d.IsEqualTo ((NSNumber) 2.0d), Is.False, "=== NSNumber-2"); + + Assert.That (d.IsEqualWithTypeCoercionTo (d), Is.True, "== self"); + Assert.That (d.IsEqualWithTypeCoercionTo (f), Is.True, "== double/float"); + Assert.That (d.IsEqualWithTypeCoercionTo ((NSNumber) 1.0d), Is.True, "== NSNumber"); + Assert.That (d.IsEqualWithTypeCoercionTo ((NSNumber) 2.0d), Is.False, "== NSNumber-2"); } } @@ -79,11 +79,11 @@ public void CreatePromise () using (var c = new JSContext ()) { bool called = false; var p = JSValue.CreatePromise (c, (resolve, reject) => { - Assert.NotNull (resolve, "resolve"); - Assert.NotNull (reject, "reject"); + Assert.That (resolve, Is.Not.Null, "resolve"); + Assert.That (reject, Is.Not.Null, "reject"); called = true; }); - Assert.True (called, "called"); + Assert.That (called, Is.True, "called"); } } @@ -97,8 +97,8 @@ public void ToArray () using var array = NSArray.FromStrings ("a", "b"); using var value = JSValue.From (array, context); using var arr2 = value.ToArray (); - Assert.AreEqual ("a", arr2.GetItem (0).ToString (), "a"); - Assert.AreEqual ("b", arr2.GetItem (1).ToString (), "a"); + Assert.That (arr2.GetItem (0).ToString (), Is.EqualTo ("a"), "a"); + Assert.That (arr2.GetItem (1).ToString (), Is.EqualTo ("b"), "a"); } } } diff --git a/tests/monotouch-test/LocalAuthentication/LADomainStateCompanionTest.cs b/tests/monotouch-test/LocalAuthentication/LADomainStateCompanionTest.cs index fb7f0c0c2c4a..4feebdfdc164 100644 --- a/tests/monotouch-test/LocalAuthentication/LADomainStateCompanionTest.cs +++ b/tests/monotouch-test/LocalAuthentication/LADomainStateCompanionTest.cs @@ -15,9 +15,9 @@ public void AvailableCompanionTypes () TestRuntime.AssertXcodeVersion (16, 0); using var context = new LAContext (); - Assert.IsNotNull (context.DomainState, "DomainState"); - Assert.IsNotNull (context.DomainState.Companion, "DomainState.Companion"); - Assert.IsNotNull (context.DomainState.Companion.WeakAvailableCompanionTypes, "DomainState.Companion.WeakAvailableCompanionTypes"); + Assert.That (context.DomainState, Is.Not.Null, "DomainState"); + Assert.That (context.DomainState.Companion, Is.Not.Null, "DomainState.Companion"); + Assert.That (context.DomainState.Companion.WeakAvailableCompanionTypes, Is.Not.Null, "DomainState.Companion.WeakAvailableCompanionTypes"); Assert.That (context.DomainState.Companion.AvailableCompanionTypes, Is.EqualTo (LACompanionType.None).Or.EqualTo (LACompanionType.Watch), "DomainState.Companion.AvailableCompanionTypes"); } } diff --git a/tests/monotouch-test/MapKit/AnnotationViewTest.cs b/tests/monotouch-test/MapKit/AnnotationViewTest.cs index 98b89d428605..03c5b5d9fb2f 100644 --- a/tests/monotouch-test/MapKit/AnnotationViewTest.cs +++ b/tests/monotouch-test/MapKit/AnnotationViewTest.cs @@ -33,7 +33,7 @@ public void InitWithFrame () var frame = new CGRect (10, 10, 100, 100); using (MKAnnotationView av = new MKAnnotationView (frame)) { Assert.That (av.Frame, Is.EqualTo (frame), "Frame"); - Assert.Null (av.Annotation, "Annotation"); + Assert.That (av.Annotation, Is.Null, "Annotation"); } } @@ -43,7 +43,7 @@ public void InitWithAnnotation () // using a null 'annotation' crash - but the property can be set to null later using (var a = new MKPolygon ()) using (MKAnnotationView av = new MKAnnotationView (a, "reuse")) { - Assert.AreSame (a, av.Annotation, "Annotation"); + Assert.That (av.Annotation, Is.SameAs (a), "Annotation"); av.Annotation = null; } } @@ -52,19 +52,19 @@ public void InitWithAnnotation () public void Default () { using (var def = new MKAnnotationView ()) { - Assert.IsNull (def.Annotation, "Annotation"); - Assert.AreEqual (def.CalloutOffset, CGPoint.Empty, "CalloutOffset"); - Assert.IsFalse (def.CanShowCallout, "CanShowCallout"); - Assert.AreEqual (def.CenterOffset, CGPoint.Empty, "CenterOffset"); - Assert.IsFalse (def.Draggable, "Draggable"); + Assert.That (def.Annotation, Is.Null, "Annotation"); + Assert.That (CGPoint.Empty, Is.EqualTo (def.CalloutOffset), "CalloutOffset"); + Assert.That (def.CanShowCallout, Is.False, "CanShowCallout"); + Assert.That (CGPoint.Empty, Is.EqualTo (def.CenterOffset), "CenterOffset"); + Assert.That (def.Draggable, Is.False, "Draggable"); Assert.That (def.DragState, Is.EqualTo (MKAnnotationViewDragState.None), "DragState"); - Assert.IsTrue (def.Enabled, "Enabled"); - Assert.IsFalse (def.Highlighted, "Highlighted"); - Assert.IsNull (def.Image, "Image"); - Assert.IsNull (def.LeftCalloutAccessoryView, "LeftCalloutAccessoryView"); - Assert.IsNull (def.ReuseIdentifier, "ReuseIdentifier"); - Assert.IsNull (def.RightCalloutAccessoryView, "RightCalloutAccessoryView"); - Assert.IsFalse (def.Selected, "Selected"); + Assert.That (def.Enabled, Is.True, "Enabled"); + Assert.That (def.Highlighted, Is.False, "Highlighted"); + Assert.That (def.Image, Is.Null, "Image"); + Assert.That (def.LeftCalloutAccessoryView, Is.Null, "LeftCalloutAccessoryView"); + Assert.That (def.ReuseIdentifier, Is.Null, "ReuseIdentifier"); + Assert.That (def.RightCalloutAccessoryView, Is.Null, "RightCalloutAccessoryView"); + Assert.That (def.Selected, Is.False, "Selected"); } } @@ -74,27 +74,27 @@ public void Null () using (var def = new MKAnnotationView ()) { def.Annotation = null; def.Annotation = new MKPolygon (); - Assert.IsNotNull (def.Annotation, "Annotation NN"); + Assert.That (def.Annotation, Is.Not.Null, "Annotation NN"); def.Annotation = null; - Assert.IsNull (def.Annotation, "Annotation N"); + Assert.That (def.Annotation, Is.Null, "Annotation N"); def.Image = null; def.Image = new PlatformImage (); - Assert.IsNotNull (def.Image, "Image NN"); + Assert.That (def.Image, Is.Not.Null, "Image NN"); def.Image = null; - Assert.IsNull (def.Image, "Image N"); + Assert.That (def.Image, Is.Null, "Image N"); def.LeftCalloutAccessoryView = null; def.LeftCalloutAccessoryView = new PlatformView (); - Assert.IsNotNull (def.LeftCalloutAccessoryView, "LeftCalloutAccessoryView NN"); + Assert.That (def.LeftCalloutAccessoryView, Is.Not.Null, "LeftCalloutAccessoryView NN"); def.LeftCalloutAccessoryView = null; - Assert.IsNull (def.LeftCalloutAccessoryView, "LeftCalloutAccessoryView N"); + Assert.That (def.LeftCalloutAccessoryView, Is.Null, "LeftCalloutAccessoryView N"); def.RightCalloutAccessoryView = null; def.RightCalloutAccessoryView = new PlatformView (); - Assert.IsNotNull (def.RightCalloutAccessoryView, "RightCalloutAccessoryView NN"); + Assert.That (def.RightCalloutAccessoryView, Is.Not.Null, "RightCalloutAccessoryView NN"); def.RightCalloutAccessoryView = null; - Assert.IsNull (def.RightCalloutAccessoryView, "RightCalloutAccessoryView N"); + Assert.That (def.RightCalloutAccessoryView, Is.Null, "RightCalloutAccessoryView N"); } } } diff --git a/tests/monotouch-test/MapKit/LocalSearchRequestTest.cs b/tests/monotouch-test/MapKit/LocalSearchRequestTest.cs index 36f566da4c83..637706ac319f 100644 --- a/tests/monotouch-test/MapKit/LocalSearchRequestTest.cs +++ b/tests/monotouch-test/MapKit/LocalSearchRequestTest.cs @@ -25,7 +25,7 @@ public void Default () TestRuntime.AssertSystemVersion (ApplePlatform.TVOS, 9, 2, throwIfOtherPlatform: false); using (var lsr = new MKLocalSearchRequest ()) { - Assert.Null (lsr.NaturalLanguageQuery, "NaturalLanguageQuery"); + Assert.That (lsr.NaturalLanguageQuery, Is.Null, "NaturalLanguageQuery"); Assert.That (lsr.Region.Center.Latitude, Is.EqualTo (0.0d), "Latitude"); Assert.That (lsr.Region.Center.Longitude, Is.EqualTo (0.0d), "Longitude"); Assert.That (lsr.Region.Span.LatitudeDelta, Is.EqualTo (0.0d), "LatitudeDelta"); diff --git a/tests/monotouch-test/MapKit/LocalSearchTest.cs b/tests/monotouch-test/MapKit/LocalSearchTest.cs index b41741cece95..b9f766d987f3 100644 --- a/tests/monotouch-test/MapKit/LocalSearchTest.cs +++ b/tests/monotouch-test/MapKit/LocalSearchTest.cs @@ -30,7 +30,7 @@ public void EmptyRequest () ls.Start ((MKLocalSearchResponse response, NSError error) => { wait = false; }); - Assert.True (ls.IsSearching, "IsSearching"); + Assert.That (ls.IsSearching, Is.True, "IsSearching"); // wait a bit before cancelling the search (so it really starts) // otherwise IsSearching might never complete (on iOS8) and seems very random (in earlier versions) diff --git a/tests/monotouch-test/MapKit/MKAddressFilterTest.cs b/tests/monotouch-test/MapKit/MKAddressFilterTest.cs index 8f7c2d78ac2d..f602459cc80e 100644 --- a/tests/monotouch-test/MapKit/MKAddressFilterTest.cs +++ b/tests/monotouch-test/MapKit/MKAddressFilterTest.cs @@ -15,10 +15,10 @@ public void Constructors () TestRuntime.AssertXcodeVersion (16, 0); using (var filter = new MKAddressFilter (MKAddressFilterOption.Country, MKAddressFilterConstructorOption.Exclude)) { - Assert.IsNotNull (filter, "Exclude filter"); + Assert.That (filter, Is.Not.Null, "Exclude filter"); } using (var filter = new MKAddressFilter (MKAddressFilterOption.SubAdministrativeArea, MKAddressFilterConstructorOption.Include)) { - Assert.IsNotNull (filter, "Include filter"); + Assert.That (filter, Is.Not.Null, "Include filter"); } } } diff --git a/tests/monotouch-test/MapKit/MapRectTest.cs b/tests/monotouch-test/MapKit/MapRectTest.cs index d31e30db08cc..e2aca1a8d9e3 100644 --- a/tests/monotouch-test/MapKit/MapRectTest.cs +++ b/tests/monotouch-test/MapKit/MapRectTest.cs @@ -20,15 +20,15 @@ public void Setup () public void Defaults () { MKMapRect rect = new MKMapRect (); - Assert.False (rect.IsNull, "IsNull"); - Assert.True (rect.IsEmpty, "IsEmpty"); - Assert.False (rect.Spans180thMeridian, "default"); - Assert.True (rect.Equals (rect), "Equals"); + Assert.That (rect.IsNull, Is.False, "IsNull"); + Assert.That (rect.IsEmpty, Is.True, "IsEmpty"); + Assert.That (rect.Spans180thMeridian, Is.False, "default"); + Assert.That (rect.Equals (rect), Is.True, "Equals"); Assert.That (rect.ToString (), Is.EqualTo (@"{{0, 0}, {0, 0}}"), "default"); MKMapRect rect2 = new MKMapRect (); - Assert.True (rect == rect2, "=="); - Assert.False (rect != rect2, "!="); + Assert.That (rect == rect2, Is.True, "=="); + Assert.That (rect != rect2, Is.False, "!="); Assert.That (rect.GetHashCode (), Is.EqualTo (rect2.GetHashCode ()), "GetHashCode"); } @@ -38,9 +38,9 @@ public void ContainsPoint () MKMapRect rect = new MKMapRect (); MKMapPoint point = new MKMapPoint (); if (TestRuntime.CheckXcodeVersion (8, 0)) - Assert.True (rect.Contains (point), "default"); + Assert.That (rect.Contains (point), Is.True, "default"); else - Assert.False (rect.Contains (point), "default"); + Assert.That (rect.Contains (point), Is.False, "default"); } [Test] @@ -48,7 +48,7 @@ public void ContainsRect () { MKMapRect rect1 = new MKMapRect (); MKMapRect rect2 = new MKMapRect (); - Assert.True (rect1.Contains (rect2), "default"); + Assert.That (rect1.Contains (rect2), Is.True, "default"); } [Test] @@ -66,15 +66,15 @@ public void Intersection () { MKMapRect rect1 = new MKMapRect (1, 2, 3, 4); MKMapRect rect2 = new MKMapRect (2, 3, 2, 1); - Assert.True (MKMapRect.Intersects (rect1, rect2), "Intersects"); + Assert.That (MKMapRect.Intersects (rect1, rect2), Is.True, "Intersects"); MKMapRect n = MKMapRect.Intersection (rect1, rect2); Assert.That (n.ToString (), Is.EqualTo (@"{{2, 3}, {2, 1}}"), "ToString"); MKMapRect rect3 = new MKMapRect (-2, -3, 2, 1); - Assert.False (MKMapRect.Intersects (rect1, rect3), "!Intersects"); + Assert.That (MKMapRect.Intersects (rect1, rect3), Is.False, "!Intersects"); n = MKMapRect.Intersection (rect1, rect3); - Assert.True (n.IsNull, "IsNull"); + Assert.That (n.IsNull, Is.True, "IsNull"); } [Test] @@ -82,7 +82,7 @@ public void Inset () { MKMapRect rect = new MKMapRect (Double.PositiveInfinity, Double.PositiveInfinity, 0, 0); MKMapRect rectin = rect.Inset (-1, 1); - Assert.True (rectin.IsNull, "IsNull"); + Assert.That (rectin.IsNull, Is.True, "IsNull"); rect = new MKMapRect (1, 2, 3, 4); rectin = rect.Inset (-1, 1); @@ -94,7 +94,7 @@ public void Offset () { MKMapRect rect = new MKMapRect (Double.PositiveInfinity, Double.PositiveInfinity, 0, 0); MKMapRect rectoff = rect.Offset (-1, 1); - Assert.True (rectoff.IsNull, "IsNull"); + Assert.That (rectoff.IsNull, Is.True, "IsNull"); rect = new MKMapRect (1, 2, 3, 4); rectoff = rect.Offset (1, -1); @@ -105,9 +105,9 @@ public void Offset () public void Remainder () { MKMapRect rect = new MKMapRect (); - Assert.False (rect.Spans180thMeridian, "default"); + Assert.That (rect.Spans180thMeridian, Is.False, "default"); MKMapRect remainder = rect.Remainder (); - Assert.True (remainder.IsNull, "IsNull"); + Assert.That (remainder.IsNull, Is.True, "IsNull"); rect = new MKMapRect (-90, -90, 90, 90); Assert.That (rect.Spans180thMeridian, Is.EqualTo (!TestRuntime.CheckXcodeVersion (5, 1)), rect.ToString ()); @@ -130,8 +130,8 @@ public void NullRect () { MKMapRect nullRect = MKMapRect.Null; MKMapRect expectedValue = new MKMapRect (double.PositiveInfinity, double.PositiveInfinity, 0, 0); - Assert.AreEqual (expectedValue, nullRect, "NullRect equals (PositiveInfinity, PositiveInfinity, 0, 0)"); - Assert.IsTrue (nullRect.IsNull, "IsNull"); + Assert.That (nullRect, Is.EqualTo (expectedValue), "NullRect equals (PositiveInfinity, PositiveInfinity, 0, 0)"); + Assert.That (nullRect.IsNull, Is.True, "IsNull"); } } } diff --git a/tests/monotouch-test/MapKit/OverlayPathRendererTest.cs b/tests/monotouch-test/MapKit/OverlayPathRendererTest.cs index 050b5537fff4..5d0269246afa 100644 --- a/tests/monotouch-test/MapKit/OverlayPathRendererTest.cs +++ b/tests/monotouch-test/MapKit/OverlayPathRendererTest.cs @@ -30,7 +30,7 @@ public void DefaultCtor () TestRuntime.AssertXcodeVersion (5, 0, 1); using (var opr = new MKOverlayPathRenderer ()) { - Assert.Null (opr.Path, "Path"); + Assert.That (opr.Path, Is.Null, "Path"); } } @@ -42,7 +42,7 @@ public void CtorOverlay () var loc = new CLLocationCoordinate2D (40, 70); using (var overlay = MKCircle.Circle (loc, 2000)) using (var opr = new MKOverlayPathRenderer (overlay)) { - Assert.Null (opr.Path, "Path"); + Assert.That (opr.Path, Is.Null, "Path"); } } } diff --git a/tests/monotouch-test/MapKit/OverlayViewTest.cs b/tests/monotouch-test/MapKit/OverlayViewTest.cs index 739f5bd53a38..fec6e548b6b5 100644 --- a/tests/monotouch-test/MapKit/OverlayViewTest.cs +++ b/tests/monotouch-test/MapKit/OverlayViewTest.cs @@ -18,7 +18,7 @@ public void InitWithFrame () var frame = new CGRect (10, 10, 100, 100); using (MKOverlayView ov = new MKOverlayView (frame)) { Assert.That (ov.Frame, Is.EqualTo (frame), "Frame"); - Assert.Null (ov.Overlay, "Overlay"); + Assert.That (ov.Overlay, Is.Null, "Overlay"); } } } diff --git a/tests/monotouch-test/MapKit/PinAnnotationViewTest.cs b/tests/monotouch-test/MapKit/PinAnnotationViewTest.cs index a805a20e7837..7cceabd8547a 100644 --- a/tests/monotouch-test/MapKit/PinAnnotationViewTest.cs +++ b/tests/monotouch-test/MapKit/PinAnnotationViewTest.cs @@ -35,11 +35,11 @@ public void Ctor_Annotation () { using (var a = new MKPolyline ()) using (MKPinAnnotationView av = new MKPinAnnotationView (a, "reuse")) { - Assert.AreSame (a, av.Annotation, "Annotation"); + Assert.That (av.Annotation, Is.SameAs (a), "Annotation"); #if !MONOMAC if (TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 7, 0)) // Crashes with EXC_BAD_ACCESS (SIGABRT) if < iOS 7.0 - Assert.False (av.AnimatesDrop, "AnimatesDrop"); + Assert.That (av.AnimatesDrop, Is.False, "AnimatesDrop"); if (!TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 9, 0)) return; @@ -48,7 +48,7 @@ public void Ctor_Annotation () Assert.That (av.PinColor, Is.EqualTo (MKPinAnnotationColor.Red), "PinColor"); if (TestRuntime.CheckXcodeVersion (7, 0)) - Assert.NotNull (av.PinTintColor, "PinTintColor"); + Assert.That (av.PinTintColor, Is.Not.Null, "PinTintColor"); } } @@ -63,8 +63,8 @@ public void InitWithFrame () var frame = new CGRect (10, 10, 100, 100); using (var av = new MKPinAnnotationView (frame)) { Assert.That (av.Frame.ToString (), Is.EqualTo (frame.ToString ()), "Frame"); // fp comparison fails - Assert.Null (av.Annotation, "Annotation"); - Assert.False (av.AnimatesDrop, "AnimatesDrop"); + Assert.That (av.Annotation, Is.Null, "Annotation"); + Assert.That (av.AnimatesDrop, Is.False, "AnimatesDrop"); if (!TestRuntime.CheckXcodeVersion (7, 0)) return; @@ -75,9 +75,9 @@ public void InitWithFrame () #else bool not_null = TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 10, 0); if (not_null) - Assert.NotNull (av.PinTintColor, "PinTintColor"); + Assert.That (av.PinTintColor, Is.Not.Null, "PinTintColor"); else - Assert.Null (av.PinTintColor, "PinTintColor"); // differs from the other init call + Assert.That (av.PinTintColor, Is.Null, "PinTintColor"); // differs from the other init call #endif } } diff --git a/tests/monotouch-test/MapKit/PolygonTest.cs b/tests/monotouch-test/MapKit/PolygonTest.cs index 1078d1d8a599..619727a81bf7 100644 --- a/tests/monotouch-test/MapKit/PolygonTest.cs +++ b/tests/monotouch-test/MapKit/PolygonTest.cs @@ -36,16 +36,16 @@ void CheckEmpty (MKPolygon pg) // MKAnnotation Assert.That (pg.Coordinate.Longitude, Is.NaN, "Coordinate.Longitude"); Assert.That (pg.Coordinate.Latitude, Is.NaN, "Coordinate.Latitude"); - Assert.Null (pg.Title, "Title"); - Assert.Null (pg.Subtitle, "Subtitle"); + Assert.That (pg.Title, Is.Null, "Title"); + Assert.That (pg.Subtitle, Is.Null, "Subtitle"); // MKOverlay - Assert.True (Double.IsPositiveInfinity (pg.BoundingMapRect.Origin.X), "BoundingMapRect.Origin.X"); - Assert.True (Double.IsPositiveInfinity (pg.BoundingMapRect.Origin.Y), "BoundingMapRect.Origin.Y"); - Assert.True (Double.IsNegativeInfinity (pg.BoundingMapRect.Size.Height), "BoundingMapRect.Size.Height"); - Assert.True (Double.IsNegativeInfinity (pg.BoundingMapRect.Size.Width), "BoundingMapRect.Size.Width"); - Assert.False (pg.Intersects (pg.BoundingMapRect), "Intersect/Self"); + Assert.That (Double.IsPositiveInfinity (pg.BoundingMapRect.Origin.X), Is.True, "BoundingMapRect.Origin.X"); + Assert.That (Double.IsPositiveInfinity (pg.BoundingMapRect.Origin.Y), Is.True, "BoundingMapRect.Origin.Y"); + Assert.That (Double.IsNegativeInfinity (pg.BoundingMapRect.Size.Height), Is.True, "BoundingMapRect.Size.Height"); + Assert.That (Double.IsNegativeInfinity (pg.BoundingMapRect.Size.Width), Is.True, "BoundingMapRect.Size.Width"); + Assert.That (pg.Intersects (pg.BoundingMapRect), Is.False, "Intersect/Self"); MKMapRect rect = new MKMapRect (0, 0, 0, 0); - Assert.False (pg.Intersects (rect), "Intersect/Empty"); + Assert.That (pg.Intersects (rect), Is.False, "Intersect/Empty"); ShapeTest.CheckShape (pg); } @@ -103,7 +103,7 @@ public void setCoordinate_Selector () pg.Coordinate = new CLLocationCoordinate2D (10, 20); } catch (ObjCException mte) { - Assert.True (mte.Message.Contains ("unrecognized selector sent to instance")); + Assert.That (mte.Message.Contains ("unrecognized selector sent to instance"), Is.True); } catch { Assert.Fail ("API could be working/implemented"); diff --git a/tests/monotouch-test/MapKit/PolylineTest.cs b/tests/monotouch-test/MapKit/PolylineTest.cs index 4c4bc7602489..23f6f6ae65e1 100644 --- a/tests/monotouch-test/MapKit/PolylineTest.cs +++ b/tests/monotouch-test/MapKit/PolylineTest.cs @@ -32,21 +32,21 @@ void CheckEmpty (MKPolyline pl) Assert.That (pl.Coordinate.Latitude, Is.EqualTo (-90f), "Coordinate.Latitude"); else Assert.That (pl.Coordinate.Latitude, Is.NaN, "Coordinate.Latitude"); - Assert.Null (pl.Title, "Title"); - Assert.Null (pl.Subtitle, "Subtitle"); + Assert.That (pl.Title, Is.Null, "Title"); + Assert.That (pl.Subtitle, Is.Null, "Subtitle"); // MKOverlay - Assert.True (Double.IsPositiveInfinity (pl.BoundingMapRect.Origin.X), "BoundingMapRect.Origin.X"); - Assert.True (Double.IsPositiveInfinity (pl.BoundingMapRect.Origin.Y), "BoundingMapRect.Origin.Y"); + Assert.That (Double.IsPositiveInfinity (pl.BoundingMapRect.Origin.X), Is.True, "BoundingMapRect.Origin.X"); + Assert.That (Double.IsPositiveInfinity (pl.BoundingMapRect.Origin.Y), Is.True, "BoundingMapRect.Origin.Y"); if (TestRuntime.CheckXcodeVersion (5, 0, 1)) { Assert.That (pl.BoundingMapRect.Size.Height, Is.EqualTo (0.0f), "BoundingMapRect.Size.Height"); Assert.That (pl.BoundingMapRect.Size.Width, Is.EqualTo (0.0f), "BoundingMapRect.Size.Width"); } else { - Assert.True (Double.IsNegativeInfinity (pl.BoundingMapRect.Size.Height), "BoundingMapRect.Size.Height"); - Assert.True (Double.IsNegativeInfinity (pl.BoundingMapRect.Size.Width), "BoundingMapRect.Size.Width"); + Assert.That (Double.IsNegativeInfinity (pl.BoundingMapRect.Size.Height), Is.True, "BoundingMapRect.Size.Height"); + Assert.That (Double.IsNegativeInfinity (pl.BoundingMapRect.Size.Width), Is.True, "BoundingMapRect.Size.Width"); } - Assert.False (pl.Intersects (pl.BoundingMapRect), "Intersect/Self"); + Assert.That (pl.Intersects (pl.BoundingMapRect), Is.False, "Intersect/Self"); MKMapRect rect = new MKMapRect (0, 0, 0, 0); - Assert.False (pl.Intersects (rect), "Intersect/Empty"); + Assert.That (pl.Intersects (rect), Is.False, "Intersect/Empty"); ShapeTest.CheckShape (pl); } @@ -83,7 +83,7 @@ public void setCoordinate_Selector () pl.Coordinate = new CLLocationCoordinate2D (10, 20); } catch (ObjCException mte) { - Assert.True (mte.Message.Contains ("unrecognized selector sent to instance")); + Assert.That (mte.Message.Contains ("unrecognized selector sent to instance"), Is.True); } catch { Assert.Fail ("API could be working/implemented"); diff --git a/tests/monotouch-test/MediaAccessibility/AudibleMediaTest.cs b/tests/monotouch-test/MediaAccessibility/AudibleMediaTest.cs index 0bcceb877002..aa247aae384f 100644 --- a/tests/monotouch-test/MediaAccessibility/AudibleMediaTest.cs +++ b/tests/monotouch-test/MediaAccessibility/AudibleMediaTest.cs @@ -24,9 +24,9 @@ public void PreferredCharacteristics () TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 10, 10, throwIfOtherPlatform: false); if (TestRuntime.CheckXcodeVersion (7, 0)) { - Assert.NotNull (MAAudibleMedia.GetPreferredCharacteristics ()); + Assert.That (MAAudibleMedia.GetPreferredCharacteristics (), Is.Not.Null); } else { - Assert.Null (MAAudibleMedia.GetPreferredCharacteristics ()); + Assert.That (MAAudibleMedia.GetPreferredCharacteristics (), Is.Null); } } } diff --git a/tests/monotouch-test/MediaAccessibility/ImageCaptioningTest.cs b/tests/monotouch-test/MediaAccessibility/ImageCaptioningTest.cs index 0927046856c3..82da8929bd03 100644 --- a/tests/monotouch-test/MediaAccessibility/ImageCaptioningTest.cs +++ b/tests/monotouch-test/MediaAccessibility/ImageCaptioningTest.cs @@ -26,22 +26,22 @@ public void GetCaption () Assert.Throws (() => MAImageCaptioning.GetCaption (null, out _)); using (NSUrl url = new NSUrl (NetworkResources.MicrosoftUrl)) { var s = MAImageCaptioning.GetCaption (url, out var e); - Assert.Null (s, "remote / return value"); + Assert.That (s, Is.Null, "remote / return value"); Assert.That (e, Is.Null.Or.Not.Null, "remote / error"); // sometimes we get an error, and sometimes we don't 🤷‍♂️ } string file = Path.Combine (NSBundle.MainBundle.ResourcePath, "basn3p08.png"); file = file.Replace (" ", "%20"); using (NSUrl url = new NSUrl (file)) { var s = MAImageCaptioning.GetCaption (url, out var e); - Assert.Null (s, "local / return value"); - Assert.NotNull (e, "local / error"); // does not like the URL (invalid) + Assert.That (s, Is.Null, "local / return value"); + Assert.That (e, Is.Not.Null, "local / error"); // does not like the URL (invalid) } file = NSBundle.MainBundle.ResourceUrl.AbsoluteString + "basn3p08.png"; file = file.Replace (" ", "%20"); using (NSUrl url = new NSUrl (file)) { var s = MAImageCaptioning.GetCaption (url, out var e); - Assert.Null (s, "local / return value"); - Assert.Null (e, "local / no error"); + Assert.That (s, Is.Null, "local / return value"); + Assert.That (e, Is.Null, "local / no error"); } } @@ -70,43 +70,43 @@ public void SetCaption () var read_only = Runtime.Arch == Arch.DEVICE; #endif if (read_only) { - Assert.False (MAImageCaptioning.SetCaption (url, "xamarin", out var e), "Set"); - Assert.NotNull (e, "ro / set / no error"); // weird, it can't be saved back to the file metadata + Assert.That (MAImageCaptioning.SetCaption (url, "xamarin", out var e), Is.False, "Set"); + Assert.That (e, Is.Not.Null, "ro / set / no error"); // weird, it can't be saved back to the file metadata var s = MAImageCaptioning.GetCaption (url, out e); - Assert.Null (s, "ro / roundtrip 1"); // not very surprising since Set can't save it - Assert.Null (e, "ro / get / no error"); + Assert.That (s, Is.Null, "ro / roundtrip 1"); // not very surprising since Set can't save it + Assert.That (e, Is.Null, "ro / get / no error"); - Assert.False (MAImageCaptioning.SetCaption (url, "xamarin", out e), "Set 2"); + Assert.That (MAImageCaptioning.SetCaption (url, "xamarin", out e), Is.False, "Set 2"); s = MAImageCaptioning.GetCaption (url, out e); - Assert.Null (s, "ro / back to original"); - Assert.Null (e, "ro / get back / no error"); + Assert.That (s, Is.Null, "ro / back to original"); + Assert.That (e, Is.Null, "ro / get back / no error"); } else { - Assert.True (MAImageCaptioning.SetCaption (url, "xamarin", out var e), "Set"); - Assert.Null (e, "ro / set / no error"); // weird, it can't be saved back to the file metadata + Assert.That (MAImageCaptioning.SetCaption (url, "xamarin", out var e), Is.True, "Set"); + Assert.That (e, Is.Null, "ro / set / no error"); // weird, it can't be saved back to the file metadata var s = MAImageCaptioning.GetCaption (url, out e); if (TestRuntime.CheckXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch)) { - Assert.AreEqual ("xamarin", s, "ro / roundtrip 2"); + Assert.That (s, Is.EqualTo ("xamarin"), "ro / roundtrip 2"); } else { - Assert.Null (s, "ro / roundtrip 3"); // not very surprising since Set can't save it + Assert.That (s, Is.Null, "ro / roundtrip 3"); // not very surprising since Set can't save it } - Assert.Null (e, "ro / get / no error"); + Assert.That (e, Is.Null, "ro / get / no error"); - Assert.True (MAImageCaptioning.SetCaption (url, "xamarin", out e), "Set 2"); + Assert.That (MAImageCaptioning.SetCaption (url, "xamarin", out e), Is.True, "Set 2"); s = MAImageCaptioning.GetCaption (url, out e); if (TestRuntime.CheckXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch)) { - Assert.AreEqual ("xamarin", s, "ro / back to original"); + Assert.That (s, Is.EqualTo ("xamarin"), "ro / back to original"); } else { - Assert.Null (s, "ro / back to original"); + Assert.That (s, Is.Null, "ro / back to original"); } - Assert.Null (e, "ro / get back / no error"); + Assert.That (e, Is.Null, "ro / get back / no error"); // Restore original value - Assert.True (MAImageCaptioning.SetCaption (url, null, out e), "Set 2"); + Assert.That (MAImageCaptioning.SetCaption (url, null, out e), Is.True, "Set 2"); s = MAImageCaptioning.GetCaption (url, out e); - Assert.Null (s, "ro / back to null"); - Assert.Null (e, "ro / get back null / no error"); + Assert.That (s, Is.Null, "ro / back to null"); + Assert.That (e, Is.Null, "ro / get back null / no error"); } // 2nd try with a read/write copy @@ -114,25 +114,25 @@ public void SetCaption () File.Copy (url.Path, temp, overwrite: true); } using (var rw_url = NSUrl.FromFilename (temp)) { - Assert.True (MAImageCaptioning.SetCaption (rw_url, "xamarin", out var e), "Set"); - Assert.Null (e, "rw / set / no error"); // weird, it can't be saved back to the file metadata + Assert.That (MAImageCaptioning.SetCaption (rw_url, "xamarin", out var e), Is.True, "Set"); + Assert.That (e, Is.Null, "rw / set / no error"); // weird, it can't be saved back to the file metadata var s = MAImageCaptioning.GetCaption (rw_url, out e); if (TestRuntime.CheckXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch)) { - Assert.AreEqual ("xamarin", s, "rw / roundtrip"); // :) + Assert.That (s, Is.EqualTo ("xamarin"), "rw / roundtrip"); // :) } else { - Assert.Null (s, "rw / roundtrip"); // :( + Assert.That (s, Is.Null, "rw / roundtrip"); // :( } - Assert.Null (e, "rw / get / no error"); + Assert.That (e, Is.Null, "rw / get / no error"); - Assert.True (MAImageCaptioning.SetCaption (rw_url, "xamarin", out e), "Set 2"); + Assert.That (MAImageCaptioning.SetCaption (rw_url, "xamarin", out e), Is.True, "Set 2"); s = MAImageCaptioning.GetCaption (rw_url, out e); if (TestRuntime.CheckXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch)) { - Assert.AreEqual ("xamarin", s, "rw / back to original"); + Assert.That (s, Is.EqualTo ("xamarin"), "rw / back to original"); } else { - Assert.Null (s, "rw / back to original"); + Assert.That (s, Is.Null, "rw / back to original"); } - Assert.Null (e, "rw / get back / no error"); + Assert.That (e, Is.Null, "rw / get back / no error"); } } finally { diff --git a/tests/monotouch-test/MediaExtension/MERawProcessingBooleanParameterTest.cs b/tests/monotouch-test/MediaExtension/MERawProcessingBooleanParameterTest.cs index 07329dee10c2..2c685fe1b015 100644 --- a/tests/monotouch-test/MediaExtension/MERawProcessingBooleanParameterTest.cs +++ b/tests/monotouch-test/MediaExtension/MERawProcessingBooleanParameterTest.cs @@ -12,15 +12,15 @@ public void CtorTest_Neutral () using var obj = new MERawProcessingBooleanParameter ("name", "key", "description", false, true, MERawProcessingBooleanParameterInitializationOption.NeutralValue); Assert.Multiple (() => { - Assert.AreEqual ("name", obj.Name, "Name"); - Assert.AreEqual ("key", obj.Key, "Key"); - Assert.IsNull (obj.LongDescription, "LongDescription"); - Assert.IsFalse (obj.InitialValue, "InitialValue"); - Assert.IsFalse (obj.CurrentValue, "CurrentValue"); - Assert.IsTrue (obj.HasNeutralValue (out var neutralValue), "HasNeutralValue"); - Assert.IsTrue (neutralValue, "NeutralValue"); - Assert.IsFalse (obj.HasCameraValue (out var cameraValue), "HasCameraValue"); - Assert.IsFalse (cameraValue, "NeutralValue"); + Assert.That (obj.Name, Is.EqualTo ("name"), "Name"); + Assert.That (obj.Key, Is.EqualTo ("key"), "Key"); + Assert.That (obj.LongDescription, Is.Null, "LongDescription"); + Assert.That (obj.InitialValue, Is.False, "InitialValue"); + Assert.That (obj.CurrentValue, Is.False, "CurrentValue"); + Assert.That (obj.HasNeutralValue (out var neutralValue), Is.True, "HasNeutralValue"); + Assert.That (neutralValue, Is.True, "NeutralValue"); + Assert.That (obj.HasCameraValue (out var cameraValue), Is.False, "HasCameraValue"); + Assert.That (cameraValue, Is.False, "NeutralValue"); }); } @@ -31,15 +31,15 @@ public void CtorTest_Camera () using var obj = new MERawProcessingBooleanParameter ("name", "key", "description", false, true, MERawProcessingBooleanParameterInitializationOption.CameraValue); Assert.Multiple (() => { - Assert.AreEqual ("name", obj.Name, "Name"); - Assert.AreEqual ("key", obj.Key, "Key"); - Assert.IsNull (obj.LongDescription, "LongDescription"); - Assert.IsFalse (obj.InitialValue, "InitialValue"); - Assert.IsFalse (obj.CurrentValue, "CurrentValue"); - Assert.IsFalse (obj.HasNeutralValue (out var neutralValue), "HasNeutralValue"); - Assert.IsFalse (neutralValue, "NeutralValue"); - Assert.IsTrue (obj.HasCameraValue (out var cameraValue), "HasCameraValue"); - Assert.IsTrue (cameraValue, "NeutralValue"); + Assert.That (obj.Name, Is.EqualTo ("name"), "Name"); + Assert.That (obj.Key, Is.EqualTo ("key"), "Key"); + Assert.That (obj.LongDescription, Is.Null, "LongDescription"); + Assert.That (obj.InitialValue, Is.False, "InitialValue"); + Assert.That (obj.CurrentValue, Is.False, "CurrentValue"); + Assert.That (obj.HasNeutralValue (out var neutralValue), Is.False, "HasNeutralValue"); + Assert.That (neutralValue, Is.False, "NeutralValue"); + Assert.That (obj.HasCameraValue (out var cameraValue), Is.True, "HasCameraValue"); + Assert.That (cameraValue, Is.True, "NeutralValue"); }); } } diff --git a/tests/monotouch-test/MediaExtension/MERawProcessingFloatParameterTest.cs b/tests/monotouch-test/MediaExtension/MERawProcessingFloatParameterTest.cs index 9cd03351f6ee..1621d859e67c 100644 --- a/tests/monotouch-test/MediaExtension/MERawProcessingFloatParameterTest.cs +++ b/tests/monotouch-test/MediaExtension/MERawProcessingFloatParameterTest.cs @@ -12,17 +12,17 @@ public void CtorTest_Neutral () using var obj = new MERawProcessingFloatParameter ("name", "key", "description", 1.2f, 3.4f, 0.1f, 1.1f, MERawProcessingFloatParameterInitializationOption.NeutralValue); Assert.Multiple (() => { - Assert.AreEqual ("name", obj.Name, "Name"); - Assert.AreEqual ("key", obj.Key, "Key"); - Assert.IsNull (obj.LongDescription, "LongDescription"); - Assert.AreEqual (1.2f, obj.InitialValue, "InitialValue"); - Assert.AreEqual (1.2f, obj.CurrentValue, "CurrentValue"); - Assert.AreEqual (3.4f, obj.MaximumValue, "MaximumValue"); - Assert.AreEqual (0.1f, obj.MinimumValue, "MinimumValue"); - Assert.IsTrue (obj.HasNeutralValue (out var neutralValue), "HasNeutralValue"); - Assert.AreEqual (1.1f, neutralValue, "NeutralValue"); - Assert.IsFalse (obj.HasCameraValue (out var cameraValue), "HasCameraValue"); - Assert.AreEqual (0f, cameraValue, "NeutralValue"); + Assert.That (obj.Name, Is.EqualTo ("name"), "Name"); + Assert.That (obj.Key, Is.EqualTo ("key"), "Key"); + Assert.That (obj.LongDescription, Is.Null, "LongDescription"); + Assert.That (obj.InitialValue, Is.EqualTo (1.2f), "InitialValue"); + Assert.That (obj.CurrentValue, Is.EqualTo (1.2f), "CurrentValue"); + Assert.That (obj.MaximumValue, Is.EqualTo (3.4f), "MaximumValue"); + Assert.That (obj.MinimumValue, Is.EqualTo (0.1f), "MinimumValue"); + Assert.That (obj.HasNeutralValue (out var neutralValue), Is.True, "HasNeutralValue"); + Assert.That (neutralValue, Is.EqualTo (1.1f), "NeutralValue"); + Assert.That (obj.HasCameraValue (out var cameraValue), Is.False, "HasCameraValue"); + Assert.That (cameraValue, Is.EqualTo (0f), "NeutralValue"); }); } @@ -33,17 +33,17 @@ public void CtorTest_Camera () using var obj = new MERawProcessingFloatParameter ("name", "key", "description", 1.2f, 3.4f, 0.1f, 1.1f, MERawProcessingFloatParameterInitializationOption.CameraValue); Assert.Multiple (() => { - Assert.AreEqual ("name", obj.Name, "Name"); - Assert.AreEqual ("key", obj.Key, "Key"); - Assert.IsNull (obj.LongDescription, "LongDescription"); - Assert.AreEqual (1.2f, obj.InitialValue, "InitialValue"); - Assert.AreEqual (1.2f, obj.CurrentValue, "CurrentValue"); - Assert.AreEqual (3.4f, obj.MaximumValue, "MaximumValue"); - Assert.AreEqual (0.1f, obj.MinimumValue, "MinimumValue"); - Assert.IsFalse (obj.HasNeutralValue (out var neutralValue), "HasNeutralValue"); - Assert.AreEqual (0f, neutralValue, "NeutralValue"); - Assert.IsTrue (obj.HasCameraValue (out var cameraValue), "HasCameraValue"); - Assert.AreEqual (1.1f, cameraValue, "NeutralValue"); + Assert.That (obj.Name, Is.EqualTo ("name"), "Name"); + Assert.That (obj.Key, Is.EqualTo ("key"), "Key"); + Assert.That (obj.LongDescription, Is.Null, "LongDescription"); + Assert.That (obj.InitialValue, Is.EqualTo (1.2f), "InitialValue"); + Assert.That (obj.CurrentValue, Is.EqualTo (1.2f), "CurrentValue"); + Assert.That (obj.MaximumValue, Is.EqualTo (3.4f), "MaximumValue"); + Assert.That (obj.MinimumValue, Is.EqualTo (0.1f), "MinimumValue"); + Assert.That (obj.HasNeutralValue (out var neutralValue), Is.False, "HasNeutralValue"); + Assert.That (neutralValue, Is.EqualTo (0f), "NeutralValue"); + Assert.That (obj.HasCameraValue (out var cameraValue), Is.True, "HasCameraValue"); + Assert.That (cameraValue, Is.EqualTo (1.1f), "NeutralValue"); }); } } diff --git a/tests/monotouch-test/MediaExtension/MERawProcessingIntegerParameterTest.cs b/tests/monotouch-test/MediaExtension/MERawProcessingIntegerParameterTest.cs index f6dc89068d4b..f6c2c5f2151b 100644 --- a/tests/monotouch-test/MediaExtension/MERawProcessingIntegerParameterTest.cs +++ b/tests/monotouch-test/MediaExtension/MERawProcessingIntegerParameterTest.cs @@ -12,17 +12,17 @@ public void CtorTest_Neutral () using var obj = new MERawProcessingIntegerParameter ("name", "key", "description", 3, 5, 1, 2, MERawProcessingIntegerParameterInitializationOption.NeutralValue); Assert.Multiple (() => { - Assert.AreEqual ("name", obj.Name, "Name"); - Assert.AreEqual ("key", obj.Key, "Key"); - Assert.IsNull (obj.LongDescription, "LongDescription"); - Assert.AreEqual ((nint) 3, obj.InitialValue, "InitialValue"); - Assert.AreEqual ((nint) 3, obj.CurrentValue, "CurrentValue"); - Assert.AreEqual ((nint) 5, obj.MaximumValue, "MaximumValue"); - Assert.AreEqual ((nint) 1, obj.MinimumValue, "MinimumValue"); - Assert.IsTrue (obj.HasNeutralValue (out var neutralValue), "HasNeutralValue"); - Assert.AreEqual ((nint) 2, neutralValue, "NeutralValue"); - Assert.IsFalse (obj.HasCameraValue (out var cameraValue), "HasCameraValue"); - Assert.AreEqual ((nint) 0, cameraValue, "NeutralValue"); + Assert.That (obj.Name, Is.EqualTo ("name"), "Name"); + Assert.That (obj.Key, Is.EqualTo ("key"), "Key"); + Assert.That (obj.LongDescription, Is.Null, "LongDescription"); + Assert.That (obj.InitialValue, Is.EqualTo ((nint) 3), "InitialValue"); + Assert.That (obj.CurrentValue, Is.EqualTo ((nint) 3), "CurrentValue"); + Assert.That (obj.MaximumValue, Is.EqualTo ((nint) 5), "MaximumValue"); + Assert.That (obj.MinimumValue, Is.EqualTo ((nint) 1), "MinimumValue"); + Assert.That (obj.HasNeutralValue (out var neutralValue), Is.True, "HasNeutralValue"); + Assert.That (neutralValue, Is.EqualTo ((nint) 2), "NeutralValue"); + Assert.That (obj.HasCameraValue (out var cameraValue), Is.False, "HasCameraValue"); + Assert.That (cameraValue, Is.EqualTo ((nint) 0), "NeutralValue"); }); } @@ -33,17 +33,17 @@ public void CtorTest_Camera () using var obj = new MERawProcessingIntegerParameter ("name", "key", "description", 3, 5, 1, 2, MERawProcessingIntegerParameterInitializationOption.CameraValue); Assert.Multiple (() => { - Assert.AreEqual ("name", obj.Name, "Name"); - Assert.AreEqual ("key", obj.Key, "Key"); - Assert.IsNull (obj.LongDescription, "LongDescription"); - Assert.AreEqual ((nint) 3, obj.InitialValue, "InitialValue"); - Assert.AreEqual ((nint) 3, obj.CurrentValue, "CurrentValue"); - Assert.AreEqual ((nint) 5, obj.MaximumValue, "MaximumValue"); - Assert.AreEqual ((nint) 1, obj.MinimumValue, "MinimumValue"); - Assert.IsFalse (obj.HasNeutralValue (out var neutralValue), "HasNeutralValue"); - Assert.AreEqual ((nint) 0, neutralValue, "NeutralValue"); - Assert.IsTrue (obj.HasCameraValue (out var cameraValue), "HasCameraValue"); - Assert.AreEqual ((nint) 2, cameraValue, "NeutralValue"); + Assert.That (obj.Name, Is.EqualTo ("name"), "Name"); + Assert.That (obj.Key, Is.EqualTo ("key"), "Key"); + Assert.That (obj.LongDescription, Is.Null, "LongDescription"); + Assert.That (obj.InitialValue, Is.EqualTo ((nint) 3), "InitialValue"); + Assert.That (obj.CurrentValue, Is.EqualTo ((nint) 3), "CurrentValue"); + Assert.That (obj.MaximumValue, Is.EqualTo ((nint) 5), "MaximumValue"); + Assert.That (obj.MinimumValue, Is.EqualTo ((nint) 1), "MinimumValue"); + Assert.That (obj.HasNeutralValue (out var neutralValue), Is.False, "HasNeutralValue"); + Assert.That (neutralValue, Is.EqualTo ((nint) 0), "NeutralValue"); + Assert.That (obj.HasCameraValue (out var cameraValue), Is.True, "HasCameraValue"); + Assert.That (cameraValue, Is.EqualTo ((nint) 2), "NeutralValue"); }); } } diff --git a/tests/monotouch-test/MediaExtension/MERawProcessingListParameterTest.cs b/tests/monotouch-test/MediaExtension/MERawProcessingListParameterTest.cs index 9f219ba4d043..d6c25d084f51 100644 --- a/tests/monotouch-test/MediaExtension/MERawProcessingListParameterTest.cs +++ b/tests/monotouch-test/MediaExtension/MERawProcessingListParameterTest.cs @@ -18,15 +18,15 @@ public void CtorTest_Neutral () }; using var obj = new MERawProcessingListParameter ("name", "key", "description", array, 1, 3, MERawProcessingListParameterInitializationOption.NeutralValue); Assert.Multiple (() => { - Assert.AreEqual ("name", obj.Name, "Name"); - Assert.AreEqual ("key", obj.Key, "Key"); - Assert.IsNull (obj.LongDescription, "LongDescription"); - Assert.AreEqual ((nint) 1, obj.InitialValue, "InitialValue"); - Assert.AreEqual ((nint) 1, obj.CurrentValue, "CurrentValue"); - Assert.IsTrue (obj.HasNeutralValue (out var neutralValue), "HasNeutralValue"); - Assert.AreEqual ((nint) 3, neutralValue, "NeutralValue"); - Assert.IsFalse (obj.HasCameraValue (out var cameraValue), "HasCameraValue"); - Assert.AreEqual ((nint) 0, cameraValue, "NeutralValue"); + Assert.That (obj.Name, Is.EqualTo ("name"), "Name"); + Assert.That (obj.Key, Is.EqualTo ("key"), "Key"); + Assert.That (obj.LongDescription, Is.Null, "LongDescription"); + Assert.That (obj.InitialValue, Is.EqualTo ((nint) 1), "InitialValue"); + Assert.That (obj.CurrentValue, Is.EqualTo ((nint) 1), "CurrentValue"); + Assert.That (obj.HasNeutralValue (out var neutralValue), Is.True, "HasNeutralValue"); + Assert.That (neutralValue, Is.EqualTo ((nint) 3), "NeutralValue"); + Assert.That (obj.HasCameraValue (out var cameraValue), Is.False, "HasCameraValue"); + Assert.That (cameraValue, Is.EqualTo ((nint) 0), "NeutralValue"); }); } @@ -43,15 +43,15 @@ public void CtorTest_Camera () }; using var obj = new MERawProcessingListParameter ("name", "key", "description", array, 1, 3, MERawProcessingListParameterInitializationOption.CameraValue); Assert.Multiple (() => { - Assert.AreEqual ("name", obj.Name, "Name"); - Assert.AreEqual ("key", obj.Key, "Key"); - Assert.IsNull (obj.LongDescription, "LongDescription"); - Assert.AreEqual ((nint) 1, obj.InitialValue, "InitialValue"); - Assert.AreEqual ((nint) 1, obj.CurrentValue, "CurrentValue"); - Assert.IsFalse (obj.HasNeutralValue (out var neutralValue), "HasNeutralValue"); - Assert.AreEqual ((nint) 0, neutralValue, "NeutralValue"); - Assert.IsTrue (obj.HasCameraValue (out var cameraValue), "HasCameraValue"); - Assert.AreEqual ((nint) 3, cameraValue, "NeutralValue"); + Assert.That (obj.Name, Is.EqualTo ("name"), "Name"); + Assert.That (obj.Key, Is.EqualTo ("key"), "Key"); + Assert.That (obj.LongDescription, Is.Null, "LongDescription"); + Assert.That (obj.InitialValue, Is.EqualTo ((nint) 1), "InitialValue"); + Assert.That (obj.CurrentValue, Is.EqualTo ((nint) 1), "CurrentValue"); + Assert.That (obj.HasNeutralValue (out var neutralValue), Is.False, "HasNeutralValue"); + Assert.That (neutralValue, Is.EqualTo ((nint) 0), "NeutralValue"); + Assert.That (obj.HasCameraValue (out var cameraValue), Is.True, "HasCameraValue"); + Assert.That (cameraValue, Is.EqualTo ((nint) 3), "NeutralValue"); }); } } diff --git a/tests/monotouch-test/MediaPlayer/NowPlayingInfoCenterTest.cs b/tests/monotouch-test/MediaPlayer/NowPlayingInfoCenterTest.cs index 48d1ce38314a..bf1d7072e655 100644 --- a/tests/monotouch-test/MediaPlayer/NowPlayingInfoCenterTest.cs +++ b/tests/monotouch-test/MediaPlayer/NowPlayingInfoCenterTest.cs @@ -74,43 +74,43 @@ public void NowPlaying () dc.NowPlaying = NowPlayingInfo; // internal NSDictionary ToDictionary () var np = dc.NowPlaying; // internal MPNowPlayingInfo (NSDictionary source) - Assert.IsInstanceOf (typeof (double), np.ElapsedPlaybackTime, "#1"); - Assert.IsInstanceOf (typeof (double), np.PlaybackRate, "#2"); + Assert.That (np.ElapsedPlaybackTime, Is.InstanceOf (typeof (double)), "#1"); + Assert.That (np.PlaybackRate, Is.InstanceOf (typeof (double)), "#2"); if (v8_0) - Assert.IsInstanceOf (typeof (double), np.DefaultPlaybackRate, "#3"); - Assert.IsInstanceOf (typeof (int), np.PlaybackQueueIndex, "#4"); - Assert.IsInstanceOf (typeof (int), np.PlaybackQueueCount, "#5"); - Assert.IsInstanceOf (typeof (int), np.ChapterNumber, "#6"); - Assert.IsInstanceOf (typeof (int), np.ChapterCount, "#7"); + Assert.That (np.DefaultPlaybackRate, Is.InstanceOf (typeof (double)), "#3"); + Assert.That (np.PlaybackQueueIndex, Is.InstanceOf (typeof (int)), "#4"); + Assert.That (np.PlaybackQueueCount, Is.InstanceOf (typeof (int)), "#5"); + Assert.That (np.ChapterNumber, Is.InstanceOf (typeof (int)), "#6"); + Assert.That (np.ChapterCount, Is.InstanceOf (typeof (int)), "#7"); if (v9_0) { - Assert.IsInstanceOf (typeof (MPNowPlayingInfoLanguageOptionGroup []), np.AvailableLanguageOptions, "#8"); - Assert.IsInstanceOf (typeof (MPNowPlayingInfoLanguageOption []), np.CurrentLanguageOptions, "#9"); + Assert.That (np.AvailableLanguageOptions, Is.InstanceOf (typeof (MPNowPlayingInfoLanguageOptionGroup [])), "#8"); + Assert.That (np.CurrentLanguageOptions, Is.InstanceOf (typeof (MPNowPlayingInfoLanguageOption [])), "#9"); } if (v10_0) { - Assert.IsInstanceOf (typeof (string), (object) np.CollectionIdentifier, "#10"); - Assert.IsInstanceOf (typeof (string), (object) np.ExternalContentIdentifier, "#11"); - Assert.IsInstanceOf (typeof (string), (object) np.ExternalUserProfileIdentifier, "#12"); - Assert.IsInstanceOf (typeof (float), np.PlaybackProgress, "#13"); - Assert.IsInstanceOf (typeof (MPNowPlayingInfoMediaType), np.MediaType, "#14"); - Assert.IsInstanceOf (typeof (bool), np.IsLiveStream, "#15"); + Assert.That ((object) np.CollectionIdentifier, Is.InstanceOf (typeof (string)), "#10"); + Assert.That ((object) np.ExternalContentIdentifier, Is.InstanceOf (typeof (string)), "#11"); + Assert.That ((object) np.ExternalUserProfileIdentifier, Is.InstanceOf (typeof (string)), "#12"); + Assert.That (np.PlaybackProgress, Is.InstanceOf (typeof (float)), "#13"); + Assert.That (np.MediaType, Is.InstanceOf (typeof (MPNowPlayingInfoMediaType)), "#14"); + Assert.That (np.IsLiveStream, Is.InstanceOf (typeof (bool)), "#15"); } - Assert.IsInstanceOf (typeof (string), (object) np.AlbumTitle, "#16"); - Assert.IsInstanceOf (typeof (int), np.AlbumTrackCount, "#17"); - Assert.IsInstanceOf (typeof (int), np.AlbumTrackNumber, "#18"); - Assert.IsInstanceOf (typeof (string), (object) np.Artist, "#19"); - Assert.IsInstanceOf (typeof (MPMediaItemArtwork), np.Artwork, "#20"); - Assert.IsInstanceOf (typeof (string), (object) np.Composer, "#21"); - Assert.IsInstanceOf (typeof (int), np.DiscCount, "#22"); - Assert.IsInstanceOf (typeof (int), np.DiscNumber, "#23"); - Assert.IsInstanceOf (typeof (string), (object) np.Genre, "#24"); - Assert.IsInstanceOf (typeof (ulong), np.PersistentID, "#25"); - Assert.IsInstanceOf (typeof (double), np.PlaybackDuration, "#26"); - Assert.IsInstanceOf (typeof (string), (object) np.Title, "#27"); + Assert.That ((object) np.AlbumTitle, Is.InstanceOf (typeof (string)), "#16"); + Assert.That (np.AlbumTrackCount, Is.InstanceOf (typeof (int)), "#17"); + Assert.That (np.AlbumTrackNumber, Is.InstanceOf (typeof (int)), "#18"); + Assert.That ((object) np.Artist, Is.InstanceOf (typeof (string)), "#19"); + Assert.That (np.Artwork, Is.InstanceOf (typeof (MPMediaItemArtwork)), "#20"); + Assert.That ((object) np.Composer, Is.InstanceOf (typeof (string)), "#21"); + Assert.That (np.DiscCount, Is.InstanceOf (typeof (int)), "#22"); + Assert.That (np.DiscNumber, Is.InstanceOf (typeof (int)), "#23"); + Assert.That ((object) np.Genre, Is.InstanceOf (typeof (string)), "#24"); + Assert.That (np.PersistentID, Is.InstanceOf (typeof (ulong)), "#25"); + Assert.That (np.PlaybackDuration, Is.InstanceOf (typeof (double)), "#26"); + Assert.That ((object) np.Title, Is.InstanceOf (typeof (string)), "#27"); if (v10_3) - Assert.IsInstanceOf (typeof (NSUrl), np.AssetUrl, "#28"); + Assert.That (np.AssetUrl, Is.InstanceOf (typeof (NSUrl)), "#28"); } } } diff --git a/tests/monotouch-test/MediaPlayer/RemoteCommandCenterTest.cs b/tests/monotouch-test/MediaPlayer/RemoteCommandCenterTest.cs index 7e05e6725ead..94eaada1508c 100644 --- a/tests/monotouch-test/MediaPlayer/RemoteCommandCenterTest.cs +++ b/tests/monotouch-test/MediaPlayer/RemoteCommandCenterTest.cs @@ -26,20 +26,20 @@ public void Shared () TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 10, 12, 2, throwIfOtherPlatform: false); MPRemoteCommandCenter shared = MPRemoteCommandCenter.Shared; - Assert.NotNull (shared.BookmarkCommand, "BookmarkCommand"); - Assert.NotNull (shared.ChangePlaybackRateCommand, "ChangePlaybackRateCommand"); - Assert.NotNull (shared.DislikeCommand, "DislikeCommand"); - Assert.NotNull (shared.LikeCommand, "LikeCommand"); - Assert.NotNull (shared.NextTrackCommand, "NextTrackCommand"); - Assert.NotNull (shared.PauseCommand, "PauseCommand"); - Assert.NotNull (shared.PlayCommand, "PlayCommand"); - Assert.NotNull (shared.PreviousTrackCommand, "PreviousTrackCommand"); - Assert.NotNull (shared.SeekBackwardCommand, "SeekBackwardCommand"); - Assert.NotNull (shared.SeekForwardCommand, "SeekForwardCommand"); - Assert.NotNull (shared.SkipBackwardCommand, "SkipBackwardCommand"); - Assert.NotNull (shared.SkipForwardCommand, "SkipForwardCommand"); - Assert.NotNull (shared.StopCommand, "StopCommand"); - Assert.NotNull (shared.TogglePlayPauseCommand, "TogglePlayPauseCommand"); + Assert.That (shared.BookmarkCommand, Is.Not.Null, "BookmarkCommand"); + Assert.That (shared.ChangePlaybackRateCommand, Is.Not.Null, "ChangePlaybackRateCommand"); + Assert.That (shared.DislikeCommand, Is.Not.Null, "DislikeCommand"); + Assert.That (shared.LikeCommand, Is.Not.Null, "LikeCommand"); + Assert.That (shared.NextTrackCommand, Is.Not.Null, "NextTrackCommand"); + Assert.That (shared.PauseCommand, Is.Not.Null, "PauseCommand"); + Assert.That (shared.PlayCommand, Is.Not.Null, "PlayCommand"); + Assert.That (shared.PreviousTrackCommand, Is.Not.Null, "PreviousTrackCommand"); + Assert.That (shared.SeekBackwardCommand, Is.Not.Null, "SeekBackwardCommand"); + Assert.That (shared.SeekForwardCommand, Is.Not.Null, "SeekForwardCommand"); + Assert.That (shared.SkipBackwardCommand, Is.Not.Null, "SkipBackwardCommand"); + Assert.That (shared.SkipForwardCommand, Is.Not.Null, "SkipForwardCommand"); + Assert.That (shared.StopCommand, Is.Not.Null, "StopCommand"); + Assert.That (shared.TogglePlayPauseCommand, Is.Not.Null, "TogglePlayPauseCommand"); } [Test] @@ -49,8 +49,8 @@ public void Shared_8 () TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 10, 12, 2, throwIfOtherPlatform: false); MPRemoteCommandCenter shared = MPRemoteCommandCenter.Shared; - Assert.NotNull (shared.ChangeRepeatModeCommand, "ChangeRepeatModeCommand"); - Assert.NotNull (shared.ChangeShuffleModeCommand, "ChangeShuffleModeCommand"); + Assert.That (shared.ChangeRepeatModeCommand, Is.Not.Null, "ChangeRepeatModeCommand"); + Assert.That (shared.ChangeShuffleModeCommand, Is.Not.Null, "ChangeShuffleModeCommand"); } [Test] @@ -60,7 +60,7 @@ public void Shared_9 () TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 10, 12, 2, throwIfOtherPlatform: false); MPRemoteCommandCenter shared = MPRemoteCommandCenter.Shared; - Assert.NotNull (shared.EnableLanguageOptionCommand, "EnableLanguageOptionCommand"); + Assert.That (shared.EnableLanguageOptionCommand, Is.Not.Null, "EnableLanguageOptionCommand"); } } } diff --git a/tests/monotouch-test/MediaPlayer/SkipIntervalCommandTest.cs b/tests/monotouch-test/MediaPlayer/SkipIntervalCommandTest.cs index a5ef7c302068..f3a504d55c4d 100644 --- a/tests/monotouch-test/MediaPlayer/SkipIntervalCommandTest.cs +++ b/tests/monotouch-test/MediaPlayer/SkipIntervalCommandTest.cs @@ -35,7 +35,7 @@ public void ManualBinding () if (TestRuntime.CheckXcodeVersion (11, 0)) { Assert.That (skip.PreferredIntervals, Is.EqualTo (new double [] { 10.0d }), "PreferredIntervals"); } else { - Assert.Null (skip.PreferredIntervals, "PreferredIntervals"); + Assert.That (skip.PreferredIntervals, Is.Null, "PreferredIntervals"); } double [] intervals = new [] { 1.0d, 3.14d }; skip.PreferredIntervals = intervals; diff --git a/tests/monotouch-test/MediaToolbox/AudioProcessingTapTest.cs b/tests/monotouch-test/MediaToolbox/AudioProcessingTapTest.cs index 685dde972379..b63b9d3275bf 100644 --- a/tests/monotouch-test/MediaToolbox/AudioProcessingTapTest.cs +++ b/tests/monotouch-test/MediaToolbox/AudioProcessingTapTest.cs @@ -38,7 +38,7 @@ public unsafe void Initialization () IntPtr handle; using (var res = new MTAudioProcessingTap (cb, MTAudioProcessingTapCreationFlags.PreEffects)) { handle = res.Handle; - Assert.AreEqual (44, (int) res.GetStorage ()); + Assert.That ((int) res.GetStorage (), Is.EqualTo (44)); Assert.That (CFGetRetainCount (handle), Is.EqualTo ((nint) 1), "RC"); } } diff --git a/tests/monotouch-test/MessageUI/MailComposeViewControllerTest.cs b/tests/monotouch-test/MessageUI/MailComposeViewControllerTest.cs index 44abbec9d81a..4a4ac9cd0dae 100644 --- a/tests/monotouch-test/MessageUI/MailComposeViewControllerTest.cs +++ b/tests/monotouch-test/MessageUI/MailComposeViewControllerTest.cs @@ -41,9 +41,9 @@ public void MailComposeDelegate () Assert.Inconclusive ("Not configured to send emails"); using (var mail = new MFMailComposeViewController ()) { - Assert.Null (mail.MailComposeDelegate, "MailComposeDelegate"); + Assert.That (mail.MailComposeDelegate, Is.Null, "MailComposeDelegate"); mail.Finished += (sender, e) => { }; - Assert.NotNull (mail.MailComposeDelegate, "MailComposeDelegate"); + Assert.That (mail.MailComposeDelegate, Is.Not.Null, "MailComposeDelegate"); } } } diff --git a/tests/monotouch-test/MessageUI/MessageComposeViewControllerTest.cs b/tests/monotouch-test/MessageUI/MessageComposeViewControllerTest.cs index c163d0d0bf06..2a5e637777d1 100644 --- a/tests/monotouch-test/MessageUI/MessageComposeViewControllerTest.cs +++ b/tests/monotouch-test/MessageUI/MessageComposeViewControllerTest.cs @@ -27,9 +27,9 @@ public void MessageComposeDelegate () Assert.Inconclusive ("Not configured to send text"); using (var mail = new MFMessageComposeViewController ()) { - Assert.Null (mail.MessageComposeDelegate, "MessageComposeDelegate"); + Assert.That (mail.MessageComposeDelegate, Is.Null, "MessageComposeDelegate"); mail.Finished += (sender, e) => { }; - Assert.NotNull (mail.MessageComposeDelegate, "MessageComposeDelegate"); + Assert.That (mail.MessageComposeDelegate, Is.Not.Null, "MessageComposeDelegate"); } } } diff --git a/tests/monotouch-test/Metal/ClearValueTest.cs b/tests/monotouch-test/Metal/ClearValueTest.cs index 3a2e234dba19..fc17c9a799ba 100644 --- a/tests/monotouch-test/Metal/ClearValueTest.cs +++ b/tests/monotouch-test/Metal/ClearValueTest.cs @@ -12,31 +12,31 @@ public void Constructor () value = new MTLClearValue (); - Assert.AreEqual (0, value.Color.Alpha, "1-color-alpha"); - Assert.AreEqual (0, value.Color.Blue, "1-color-blue"); - Assert.AreEqual (0, value.Color.Green, "1-color-green"); - Assert.AreEqual (0, value.Color.Red, "1-color-red"); - Assert.AreEqual (0, value.Depth, "1-depth"); - Assert.AreEqual (0, value.Stencil, "1-stencil"); + Assert.That (value.Color.Alpha, Is.EqualTo (0), "1-color-alpha"); + Assert.That (value.Color.Blue, Is.EqualTo (0), "1-color-blue"); + Assert.That (value.Color.Green, Is.EqualTo (0), "1-color-green"); + Assert.That (value.Color.Red, Is.EqualTo (0), "1-color-red"); + Assert.That (value.Depth, Is.EqualTo (0), "1-depth"); + Assert.That (value.Stencil, Is.EqualTo (0), "1-stencil"); value = new MTLClearValue (0.2f); - Assert.AreEqual (0.2f, value.Depth, "2-depth"); + Assert.That (value.Depth, Is.EqualTo (0.2f), "2-depth"); value = new MTLClearValue (123); - Assert.AreEqual (123, value.Stencil, "3-stencil"); + Assert.That (value.Stencil, Is.EqualTo (123), "3-stencil"); value = new MTLClearValue (-2); - Assert.AreEqual (-2, value.Depth, "4-depth"); + Assert.That (value.Depth, Is.EqualTo (-2), "4-depth"); value = new MTLClearValue (new MTLClearColor (1, 2, 3, 4)); - Assert.AreEqual (4, value.Color.Alpha, "5-color-alpha"); - Assert.AreEqual (3, value.Color.Blue, "5-color-blue"); - Assert.AreEqual (2, value.Color.Green, "5-color-green"); - Assert.AreEqual (1, value.Color.Red, "5-color-red"); + Assert.That (value.Color.Alpha, Is.EqualTo (4), "5-color-alpha"); + Assert.That (value.Color.Blue, Is.EqualTo (3), "5-color-blue"); + Assert.That (value.Color.Green, Is.EqualTo (2), "5-color-green"); + Assert.That (value.Color.Red, Is.EqualTo (1), "5-color-red"); } } } diff --git a/tests/monotouch-test/Metal/HeapDescriptorTest.cs b/tests/monotouch-test/Metal/HeapDescriptorTest.cs index 62d2911e5d32..d375e6e287d4 100644 --- a/tests/monotouch-test/Metal/HeapDescriptorTest.cs +++ b/tests/monotouch-test/Metal/HeapDescriptorTest.cs @@ -56,7 +56,7 @@ public void GetSetCpuCacheModeTest () TestRuntime.AssertXcodeVersion (9, 0); hd.CpuCacheMode = MTLCpuCacheMode.WriteCombined; - Assert.AreEqual (MTLCpuCacheMode.WriteCombined, hd.CpuCacheMode); + Assert.That (hd.CpuCacheMode, Is.EqualTo (MTLCpuCacheMode.WriteCombined)); } [Test] @@ -65,7 +65,7 @@ public void GetSetSizeTest () TestRuntime.AssertXcodeVersion (9, 0); hd.Size = 2; - Assert.AreEqual ((nuint) 2, hd.Size); + Assert.That (hd.Size, Is.EqualTo ((nuint) 2)); } [Test] @@ -74,7 +74,7 @@ public void GetSetStorageModeTest () TestRuntime.AssertXcodeVersion (9, 0); hd.StorageMode = MTLStorageMode.Private; - Assert.AreEqual (MTLStorageMode.Private, hd.StorageMode); + Assert.That (hd.StorageMode, Is.EqualTo (MTLStorageMode.Private)); } [Test] diff --git a/tests/monotouch-test/Metal/MTKMeshTest.cs b/tests/monotouch-test/Metal/MTKMeshTest.cs index b1c54f52cd63..48f9d615b32d 100644 --- a/tests/monotouch-test/Metal/MTKMeshTest.cs +++ b/tests/monotouch-test/Metal/MTKMeshTest.cs @@ -33,11 +33,11 @@ public void FromAsset () var result = MTKMesh.FromAsset (asset, device, out var sourceMeshes, out var error); - Assert.IsNull (error, "error"); - Assert.IsNotNull (result, "result"); + Assert.That (error, Is.Null, "error"); + Assert.That (result, Is.Not.Null, "result"); Assert.That (result!.Length, Is.GreaterThan (0), "result length"); - Assert.IsNotNull (sourceMeshes, "sourceMeshes"); - Assert.AreEqual (result.Length, sourceMeshes!.Length, "sourceMeshes length"); + Assert.That (sourceMeshes, Is.Not.Null, "sourceMeshes"); + Assert.That (sourceMeshes!.Length, Is.EqualTo (result.Length), "sourceMeshes length"); } } } diff --git a/tests/monotouch-test/Metal/MTL4CommandBufferTests.cs b/tests/monotouch-test/Metal/MTL4CommandBufferTests.cs index 43abe0260080..e7956316b200 100644 --- a/tests/monotouch-test/Metal/MTL4CommandBufferTests.cs +++ b/tests/monotouch-test/Metal/MTL4CommandBufferTests.cs @@ -22,8 +22,8 @@ public void UseResidencySets () InitialCapacity = 3, }; using var residencySet = device.CreateResidencySet (residencySetDescriptor, out var error); - Assert.IsNull (error, "Error #1"); - Assert.IsNotNull (residencySet, "ResidencySet #1"); + Assert.That (error, Is.Null, "Error #1"); + Assert.That (residencySet, Is.Not.Null, "ResidencySet #1"); commandBuffer.UseResidencySets (residencySet); commandBuffer.UseResidencySets (new IMTLResidencySet [] { residencySet }); diff --git a/tests/monotouch-test/Metal/MTL4CommandQueueTests.cs b/tests/monotouch-test/Metal/MTL4CommandQueueTests.cs index a3c141df5350..73ca9be16d3f 100644 --- a/tests/monotouch-test/Metal/MTL4CommandQueueTests.cs +++ b/tests/monotouch-test/Metal/MTL4CommandQueueTests.cs @@ -46,8 +46,8 @@ public void AddOrRemoveResidencySets () InitialCapacity = 3 }; using var residencySet = device.CreateResidencySet (residencySetDescriptor, out var error); - Assert.IsNull (error, "Error #1"); - Assert.IsNotNull (residencySet, "ResidencySet #1"); + Assert.That (error, Is.Null, "Error #1"); + Assert.That (residencySet, Is.Not.Null, "ResidencySet #1"); commandQ.AddResidencySets (residencySet); commandQ.RemoveResidencySets (residencySet); diff --git a/tests/monotouch-test/Metal/MTL4CopySparseBufferMappingOperationTest.cs b/tests/monotouch-test/Metal/MTL4CopySparseBufferMappingOperationTest.cs index 5f0f0de40afd..fdf97c4cef2d 100644 --- a/tests/monotouch-test/Metal/MTL4CopySparseBufferMappingOperationTest.cs +++ b/tests/monotouch-test/Metal/MTL4CopySparseBufferMappingOperationTest.cs @@ -18,8 +18,8 @@ public void Constructor_Default_InitializesWithDefaultValues () var operation = new MTL4CopySparseBufferMappingOperation (); // Assert - Assert.AreEqual (default (NSRange), operation.SourceRange); - Assert.AreEqual (default (nuint), operation.DestinationOffset); + Assert.That (operation.SourceRange, Is.EqualTo (default (NSRange))); + Assert.That (operation.DestinationOffset, Is.EqualTo (default (nuint))); } [Test] @@ -33,7 +33,7 @@ public void SourceRange_SetAndGet_ReturnsCorrectValue () operation.SourceRange = expectedRange; // Assert - Assert.AreEqual (expectedRange, operation.SourceRange); + Assert.That (operation.SourceRange, Is.EqualTo (expectedRange)); } [Test] @@ -47,7 +47,7 @@ public void DestinationOffset_SetAndGet_ReturnsCorrectValue () operation.DestinationOffset = expectedOffset; // Assert - Assert.AreEqual (expectedOffset, operation.DestinationOffset); + Assert.That (operation.DestinationOffset, Is.EqualTo (expectedOffset)); } [Test] @@ -63,8 +63,8 @@ public void Properties_SetAllProperties_RetainsAllValues () operation.DestinationOffset = expectedOffset; // Assert - Assert.AreEqual (expectedRange, operation.SourceRange); - Assert.AreEqual (expectedOffset, operation.DestinationOffset); + Assert.That (operation.SourceRange, Is.EqualTo (expectedRange)); + Assert.That (operation.DestinationOffset, Is.EqualTo (expectedOffset)); } [Test] @@ -78,9 +78,9 @@ public void SourceRange_WithZeroLength_HandlesCorrectly () operation.SourceRange = zeroLengthRange; // Assert - Assert.AreEqual (zeroLengthRange, operation.SourceRange); - Assert.AreEqual (10, (int) operation.SourceRange.Location); - Assert.AreEqual (0, (int) operation.SourceRange.Length); + Assert.That (operation.SourceRange, Is.EqualTo (zeroLengthRange)); + Assert.That ((int) operation.SourceRange.Location, Is.EqualTo (10)); + Assert.That ((int) operation.SourceRange.Length, Is.EqualTo (0)); } [Test] @@ -94,7 +94,7 @@ public void SourceRange_WithMaxValues_HandlesCorrectly () operation.SourceRange = maxRange; // Assert - Assert.AreEqual (maxRange, operation.SourceRange); + Assert.That (operation.SourceRange, Is.EqualTo (maxRange)); } [Test] @@ -107,7 +107,7 @@ public void DestinationOffset_WithZeroValue_HandlesCorrectly () operation.DestinationOffset = 0; // Assert - Assert.AreEqual (0, (int) operation.DestinationOffset); + Assert.That ((int) operation.DestinationOffset, Is.EqualTo (0)); } [Test] @@ -120,7 +120,7 @@ public void DestinationOffset_WithMaxValue_HandlesCorrectly () operation.DestinationOffset = nuint.MaxValue; // Assert - Assert.AreEqual (nuint.MaxValue, operation.DestinationOffset); + Assert.That (operation.DestinationOffset, Is.EqualTo (nuint.MaxValue)); } [Test] @@ -138,8 +138,8 @@ public void Struct_MultipleInstances_AreIndependent () operation2.DestinationOffset = 2048; // Assert - Assert.AreNotEqual (operation1.SourceRange, operation2.SourceRange); - Assert.AreNotEqual (operation1.DestinationOffset, operation2.DestinationOffset); + Assert.That (operation2.SourceRange, Is.Not.EqualTo (operation1.SourceRange)); + Assert.That (operation2.DestinationOffset, Is.Not.EqualTo (operation1.DestinationOffset)); } [Test] @@ -153,9 +153,9 @@ public void SourceRange_WithLargeValues_HandlesCorrectly () operation.SourceRange = largeRange; // Assert - Assert.AreEqual (largeRange, operation.SourceRange); - Assert.AreEqual (1000000, (int) operation.SourceRange.Location); - Assert.AreEqual (500000, (int) operation.SourceRange.Length); + Assert.That (operation.SourceRange, Is.EqualTo (largeRange)); + Assert.That ((int) operation.SourceRange.Location, Is.EqualTo (1000000)); + Assert.That ((int) operation.SourceRange.Length, Is.EqualTo (500000)); } } } diff --git a/tests/monotouch-test/Metal/MTL4CopySparseTextureMappingOperationTest.cs b/tests/monotouch-test/Metal/MTL4CopySparseTextureMappingOperationTest.cs index 3da1c8552a12..9a3b2d3ff3d1 100644 --- a/tests/monotouch-test/Metal/MTL4CopySparseTextureMappingOperationTest.cs +++ b/tests/monotouch-test/Metal/MTL4CopySparseTextureMappingOperationTest.cs @@ -18,12 +18,12 @@ public void Constructor_Default_InitializesWithDefaultValues () var operation = new MTL4CopySparseTextureMappingOperation (); // Assert - Assert.AreEqual (default (MTLRegion), operation.SourceRegion); - Assert.AreEqual (default (nuint), operation.SourceLevel); - Assert.AreEqual (default (nuint), operation.SourceSlice); - Assert.AreEqual (default (MTLOrigin), operation.DestinationOrigin); - Assert.AreEqual (default (nuint), operation.DestinationLevel); - Assert.AreEqual (default (nuint), operation.DestinationSlice); + Assert.That (operation.SourceRegion, Is.EqualTo (default (MTLRegion))); + Assert.That (operation.SourceLevel, Is.EqualTo (default (nuint))); + Assert.That (operation.SourceSlice, Is.EqualTo (default (nuint))); + Assert.That (operation.DestinationOrigin, Is.EqualTo (default (MTLOrigin))); + Assert.That (operation.DestinationLevel, Is.EqualTo (default (nuint))); + Assert.That (operation.DestinationSlice, Is.EqualTo (default (nuint))); } [Test] @@ -37,7 +37,7 @@ public void SourceRegion_SetAndGet_ReturnsCorrectValue () operation.SourceRegion = expectedRegion; // Assert - Assert.AreEqual (expectedRegion, operation.SourceRegion); + Assert.That (operation.SourceRegion, Is.EqualTo (expectedRegion)); } [Test] @@ -51,7 +51,7 @@ public void SourceLevel_SetAndGet_ReturnsCorrectValue () operation.SourceLevel = expectedLevel; // Assert - Assert.AreEqual (expectedLevel, operation.SourceLevel); + Assert.That (operation.SourceLevel, Is.EqualTo (expectedLevel)); } [Test] @@ -65,7 +65,7 @@ public void SourceSlice_SetAndGet_ReturnsCorrectValue () operation.SourceSlice = expectedSlice; // Assert - Assert.AreEqual (expectedSlice, operation.SourceSlice); + Assert.That (operation.SourceSlice, Is.EqualTo (expectedSlice)); } [Test] @@ -79,7 +79,7 @@ public void DestinationOrigin_SetAndGet_ReturnsCorrectValue () operation.DestinationOrigin = expectedOrigin; // Assert - Assert.AreEqual (expectedOrigin, operation.DestinationOrigin); + Assert.That (operation.DestinationOrigin, Is.EqualTo (expectedOrigin)); } [Test] @@ -93,7 +93,7 @@ public void DestinationLevel_SetAndGet_ReturnsCorrectValue () operation.DestinationLevel = expectedLevel; // Assert - Assert.AreEqual (expectedLevel, operation.DestinationLevel); + Assert.That (operation.DestinationLevel, Is.EqualTo (expectedLevel)); } [Test] @@ -107,7 +107,7 @@ public void DestinationSlice_SetAndGet_ReturnsCorrectValue () operation.DestinationSlice = expectedSlice; // Assert - Assert.AreEqual (expectedSlice, operation.DestinationSlice); + Assert.That (operation.DestinationSlice, Is.EqualTo (expectedSlice)); } [Test] @@ -131,12 +131,12 @@ public void Properties_SetAllProperties_RetainsAllValues () operation.DestinationSlice = expectedDestinationSlice; // Assert - Assert.AreEqual (expectedSourceRegion, operation.SourceRegion); - Assert.AreEqual (expectedSourceLevel, operation.SourceLevel); - Assert.AreEqual (expectedSourceSlice, operation.SourceSlice); - Assert.AreEqual (expectedDestinationOrigin, operation.DestinationOrigin); - Assert.AreEqual (expectedDestinationLevel, operation.DestinationLevel); - Assert.AreEqual (expectedDestinationSlice, operation.DestinationSlice); + Assert.That (operation.SourceRegion, Is.EqualTo (expectedSourceRegion)); + Assert.That (operation.SourceLevel, Is.EqualTo (expectedSourceLevel)); + Assert.That (operation.SourceSlice, Is.EqualTo (expectedSourceSlice)); + Assert.That (operation.DestinationOrigin, Is.EqualTo (expectedDestinationOrigin)); + Assert.That (operation.DestinationLevel, Is.EqualTo (expectedDestinationLevel)); + Assert.That (operation.DestinationSlice, Is.EqualTo (expectedDestinationSlice)); } [Test] @@ -152,10 +152,10 @@ public void LevelAndSlice_WithZeroValues_HandlesCorrectly () operation.DestinationSlice = 0; // Assert - Assert.AreEqual (0, (int) operation.SourceLevel); - Assert.AreEqual (0, (int) operation.SourceSlice); - Assert.AreEqual (0, (int) operation.DestinationLevel); - Assert.AreEqual (0, (int) operation.DestinationSlice); + Assert.That ((int) operation.SourceLevel, Is.EqualTo (0)); + Assert.That ((int) operation.SourceSlice, Is.EqualTo (0)); + Assert.That ((int) operation.DestinationLevel, Is.EqualTo (0)); + Assert.That ((int) operation.DestinationSlice, Is.EqualTo (0)); } [Test] @@ -171,10 +171,10 @@ public void LevelAndSlice_WithMaxValues_HandlesCorrectly () operation.DestinationSlice = nuint.MaxValue; // Assert - Assert.AreEqual (nuint.MaxValue, operation.SourceLevel); - Assert.AreEqual (nuint.MaxValue, operation.SourceSlice); - Assert.AreEqual (nuint.MaxValue, operation.DestinationLevel); - Assert.AreEqual (nuint.MaxValue, operation.DestinationSlice); + Assert.That (operation.SourceLevel, Is.EqualTo (nuint.MaxValue)); + Assert.That (operation.SourceSlice, Is.EqualTo (nuint.MaxValue)); + Assert.That (operation.DestinationLevel, Is.EqualTo (nuint.MaxValue)); + Assert.That (operation.DestinationSlice, Is.EqualTo (nuint.MaxValue)); } [Test] @@ -194,9 +194,9 @@ public void Struct_MultipleInstances_AreIndependent () operation2.SourceSlice = 7; // Assert - Assert.AreNotEqual (operation1.SourceRegion, operation2.SourceRegion); - Assert.AreNotEqual (operation1.SourceLevel, operation2.SourceLevel); - Assert.AreNotEqual (operation1.SourceSlice, operation2.SourceSlice); + Assert.That (operation2.SourceRegion, Is.Not.EqualTo (operation1.SourceRegion)); + Assert.That (operation2.SourceLevel, Is.Not.EqualTo (operation1.SourceLevel)); + Assert.That (operation2.SourceSlice, Is.Not.EqualTo (operation1.SourceSlice)); } [Test] @@ -210,7 +210,7 @@ public void SourceRegion_WithZeroSize_HandlesCorrectly () operation.SourceRegion = zeroSizeRegion; // Assert - Assert.AreEqual (zeroSizeRegion, operation.SourceRegion); + Assert.That (operation.SourceRegion, Is.EqualTo (zeroSizeRegion)); } [Test] @@ -224,7 +224,7 @@ public void DestinationOrigin_WithZeroValues_HandlesCorrectly () operation.DestinationOrigin = zeroOrigin; // Assert - Assert.AreEqual (zeroOrigin, operation.DestinationOrigin); + Assert.That (operation.DestinationOrigin, Is.EqualTo (zeroOrigin)); } } } diff --git a/tests/monotouch-test/Metal/MTL4UpdateSparseBufferMappingOperationTest.cs b/tests/monotouch-test/Metal/MTL4UpdateSparseBufferMappingOperationTest.cs index 4282d3a7c186..7cd4216817cc 100644 --- a/tests/monotouch-test/Metal/MTL4UpdateSparseBufferMappingOperationTest.cs +++ b/tests/monotouch-test/Metal/MTL4UpdateSparseBufferMappingOperationTest.cs @@ -18,9 +18,9 @@ public void Constructor_Default_InitializesWithDefaultValues () var operation = new MTL4UpdateSparseBufferMappingOperation (); // Assert - Assert.AreEqual (default (MTLSparseTextureMappingMode), operation.Mode); - Assert.AreEqual (default (NSRange), operation.BufferRange); - Assert.AreEqual (default (nuint), operation.HeapOffset); + Assert.That (operation.Mode, Is.EqualTo (default (MTLSparseTextureMappingMode))); + Assert.That (operation.BufferRange, Is.EqualTo (default (NSRange))); + Assert.That (operation.HeapOffset, Is.EqualTo (default (nuint))); } [Test] @@ -34,7 +34,7 @@ public void Mode_SetAndGet_ReturnsCorrectValue () operation.Mode = expectedMode; // Assert - Assert.AreEqual (expectedMode, operation.Mode); + Assert.That (operation.Mode, Is.EqualTo (expectedMode)); } [Test] @@ -48,7 +48,7 @@ public void BufferRange_SetAndGet_ReturnsCorrectValue () operation.BufferRange = expectedRange; // Assert - Assert.AreEqual (expectedRange, operation.BufferRange); + Assert.That (operation.BufferRange, Is.EqualTo (expectedRange)); } [Test] @@ -62,7 +62,7 @@ public void HeapOffset_SetAndGet_ReturnsCorrectValue () operation.HeapOffset = expectedOffset; // Assert - Assert.AreEqual (expectedOffset, operation.HeapOffset); + Assert.That (operation.HeapOffset, Is.EqualTo (expectedOffset)); } [Test] @@ -80,9 +80,9 @@ public void Properties_SetAllProperties_RetainsAllValues () operation.HeapOffset = expectedOffset; // Assert - Assert.AreEqual (expectedMode, operation.Mode); - Assert.AreEqual (expectedRange, operation.BufferRange); - Assert.AreEqual (expectedOffset, operation.HeapOffset); + Assert.That (operation.Mode, Is.EqualTo (expectedMode)); + Assert.That (operation.BufferRange, Is.EqualTo (expectedRange)); + Assert.That (operation.HeapOffset, Is.EqualTo (expectedOffset)); } [Test] @@ -96,9 +96,9 @@ public void BufferRange_WithZeroLength_HandlesCorrectly () operation.BufferRange = zeroLengthRange; // Assert - Assert.AreEqual (zeroLengthRange, operation.BufferRange); - Assert.AreEqual (10, (int) operation.BufferRange.Location); - Assert.AreEqual (0, (int) operation.BufferRange.Length); + Assert.That (operation.BufferRange, Is.EqualTo (zeroLengthRange)); + Assert.That ((int) operation.BufferRange.Location, Is.EqualTo (10)); + Assert.That ((int) operation.BufferRange.Length, Is.EqualTo (0)); } [Test] @@ -112,7 +112,7 @@ public void BufferRange_WithMaxValues_HandlesCorrectly () operation.BufferRange = maxRange; // Assert - Assert.AreEqual (maxRange, operation.BufferRange); + Assert.That (operation.BufferRange, Is.EqualTo (maxRange)); } [Test] @@ -125,7 +125,7 @@ public void HeapOffset_WithZeroValue_HandlesCorrectly () operation.HeapOffset = 0; // Assert - Assert.AreEqual (0, (int) operation.HeapOffset); + Assert.That ((int) operation.HeapOffset, Is.EqualTo (0)); } [Test] @@ -138,7 +138,7 @@ public void HeapOffset_WithMaxValue_HandlesCorrectly () operation.HeapOffset = nuint.MaxValue; // Assert - Assert.AreEqual (nuint.MaxValue, operation.HeapOffset); + Assert.That (operation.HeapOffset, Is.EqualTo (nuint.MaxValue)); } [Test] @@ -151,7 +151,7 @@ public void Mode_WithAllValidValues_HandlesCorrectly () // Act & Assert foreach (var mode in validModes) { operation.Mode = mode; - Assert.AreEqual (mode, operation.Mode); + Assert.That (operation.Mode, Is.EqualTo (mode)); } } @@ -172,10 +172,10 @@ public void Struct_MultipleInstances_AreIndependent () operation2.HeapOffset = 2048; // Assert - Assert.AreEqual (MTLSparseTextureMappingMode.Map, operation1.Mode); - Assert.AreEqual (MTLSparseTextureMappingMode.Unmap, operation2.Mode); - Assert.AreNotEqual (operation1.BufferRange, operation2.BufferRange); - Assert.AreNotEqual (operation1.HeapOffset, operation2.HeapOffset); + Assert.That (operation1.Mode, Is.EqualTo (MTLSparseTextureMappingMode.Map)); + Assert.That (operation2.Mode, Is.EqualTo (MTLSparseTextureMappingMode.Unmap)); + Assert.That (operation2.BufferRange, Is.Not.EqualTo (operation1.BufferRange)); + Assert.That (operation2.HeapOffset, Is.Not.EqualTo (operation1.HeapOffset)); } } } diff --git a/tests/monotouch-test/Metal/MTL4UpdateSparseTextureMappingOperationTest.cs b/tests/monotouch-test/Metal/MTL4UpdateSparseTextureMappingOperationTest.cs index f7b5b175af7e..752ca8bc938a 100644 --- a/tests/monotouch-test/Metal/MTL4UpdateSparseTextureMappingOperationTest.cs +++ b/tests/monotouch-test/Metal/MTL4UpdateSparseTextureMappingOperationTest.cs @@ -18,11 +18,11 @@ public void Constructor_Default_InitializesWithDefaultValues () var operation = new MTL4UpdateSparseTextureMappingOperation (); // Assert - Assert.AreEqual (default (MTLSparseTextureMappingMode), operation.Mode); - Assert.AreEqual (default (MTLRegion), operation.TextureRegion); - Assert.AreEqual (default (nuint), operation.TextureLevel); - Assert.AreEqual (default (nuint), operation.TextureSlice); - Assert.AreEqual (default (nuint), operation.HeapOffset); + Assert.That (operation.Mode, Is.EqualTo (default (MTLSparseTextureMappingMode))); + Assert.That (operation.TextureRegion, Is.EqualTo (default (MTLRegion))); + Assert.That (operation.TextureLevel, Is.EqualTo (default (nuint))); + Assert.That (operation.TextureSlice, Is.EqualTo (default (nuint))); + Assert.That (operation.HeapOffset, Is.EqualTo (default (nuint))); } [Test] @@ -36,7 +36,7 @@ public void Mode_SetAndGet_ReturnsCorrectValue () operation.Mode = expectedMode; // Assert - Assert.AreEqual (expectedMode, operation.Mode); + Assert.That (operation.Mode, Is.EqualTo (expectedMode)); } [Test] @@ -50,7 +50,7 @@ public void TextureRegion_SetAndGet_ReturnsCorrectValue () operation.TextureRegion = expectedRegion; // Assert - Assert.AreEqual (expectedRegion, operation.TextureRegion); + Assert.That (operation.TextureRegion, Is.EqualTo (expectedRegion)); } [Test] @@ -64,7 +64,7 @@ public void TextureLevel_SetAndGet_ReturnsCorrectValue () operation.TextureLevel = expectedLevel; // Assert - Assert.AreEqual (expectedLevel, operation.TextureLevel); + Assert.That (operation.TextureLevel, Is.EqualTo (expectedLevel)); } [Test] @@ -78,7 +78,7 @@ public void TextureSlice_SetAndGet_ReturnsCorrectValue () operation.TextureSlice = expectedSlice; // Assert - Assert.AreEqual (expectedSlice, operation.TextureSlice); + Assert.That (operation.TextureSlice, Is.EqualTo (expectedSlice)); } [Test] @@ -92,7 +92,7 @@ public void HeapOffset_SetAndGet_ReturnsCorrectValue () operation.HeapOffset = expectedOffset; // Assert - Assert.AreEqual (expectedOffset, operation.HeapOffset); + Assert.That (operation.HeapOffset, Is.EqualTo (expectedOffset)); } [Test] @@ -114,11 +114,11 @@ public void Properties_SetAllProperties_RetainsAllValues () operation.HeapOffset = expectedOffset; // Assert - Assert.AreEqual (expectedMode, operation.Mode); - Assert.AreEqual (expectedRegion, operation.TextureRegion); - Assert.AreEqual (expectedLevel, operation.TextureLevel); - Assert.AreEqual (expectedSlice, operation.TextureSlice); - Assert.AreEqual (expectedOffset, operation.HeapOffset); + Assert.That (operation.Mode, Is.EqualTo (expectedMode)); + Assert.That (operation.TextureRegion, Is.EqualTo (expectedRegion)); + Assert.That (operation.TextureLevel, Is.EqualTo (expectedLevel)); + Assert.That (operation.TextureSlice, Is.EqualTo (expectedSlice)); + Assert.That (operation.HeapOffset, Is.EqualTo (expectedOffset)); } [Test] @@ -132,7 +132,7 @@ public void TextureRegion_WithZeroSize_HandlesCorrectly () operation.TextureRegion = zeroSizeRegion; // Assert - Assert.AreEqual (zeroSizeRegion, operation.TextureRegion); + Assert.That (operation.TextureRegion, Is.EqualTo (zeroSizeRegion)); } [Test] @@ -146,8 +146,8 @@ public void LevelAndSlice_WithZeroValues_HandlesCorrectly () operation.TextureSlice = 0; // Assert - Assert.AreEqual (0, (int) operation.TextureLevel); - Assert.AreEqual (0, (int) operation.TextureSlice); + Assert.That ((int) operation.TextureLevel, Is.EqualTo (0)); + Assert.That ((int) operation.TextureSlice, Is.EqualTo (0)); } [Test] @@ -161,8 +161,8 @@ public void LevelAndSlice_WithMaxValues_HandlesCorrectly () operation.TextureSlice = nuint.MaxValue; // Assert - Assert.AreEqual (nuint.MaxValue, operation.TextureLevel); - Assert.AreEqual (nuint.MaxValue, operation.TextureSlice); + Assert.That (operation.TextureLevel, Is.EqualTo (nuint.MaxValue)); + Assert.That (operation.TextureSlice, Is.EqualTo (nuint.MaxValue)); } [Test] @@ -175,7 +175,7 @@ public void HeapOffset_WithZeroValue_HandlesCorrectly () operation.HeapOffset = 0; // Assert - Assert.AreEqual (0, (int) operation.HeapOffset); + Assert.That ((int) operation.HeapOffset, Is.EqualTo (0)); } [Test] @@ -188,7 +188,7 @@ public void HeapOffset_WithMaxValue_HandlesCorrectly () operation.HeapOffset = nuint.MaxValue; // Assert - Assert.AreEqual (nuint.MaxValue, operation.HeapOffset); + Assert.That (operation.HeapOffset, Is.EqualTo (nuint.MaxValue)); } [Test] @@ -201,7 +201,7 @@ public void Mode_WithAllValidValues_HandlesCorrectly () // Act & Assert foreach (var mode in validModes) { operation.Mode = mode; - Assert.AreEqual (mode, operation.Mode); + Assert.That (operation.Mode, Is.EqualTo (mode)); } } @@ -226,12 +226,12 @@ public void Struct_MultipleInstances_AreIndependent () operation2.HeapOffset = 2048; // Assert - Assert.AreEqual (MTLSparseTextureMappingMode.Map, operation1.Mode); - Assert.AreEqual (MTLSparseTextureMappingMode.Unmap, operation2.Mode); - Assert.AreNotEqual (operation1.TextureRegion, operation2.TextureRegion); - Assert.AreNotEqual (operation1.TextureLevel, operation2.TextureLevel); - Assert.AreNotEqual (operation1.TextureSlice, operation2.TextureSlice); - Assert.AreNotEqual (operation1.HeapOffset, operation2.HeapOffset); + Assert.That (operation1.Mode, Is.EqualTo (MTLSparseTextureMappingMode.Map)); + Assert.That (operation2.Mode, Is.EqualTo (MTLSparseTextureMappingMode.Unmap)); + Assert.That (operation2.TextureRegion, Is.Not.EqualTo (operation1.TextureRegion)); + Assert.That (operation2.TextureLevel, Is.Not.EqualTo (operation1.TextureLevel)); + Assert.That (operation2.TextureSlice, Is.Not.EqualTo (operation1.TextureSlice)); + Assert.That (operation2.HeapOffset, Is.Not.EqualTo (operation1.HeapOffset)); } [Test] @@ -245,7 +245,7 @@ public void TextureRegion_WithLargeValues_HandlesCorrectly () operation.TextureRegion = largeRegion; // Assert - Assert.AreEqual (largeRegion, operation.TextureRegion); + Assert.That (operation.TextureRegion, Is.EqualTo (largeRegion)); } } } diff --git a/tests/monotouch-test/Metal/MTLArgumentDescriptorTest.cs b/tests/monotouch-test/Metal/MTLArgumentDescriptorTest.cs index 5866005ccebc..11e935c029c4 100644 --- a/tests/monotouch-test/Metal/MTLArgumentDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLArgumentDescriptorTest.cs @@ -27,42 +27,42 @@ public void TearDown () public void GetSetAccessTest () { descriptor.Access = MTLArgumentAccess.ReadWrite; - Assert.AreEqual (MTLArgumentAccess.ReadWrite, descriptor.Access); + Assert.That (descriptor.Access, Is.EqualTo (MTLArgumentAccess.ReadWrite)); } [Test] public void GetSetArrayLengthTest () { descriptor.ArrayLength = 1; - Assert.AreEqual ((nuint) 1, descriptor.ArrayLength); + Assert.That (descriptor.ArrayLength, Is.EqualTo ((nuint) 1)); } [Test] public void GetSetConstantBlockAlignmentTest () { descriptor.ConstantBlockAlignment = 1; - Assert.AreEqual ((nuint) 1, descriptor.ConstantBlockAlignment); + Assert.That (descriptor.ConstantBlockAlignment, Is.EqualTo ((nuint) 1)); } [Test] public void GetSetDataTypeTest () { descriptor.DataType = MTLDataType.Half4; - Assert.AreEqual (MTLDataType.Half4, descriptor.DataType); + Assert.That (descriptor.DataType, Is.EqualTo (MTLDataType.Half4)); } [Test] public void GetSetIndexTest () { descriptor.Index = 1; - Assert.AreEqual ((nuint) 1, descriptor.Index); + Assert.That (descriptor.Index, Is.EqualTo ((nuint) 1)); } [Test] public void GetSetTextureTypeTest () { descriptor.TextureType = MTLTextureType.k2DArray; - Assert.AreEqual (MTLTextureType.k2DArray, descriptor.TextureType); + Assert.That (descriptor.TextureType, Is.EqualTo (MTLTextureType.k2DArray)); } } } diff --git a/tests/monotouch-test/Metal/MTLAttributeDescriptorTest.cs b/tests/monotouch-test/Metal/MTLAttributeDescriptorTest.cs index 93489381f94c..7c567308e78a 100644 --- a/tests/monotouch-test/Metal/MTLAttributeDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLAttributeDescriptorTest.cs @@ -27,7 +27,7 @@ public void TearDown () public void GetSetFormatTest () { descriptor.Format = MTLAttributeFormat.Invalid; - Assert.AreEqual (MTLAttributeFormat.Invalid, descriptor.Format); + Assert.That (descriptor.Format, Is.EqualTo (MTLAttributeFormat.Invalid)); } [Test] @@ -35,7 +35,7 @@ public void GetSetOffsetTest () { uint offset = 0; // must be 0, other value will crash the test. descriptor.Offset = offset; - Assert.AreEqual ((nuint) offset, descriptor.Offset); + Assert.That (descriptor.Offset, Is.EqualTo ((nuint) offset)); } [Test] @@ -43,7 +43,7 @@ public void GetSetBufferIndexTest () { uint index = 0; // must be 0, other value will crash the test. descriptor.BufferIndex = index; - Assert.AreEqual ((nuint) index, descriptor.BufferIndex); + Assert.That (descriptor.BufferIndex, Is.EqualTo ((nuint) index)); } } } diff --git a/tests/monotouch-test/Metal/MTLAttributeTest.cs b/tests/monotouch-test/Metal/MTLAttributeTest.cs index 08a32782ff16..a0c93fb4c0d9 100644 --- a/tests/monotouch-test/Metal/MTLAttributeTest.cs +++ b/tests/monotouch-test/Metal/MTLAttributeTest.cs @@ -26,37 +26,37 @@ public void TearDown () [Test] public void GetNameTest () { - Assert.Null (attr.Name, $"Name default value is {attr.Name}"); + Assert.That (attr.Name, Is.Null, $"Name default value is {attr.Name}"); } [Test] public void GetAttributeIndexTest () { - Assert.AreEqual ((nuint) 0, attr.AttributeIndex, $"AttributeIndex default value is {attr.AttributeIndex}"); + Assert.That (attr.AttributeIndex, Is.EqualTo ((nuint) 0), $"AttributeIndex default value is {attr.AttributeIndex}"); } [Test] public void GetAttributeTypeTest () { - Assert.AreEqual (MTLDataType.None, attr.AttributeType, $"AttributeType default value is {attr.AttributeType}"); + Assert.That (attr.AttributeType, Is.EqualTo (MTLDataType.None), $"AttributeType default value is {attr.AttributeType}"); } [Test] public void GetActiveTest () { - Assert.False (attr.Active); + Assert.That (attr.Active, Is.False); } [Test] public void GetIsPatchDataTest () { - Assert.False (attr.IsPatchData); + Assert.That (attr.IsPatchData, Is.False); } [Test] public void GetIsPatchControlPointDataTest () { - Assert.False (attr.IsPatchControlPointData); + Assert.That (attr.IsPatchControlPointData, Is.False); } } } diff --git a/tests/monotouch-test/Metal/MTLBlitPassDescriptorTest.cs b/tests/monotouch-test/Metal/MTLBlitPassDescriptorTest.cs index 0b7dbd3178f3..2bb645b37932 100644 --- a/tests/monotouch-test/Metal/MTLBlitPassDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLBlitPassDescriptorTest.cs @@ -19,7 +19,7 @@ public void TestSampleBufferAttachments () { // need to be tested since it fails intro using var passDescripton = MTLBlitPassDescriptor.Create (); - Assert.IsNotNull (passDescripton, "passDescriptor"); + Assert.That (passDescripton, Is.Not.Null, "passDescriptor"); Assert.DoesNotThrow (() => { using var attachments = passDescripton.SampleBufferAttachments; // don't care about the value, just that it works }, "Attachements"); diff --git a/tests/monotouch-test/Metal/MTLBlitPassSampleBufferAttachmentDescriptorArrayTest.cs b/tests/monotouch-test/Metal/MTLBlitPassSampleBufferAttachmentDescriptorArrayTest.cs index 4eb24ff551f9..b69b5152dcef 100644 --- a/tests/monotouch-test/Metal/MTLBlitPassSampleBufferAttachmentDescriptorArrayTest.cs +++ b/tests/monotouch-test/Metal/MTLBlitPassSampleBufferAttachmentDescriptorArrayTest.cs @@ -35,8 +35,8 @@ public void IndexerTest () Assert.DoesNotThrow (() => { dupe = array [0]; }); - Assert.IsNotNull (dupe, "Dupe"); - Assert.AreNotEqual (IntPtr.Zero, dupe.Handle, "Dupe"); + Assert.That (dupe, Is.Not.Null, "Dupe"); + Assert.That (dupe.Handle, Is.Not.EqualTo (IntPtr.Zero), "Dupe"); } } } diff --git a/tests/monotouch-test/Metal/MTLBlitPassSampleBufferAttachmentDescriptorTest.cs b/tests/monotouch-test/Metal/MTLBlitPassSampleBufferAttachmentDescriptorTest.cs index 8a3fcdb6bb0b..177ca0e6f59a 100644 --- a/tests/monotouch-test/Metal/MTLBlitPassSampleBufferAttachmentDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLBlitPassSampleBufferAttachmentDescriptorTest.cs @@ -47,7 +47,7 @@ public void StartOfEncoderSampleIndexTest () Assert.DoesNotThrow (() => { objIndex = descriptor.StartOfEncoderSampleIndex; }, "Getter"); - Assert.AreEqual (newIndex, objIndex, "Value"); + Assert.That (objIndex, Is.EqualTo (newIndex), "Value"); } [Test] @@ -62,7 +62,7 @@ public void EndOfEncoderSampleIndexTest () Assert.DoesNotThrow (() => { objIndex = descriptor.EndOfEncoderSampleIndex; }, "Getter"); - Assert.AreEqual (newIndex, objIndex, "Value"); + Assert.That (objIndex, Is.EqualTo (newIndex), "Value"); } } diff --git a/tests/monotouch-test/Metal/MTLBufferLayoutDescriptorTest.cs b/tests/monotouch-test/Metal/MTLBufferLayoutDescriptorTest.cs index 4c04f8ffd026..9f86f21c5b6b 100644 --- a/tests/monotouch-test/Metal/MTLBufferLayoutDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLBufferLayoutDescriptorTest.cs @@ -19,7 +19,7 @@ public void GetSetStrideTest () uint stride = 8; var descriptor = new MTLBufferLayoutDescriptor (); descriptor.Stride = stride; - Assert.AreEqual ((nuint) stride, descriptor.Stride); + Assert.That (descriptor.Stride, Is.EqualTo ((nuint) stride)); } [Test] @@ -28,7 +28,7 @@ public void GetSetStepFunctionTest () var func = MTLStepFunction.Constant; var descriptor = new MTLBufferLayoutDescriptor (); descriptor.StepFunction = func; - Assert.AreEqual (func, descriptor.StepFunction); + Assert.That (descriptor.StepFunction, Is.EqualTo (func)); } [Test] @@ -37,7 +37,7 @@ public void GetSetStepRate () uint step = 8; var descriptor = new MTLBufferLayoutDescriptor (); descriptor.StepRate = step; - Assert.AreEqual ((nuint) step, descriptor.StepRate); + Assert.That (descriptor.StepRate, Is.EqualTo ((nuint) step)); } } } diff --git a/tests/monotouch-test/Metal/MTLCommandBufferTests.cs b/tests/monotouch-test/Metal/MTLCommandBufferTests.cs index c98bff847783..f8242b954517 100644 --- a/tests/monotouch-test/Metal/MTLCommandBufferTests.cs +++ b/tests/monotouch-test/Metal/MTLCommandBufferTests.cs @@ -32,8 +32,8 @@ public void UseResidencySets () InitialCapacity = 3 }; using var residencySet = device.CreateResidencySet (residencySetDescriptor, out var error); - Assert.IsNull (error, "Error #1"); - Assert.IsNotNull (residencySet, "ResidencySet #1"); + Assert.That (error, Is.Null, "Error #1"); + Assert.That (residencySet, Is.Not.Null, "ResidencySet #1"); commandBuffer.UseResidencySets (residencySet); commandBuffer.UseResidencySets (new IMTLResidencySet [] { residencySet }); diff --git a/tests/monotouch-test/Metal/MTLCommandQueueTests.cs b/tests/monotouch-test/Metal/MTLCommandQueueTests.cs index 5c713ea40c79..043df8b30cb2 100644 --- a/tests/monotouch-test/Metal/MTLCommandQueueTests.cs +++ b/tests/monotouch-test/Metal/MTLCommandQueueTests.cs @@ -28,8 +28,8 @@ public void AddOrRemoveResidencySets () InitialCapacity = 3 }; using var residencySet = device.CreateResidencySet (residencySetDescriptor, out var error); - Assert.IsNull (error, "Error #1"); - Assert.IsNotNull (residencySet, "ResidencySet #1"); + Assert.That (error, Is.Null, "Error #1"); + Assert.That (residencySet, Is.Not.Null, "ResidencySet #1"); commandQ.AddResidencySets (residencySet); commandQ.RemoveResidencySets (residencySet); diff --git a/tests/monotouch-test/Metal/MTLComputePassDescriptorTest.cs b/tests/monotouch-test/Metal/MTLComputePassDescriptorTest.cs index 916ff0f70cfe..c1c5d27574a5 100644 --- a/tests/monotouch-test/Metal/MTLComputePassDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLComputePassDescriptorTest.cs @@ -35,7 +35,7 @@ public void DispatchTypeTest () Assert.DoesNotThrow (() => { objType = descriptor.DispatchType; }, "Getter"); - Assert.AreEqual (newType, objType, "Type"); + Assert.That (objType, Is.EqualTo (newType), "Type"); } [Test] diff --git a/tests/monotouch-test/Metal/MTLComputePassSampleBufferAttachmentDescriptorArrayTest.cs b/tests/monotouch-test/Metal/MTLComputePassSampleBufferAttachmentDescriptorArrayTest.cs index 99c247c1185e..d2f4c0ee1471 100644 --- a/tests/monotouch-test/Metal/MTLComputePassSampleBufferAttachmentDescriptorArrayTest.cs +++ b/tests/monotouch-test/Metal/MTLComputePassSampleBufferAttachmentDescriptorArrayTest.cs @@ -35,8 +35,8 @@ public void IndexerTest () Assert.DoesNotThrow (() => { dupe = array [0]; }); - Assert.IsNotNull (dupe, "Dupe"); - Assert.AreNotEqual (IntPtr.Zero, dupe.Handle, "Dupe"); + Assert.That (dupe, Is.Not.Null, "Dupe"); + Assert.That (dupe.Handle, Is.Not.EqualTo (IntPtr.Zero), "Dupe"); } } } diff --git a/tests/monotouch-test/Metal/MTLComputePassSampleBufferAttachmentDescriptorTest.cs b/tests/monotouch-test/Metal/MTLComputePassSampleBufferAttachmentDescriptorTest.cs index 494674003333..28f3bdeea145 100644 --- a/tests/monotouch-test/Metal/MTLComputePassSampleBufferAttachmentDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLComputePassSampleBufferAttachmentDescriptorTest.cs @@ -47,7 +47,7 @@ public void StartOfEncoderSampleIndexTest () Assert.DoesNotThrow (() => { objIndex = descriptor.StartOfEncoderSampleIndex; }, "Getter"); - Assert.AreEqual (newIndex, objIndex, "Value"); + Assert.That (objIndex, Is.EqualTo (newIndex), "Value"); } [Test] @@ -62,7 +62,7 @@ public void EndOfEncoderSampleIndexTest () Assert.DoesNotThrow (() => { objIndex = descriptor.EndOfEncoderSampleIndex; }, "Getter"); - Assert.AreEqual (newIndex, objIndex, "Value"); + Assert.That (objIndex, Is.EqualTo (newIndex), "Value"); } } diff --git a/tests/monotouch-test/Metal/MTLCounterSampleBufferDescriptorTest.cs b/tests/monotouch-test/Metal/MTLCounterSampleBufferDescriptorTest.cs index 058bb229b4cb..2f4ba7fea2d4 100644 --- a/tests/monotouch-test/Metal/MTLCounterSampleBufferDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLCounterSampleBufferDescriptorTest.cs @@ -46,7 +46,7 @@ public void LabelTest () Assert.DoesNotThrow (() => { objLabel = descriptor.Label; }, "Getter"); - Assert.AreEqual (newLabel, objLabel, "Label"); + Assert.That (objLabel, Is.EqualTo (newLabel), "Label"); } [Test] @@ -60,7 +60,7 @@ public void StorageModeTest () Assert.DoesNotThrow (() => { objMode = descriptor.StorageMode; }, "Getter"); - Assert.AreEqual (newMode, objMode, "Mode"); + Assert.That (objMode, Is.EqualTo (newMode), "Mode"); } [Test] @@ -75,7 +75,7 @@ public void SampleCountTest () Assert.DoesNotThrow (() => { objCount = descriptor.SampleCount; }, "Getter"); - Assert.AreEqual (newCount, objCount, "Count"); + Assert.That (objCount, Is.EqualTo (newCount), "Count"); } } } diff --git a/tests/monotouch-test/Metal/MTLDeviceTests.cs b/tests/monotouch-test/Metal/MTLDeviceTests.cs index f86a3ec056e4..2a6a38b51134 100644 --- a/tests/monotouch-test/Metal/MTLDeviceTests.cs +++ b/tests/monotouch-test/Metal/MTLDeviceTests.cs @@ -26,7 +26,7 @@ public void GetAllDevicesTest () // It's possible to run on a system that does not support metal, // in which case we'll get an empty array of devices. - Assert.IsNotNull (devices, "MTLDevices.GetAllDevices not null"); + Assert.That (devices, Is.Not.Null, "MTLDevices.GetAllDevices not null"); } #if __MACOS__ @@ -37,7 +37,7 @@ public void GetAllDevicesTestOutObserver () // It's possible to run on a system that does not support metal, // in which case we'll get an empty array of devices. - Assert.IsNotNull (devices, "MTLDevices.GetAllDevices not null"); + Assert.That (devices, Is.Not.Null, "MTLDevices.GetAllDevices not null"); MTLDevice.RemoveObserver (observer); } @@ -113,13 +113,13 @@ public void ReturnReleaseTest () var sa = device.GetHeapTextureSizeAndAlign (txt); hd.Size = sa.Size; using (var heap = device.CreateHeap (hd)) { - Assert.IsNotNull (heap, $"NonNullHeap"); + Assert.That (heap, Is.Not.Null, $"NonNullHeap"); } } } using (var queue = device.CreateCommandQueue ()) { - Assert.IsNotNull (queue, "Queue: NonNull 1"); + Assert.That (queue, Is.Not.Null, "Queue: NonNull 1"); } #if __MACOS__ @@ -127,33 +127,33 @@ public void ReturnReleaseTest () using (var descriptor = MTLTextureDescriptor.CreateTexture2DDescriptor (MTLPixelFormat.RGBA8Unorm, 64, 64, false)) { descriptor.StorageMode = MTLStorageMode.Private; using (var texture = device.CreateSharedTexture (descriptor)) { - Assert.IsNotNull (texture, "CreateSharedTexture (MTLTextureDescriptor): NonNull"); + Assert.That (texture, Is.Not.Null, "CreateSharedTexture (MTLTextureDescriptor): NonNull"); using (var handle = texture.CreateSharedTextureHandle ()) using (var shared = device.CreateSharedTexture (handle)) - Assert.IsNotNull (texture, "CreateSharedTexture (MTLSharedTextureHandle): NonNull"); + Assert.That (texture, Is.Not.Null, "CreateSharedTexture (MTLSharedTextureHandle): NonNull"); } } } #endif using (var queue = device.CreateCommandQueue (10)) { - Assert.IsNotNull (queue, "Queue: NonNull 2"); + Assert.That (queue, Is.Not.Null, "Queue: NonNull 2"); } using (var buffer = device.CreateBuffer (1024, MTLResourceOptions.CpuCacheModeDefault)) { - Assert.IsNotNull (buffer, "CreateBuffer: NonNull 1"); + Assert.That (buffer, Is.Not.Null, "CreateBuffer: NonNull 1"); } buffer_mem = AllocPageAligned (1, out buffer_length); using (var buffer = device.CreateBuffer (buffer_mem, (nuint) buffer_length, MTLResourceOptions.CpuCacheModeDefault)) { - Assert.IsNotNull (buffer, "CreateBuffer: NonNull 2"); + Assert.That (buffer, Is.Not.Null, "CreateBuffer: NonNull 2"); } FreePageAligned (buffer_mem, buffer_length); buffer_bytes = new byte [getpagesize ()]; using (var buffer = device.CreateBuffer (buffer_bytes, MTLResourceOptions.CpuCacheModeDefault)) { - Assert.IsNotNull (buffer, "CreateBuffer: NonNull 3"); + Assert.That (buffer, Is.Not.Null, "CreateBuffer: NonNull 3"); } buffer_mem = AllocPageAligned (1, out buffer_length); @@ -164,18 +164,18 @@ public void ReturnReleaseTest () var resourceOptions7 = MTLResourceOptions.CpuCacheModeDefault; #endif using (var buffer = device.CreateBufferNoCopy (buffer_mem, (nuint) buffer_length, resourceOptions7, (pointer, length) => { FreePageAligned (pointer, (int) length); freed = true; })) { - Assert.IsNotNull (buffer, "CreateBufferNoCopy: NonNull 1"); + Assert.That (buffer, Is.Not.Null, "CreateBufferNoCopy: NonNull 1"); } - Assert.IsTrue (freed, "CreateBufferNoCopy: Freed 1"); + Assert.That (freed, Is.True, "CreateBufferNoCopy: Freed 1"); using (var descriptor = new MTLDepthStencilDescriptor ()) using (var dss = device.CreateDepthStencilState (descriptor)) { - Assert.IsNotNull (dss, "CreateDepthStencilState: NonNull 1"); + Assert.That (dss, Is.Not.Null, "CreateDepthStencilState: NonNull 1"); } using (var descriptor = MTLTextureDescriptor.CreateTexture2DDescriptor (MTLPixelFormat.RGBA8Unorm, 64, 64, false)) { using (var texture = device.CreateTexture (descriptor)) - Assert.NotNull (texture, "CreateTexture: NonNull 1"); + Assert.That (texture, Is.Not.Null, "CreateTexture: NonNull 1"); using (var surface = new IOSurface.IOSurface (new IOSurface.IOSurfaceOptions { Width = 64, @@ -183,44 +183,44 @@ public void ReturnReleaseTest () BytesPerElement = 4, })) { using (var texture = device.CreateTexture (descriptor, surface, 0)) - Assert.NotNull (texture, "CreateTexture: NonNull 2"); + Assert.That (texture, Is.Not.Null, "CreateTexture: NonNull 2"); } } using (var descriptor = new MTLSamplerDescriptor ()) using (var sampler = device.CreateSamplerState (descriptor)) - Assert.IsNotNull (sampler, "CreateSamplerState: NonNull 1"); + Assert.That (sampler, Is.Not.Null, "CreateSamplerState: NonNull 1"); using (var library = device.CreateDefaultLibrary ()) - Assert.IsNotNull (library, "CreateDefaultLibrary: NonNull 1"); + Assert.That (library, Is.Not.Null, "CreateDefaultLibrary: NonNull 1"); using (var library = device.CreateLibrary (metallib_path, out var error)) { - Assert.IsNotNull (library, "CreateLibrary: NonNull 1"); - Assert.IsNull (error, "CreateLibrary: NonNull error 1"); + Assert.That (library, Is.Not.Null, "CreateLibrary: NonNull 1"); + Assert.That (error, Is.Null, "CreateLibrary: NonNull error 1"); } using (var data = DispatchData.FromByteBuffer (File.ReadAllBytes (metallib_path))) using (var library = device.CreateLibrary (data, out var error)) { - Assert.IsNotNull (library, "CreateLibrary: NonNull 2"); - Assert.IsNull (error, "CreateLibrary: NonNull error 2"); + Assert.That (library, Is.Not.Null, "CreateLibrary: NonNull 2"); + Assert.That (error, Is.Null, "CreateLibrary: NonNull error 2"); } using (var compile_options = new MTLCompileOptions ()) using (var library = device.CreateLibrary (metal_code, compile_options, out var error)) { - Assert.IsNotNull (library, "CreateLibrary: NonNull 3"); - Assert.IsNull (error, "CreateLibrary: NonNull error 3"); + Assert.That (library, Is.Not.Null, "CreateLibrary: NonNull 3"); + Assert.That (error, Is.Null, "CreateLibrary: NonNull error 3"); } using (var compile_options = new MTLCompileOptions ()) { device.CreateLibrary (metal_code, compile_options, (library, error) => { - Assert.IsNotNull (library, "CreateLibrary: NonNull 4"); - Assert.IsNull (error, "CreateLibrary: NonNull error 4"); + Assert.That (library, Is.Not.Null, "CreateLibrary: NonNull 4"); + Assert.That (error, Is.Null, "CreateLibrary: NonNull error 4"); }); } using (var library = device.CreateDefaultLibrary (NSBundle.MainBundle, out var error)) { - Assert.IsNotNull (library, "CreateDefaultLibrary: NonNull 2"); - Assert.IsNull (error, "CreateDefaultLibrary: NonNull error 2"); + Assert.That (library, Is.Not.Null, "CreateDefaultLibrary: NonNull 2"); + Assert.That (error, Is.Null, "CreateDefaultLibrary: NonNull error 2"); } using (var descriptor = new MTLRenderPipelineDescriptor ()) @@ -229,8 +229,8 @@ public void ReturnReleaseTest () descriptor.VertexFunction = func; descriptor.ColorAttachments [0].PixelFormat = MTLPixelFormat.BGRA8Unorm_sRGB; using (var rps = device.CreateRenderPipelineState (descriptor, out var error)) { - Assert.IsNotNull (rps, "CreateRenderPipelineState: NonNull 1"); - Assert.IsNull (error, "CreateRenderPipelineState: NonNull error 1"); + Assert.That (rps, Is.Not.Null, "CreateRenderPipelineState: NonNull 1"); + Assert.That (error, Is.Null, "CreateRenderPipelineState: NonNull error 1"); } } @@ -240,25 +240,25 @@ public void ReturnReleaseTest () descriptor.VertexFunction = func; descriptor.ColorAttachments [0].PixelFormat = MTLPixelFormat.BGRA8Unorm_sRGB; using (var rps = device.CreateRenderPipelineState (descriptor, MTLPipelineOption.BufferTypeInfo, out var reflection, out var error)) { - Assert.IsNotNull (rps, "CreateRenderPipelineState: NonNull 2"); - Assert.IsNull (error, "CreateRenderPipelineState: NonNull error 2"); - Assert.IsNotNull (reflection, "CreateRenderPipelineState: NonNull reflection 2"); + Assert.That (rps, Is.Not.Null, "CreateRenderPipelineState: NonNull 2"); + Assert.That (error, Is.Null, "CreateRenderPipelineState: NonNull error 2"); + Assert.That (reflection, Is.Not.Null, "CreateRenderPipelineState: NonNull reflection 2"); } } using (var library = device.CreateDefaultLibrary ()) using (var func = library.CreateFunction ("grayscaleKernel")) using (var cps = device.CreateComputePipelineState (func, MTLPipelineOption.ArgumentInfo, out var reflection, out var error)) { - Assert.IsNotNull (cps, "CreateComputePipelineState: NonNull 1"); - Assert.IsNull (error, "CreateComputePipelineState: NonNull error 1"); - Assert.IsNotNull (reflection, "CreateComputePipelineState: NonNull reflection 1"); + Assert.That (cps, Is.Not.Null, "CreateComputePipelineState: NonNull 1"); + Assert.That (error, Is.Null, "CreateComputePipelineState: NonNull error 1"); + Assert.That (reflection, Is.Not.Null, "CreateComputePipelineState: NonNull reflection 1"); } using (var library = device.CreateDefaultLibrary ()) using (var func = library.CreateFunction ("grayscaleKernel")) using (var cps = device.CreateComputePipelineState (func, out var error)) { - Assert.IsNotNull (cps, "CreateComputePipelineState: NonNull 2"); - Assert.IsNull (error, "CreateComputePipelineState: NonNull error 2"); + Assert.That (cps, Is.Not.Null, "CreateComputePipelineState: NonNull 2"); + Assert.That (error, Is.Null, "CreateComputePipelineState: NonNull error 2"); } using (var descriptor = new MTLComputePipelineDescriptor ()) @@ -266,26 +266,26 @@ public void ReturnReleaseTest () using (var func = library.CreateFunction ("grayscaleKernel")) { descriptor.ComputeFunction = func; using (var cps = device.CreateComputePipelineState (descriptor, MTLPipelineOption.BufferTypeInfo, out var reflection, out var error)) { - Assert.IsNotNull (cps, "CreateComputePipelineState: NonNull 3"); - Assert.IsNull (error, "CreateComputePipelineState: NonNull error 3"); - Assert.IsNotNull (reflection, "CreateComputePipelineState: NonNull reflection 3"); + Assert.That (cps, Is.Not.Null, "CreateComputePipelineState: NonNull 3"); + Assert.That (error, Is.Null, "CreateComputePipelineState: NonNull error 3"); + Assert.That (reflection, Is.Not.Null, "CreateComputePipelineState: NonNull reflection 3"); } } using (var fence = device.CreateFence ()) { - Assert.IsNotNull (fence, "CreateFence 1: NonNull"); + Assert.That (fence, Is.Not.Null, "CreateFence 1: NonNull"); } var url = "file://" + metallib_path; url = url.Replace (" ", "%20"); // url encode! using (var library = device.CreateLibrary (new NSUrl (url), out var error)) { // Looks like creating a library with a url always fails: https://forums.developer.apple.com/thread/110416 - Assert.IsNotNull (library, "CreateLibrary (NSUrl, NSError): Null"); - Assert.IsNull (error, "CreateLibrary (NSUrl, NSError): NonNull error"); + Assert.That (library, Is.Not.Null, "CreateLibrary (NSUrl, NSError): Null"); + Assert.That (error, Is.Null, "CreateLibrary (NSUrl, NSError): NonNull error"); } using (var library = device.CreateArgumentEncoder (new MTLArgumentDescriptor [] { new MTLArgumentDescriptor () { DataType = MTLDataType.Int } })) { - Assert.IsNotNull (library, "CreateArgumentEncoder (MTLArgumentDescriptor[]): NonNull"); + Assert.That (library, Is.Not.Null, "CreateArgumentEncoder (MTLArgumentDescriptor[]): NonNull"); } // Apple's charts say that "Indirect command buffers" are supported with MTLGpuFamilyCommon2 @@ -297,22 +297,22 @@ public void ReturnReleaseTest () if (supportsIndirectCommandBuffers) { using (var descriptor = new MTLIndirectCommandBufferDescriptor ()) { using (var library = device.CreateIndirectCommandBuffer (descriptor, 1, MTLResourceOptions.CpuCacheModeDefault)) { - Assert.IsNotNull (library, "CreateIndirectCommandBuffer: NonNull"); + Assert.That (library, Is.Not.Null, "CreateIndirectCommandBuffer: NonNull"); } } using (var evt = device.CreateEvent ()) { - Assert.IsNotNull (evt, "CreateEvent: NonNull"); + Assert.That (evt, Is.Not.Null, "CreateEvent: NonNull"); } using (var evt = device.CreateSharedEvent ()) { - Assert.IsNotNull (evt, "CreateSharedEvent: NonNull"); + Assert.That (evt, Is.Not.Null, "CreateSharedEvent: NonNull"); } using (var evt1 = device.CreateSharedEvent ()) using (var evt_handle = evt1.CreateSharedEventHandle ()) using (var evt = device.CreateSharedEvent (evt_handle)) { - Assert.IsNotNull (evt, "CreateSharedEvent (MTLSharedEventHandle): NonNull"); + Assert.That (evt, Is.Not.Null, "CreateSharedEvent (MTLSharedEventHandle): NonNull"); } } @@ -322,50 +322,50 @@ public void ReturnReleaseTest () descriptor.VertexFunction = func; descriptor.ColorAttachments [0].PixelFormat = MTLPixelFormat.BGRA8Unorm_sRGB; using (var rps = device.CreateRenderPipelineState (descriptor, MTLPipelineOption.ArgumentInfo, out var reflection, out var error)) { - Assert.IsNotNull (rps, "CreateRenderPipelineState (MTLTileRenderPipelineDescriptor, MTLPipelineOption, MTLRenderPipelineReflection, NSError): NonNull"); - Assert.IsNull (error, "CreateRenderPipelineState (MTLTileRenderPipelineDescriptor, MTLPipelineOption, MTLRenderPipelineReflection, NSError: NonNull error"); - Assert.IsNotNull (reflection, "CreateRenderPipelineState (MTLTileRenderPipelineDescriptor, MTLPipelineOption, MTLRenderPipelineReflection, NSError): NonNull reflection"); + Assert.That (rps, Is.Not.Null, "CreateRenderPipelineState (MTLTileRenderPipelineDescriptor, MTLPipelineOption, MTLRenderPipelineReflection, NSError): NonNull"); + Assert.That (error, Is.Null, "CreateRenderPipelineState (MTLTileRenderPipelineDescriptor, MTLPipelineOption, MTLRenderPipelineReflection, NSError: NonNull error"); + Assert.That (reflection, Is.Not.Null, "CreateRenderPipelineState (MTLTileRenderPipelineDescriptor, MTLPipelineOption, MTLRenderPipelineReflection, NSError): NonNull reflection"); } } using (var buffer = device.CreateBuffer (1024, MTLResourceOptions.CpuCacheModeDefault)) using (var descriptor = new MTLTextureDescriptor ()) using (var texture = buffer.CreateTexture (descriptor, 0, 256)) { - Assert.IsNotNull (buffer, "MTLBuffer.CreateTexture (MTLTextureDescriptor, nuint, nuint): NonNull"); + Assert.That (buffer, Is.Not.Null, "MTLBuffer.CreateTexture (MTLTextureDescriptor, nuint, nuint): NonNull"); } using (var descriptor = MTLTextureDescriptor.CreateTexture2DDescriptor (MTLPixelFormat.RGBA8Unorm, 64, 64, false)) using (var texture = device.CreateTexture (descriptor)) { using (var view = texture.CreateTextureView (MTLPixelFormat.RGBA8Unorm)) { - Assert.IsNotNull (view, "MTLTexture.CreateTextureView (MTLPixelFormat): nonnull"); + Assert.That (view, Is.Not.Null, "MTLTexture.CreateTextureView (MTLPixelFormat): nonnull"); } using (var view = texture.CreateTextureView (MTLPixelFormat.RGBA8Unorm, MTLTextureType.k2D, new NSRange (0, 1), new NSRange (0, 1))) { - Assert.IsNotNull (view, "MTLTexture.CreateTextureView (MTLPixelFormat, MTLTextureType, NSRange, NSRange): nonnull"); + Assert.That (view, Is.Not.Null, "MTLTexture.CreateTextureView (MTLPixelFormat, MTLTextureType, NSRange, NSRange): nonnull"); } } using (var library = device.CreateLibrary (fragmentshader_path, out var error)) { - Assert.IsNull (error, "MTLFunction.CreateArgumentEncoder: library creation failure"); + Assert.That (error, Is.Null, "MTLFunction.CreateArgumentEncoder: library creation failure"); using (var func = library.CreateFunction ("fragmentShader2")) { using (var enc = func.CreateArgumentEncoder (0)) { - Assert.IsNotNull (enc, "MTLFunction.CreateArgumentEncoder (nuint): NonNull"); + Assert.That (enc, Is.Not.Null, "MTLFunction.CreateArgumentEncoder (nuint): NonNull"); } using (var enc = func.CreateArgumentEncoder (0, out var reflection)) { - Assert.IsNotNull (enc, "MTLFunction.CreateArgumentEncoder (nuint, MTLArgument): NonNull"); - Assert.IsNotNull (reflection, "MTLFunction.CreateArgumentEncoder (nuint, MTLArgument): NonNull reflection"); + Assert.That (enc, Is.Not.Null, "MTLFunction.CreateArgumentEncoder (nuint, MTLArgument): NonNull"); + Assert.That (reflection, Is.Not.Null, "MTLFunction.CreateArgumentEncoder (nuint, MTLArgument): NonNull reflection"); } } } using (var library = device.CreateDefaultLibrary ()) { using (var func = library.CreateFunction ("grayscaleKernel")) { - Assert.IsNotNull (func, "CreateFunction (string): nonnull"); + Assert.That (func, Is.Not.Null, "CreateFunction (string): nonnull"); } if (TestRuntime.CheckXcodeVersion (9, 0)) { // MTLFunctionConstantValues didn't have a default ctor until Xcode 9. using (var constants = new MTLFunctionConstantValues ()) using (var func = library.CreateFunction ("grayscaleKernel", constants, out var error)) { - Assert.IsNotNull (func, "CreateFunction (string, MTLFunctionConstantValues, NSError): nonnull"); - Assert.IsNull (error, "CreateFunction (string, MTLFunctionConstantValues, NSError): null error"); + Assert.That (func, Is.Not.Null, "CreateFunction (string, MTLFunctionConstantValues, NSError): nonnull"); + Assert.That (error, Is.Null, "CreateFunction (string, MTLFunctionConstantValues, NSError): null error"); } } } @@ -378,7 +378,7 @@ public void ReturnReleaseTest () hd.Size = sa.Size; using (var heap = device.CreateHeap (hd)) using (var buffer = heap.CreateBuffer (1024, MTLResourceOptions.StorageModePrivate)) { - Assert.IsNotNull (buffer, "MTLHeap.CreateBuffer (nuint, MTLResourceOptions): nonnull"); + Assert.That (buffer, Is.Not.Null, "MTLHeap.CreateBuffer (nuint, MTLResourceOptions): nonnull"); } } } @@ -399,25 +399,25 @@ public void ReturnReleaseTest () txt.StorageMode = MTLStorageMode.Private; #endif using (var texture = heap.CreateTexture (txt)) { - Assert.IsNotNull (texture, "MTLHeap.CreateTexture (MTLTextureDescriptor): nonnull"); + Assert.That (texture, Is.Not.Null, "MTLHeap.CreateTexture (MTLTextureDescriptor): nonnull"); } } } } using (var scope = MTLCaptureManager.Shared.CreateNewCaptureScope (device)) { - Assert.IsNotNull (scope, "MTLCaptureManager.CreateNewCaptureScope (MTLDevice): nonnull"); + Assert.That (scope, Is.Not.Null, "MTLCaptureManager.CreateNewCaptureScope (MTLDevice): nonnull"); } using (var queue = device.CreateCommandQueue ()) using (var scope = MTLCaptureManager.Shared.CreateNewCaptureScope (queue)) { - Assert.IsNotNull (scope, "MTLCaptureManager.CreateNewCaptureScope (MTLCommandQueue): nonnull"); + Assert.That (scope, Is.Not.Null, "MTLCaptureManager.CreateNewCaptureScope (MTLCommandQueue): nonnull"); } TestRuntime.AssertXcodeVersion (10, 0); using (var evt = device.CreateSharedEvent ()) using (var shared = evt.CreateSharedEventHandle ()) { - Assert.IsNotNull (shared, "MTLSharedEvent.CreateSharedEvent: NonNull"); + Assert.That (shared, Is.Not.Null, "MTLSharedEvent.CreateSharedEvent: NonNull"); } } } diff --git a/tests/monotouch-test/Metal/MTLFunctionConstantTest.cs b/tests/monotouch-test/Metal/MTLFunctionConstantTest.cs index 172198a08c57..9dcfdc867c76 100644 --- a/tests/monotouch-test/Metal/MTLFunctionConstantTest.cs +++ b/tests/monotouch-test/Metal/MTLFunctionConstantTest.cs @@ -17,28 +17,28 @@ public void Setup () public void GetNameTest () { var constant = new MTLFunctionConstant (); - Assert.IsNull (constant.Name); // defualt value is null + Assert.That (constant.Name, Is.Null); // defualt value is null } [Test] public void GetTypeTest () { var constant = new MTLFunctionConstant (); - Assert.AreEqual (MTLDataType.None, constant.Type); // default value is none + Assert.That (constant.Type, Is.EqualTo (MTLDataType.None)); // default value is none } [Test] public void GetIndexTest () { var constant = new MTLFunctionConstant (); - Assert.AreEqual ((nuint) 0, constant.Index, $"Index is {constant.Index}"); // default value is 0 + Assert.That (constant.Index, Is.EqualTo ((nuint) 0), $"Index is {constant.Index}"); // default value is 0 } [Test] public void GetIsRequiredTest () { var constant = new MTLFunctionConstant (); - Assert.False (constant.IsRequired); // defualt value is false + Assert.That (constant.IsRequired, Is.False); // defualt value is false } } } diff --git a/tests/monotouch-test/Metal/MTLIOCompressionContextTest.cs b/tests/monotouch-test/Metal/MTLIOCompressionContextTest.cs index eb71a656f7b9..17e5f0f84223 100644 --- a/tests/monotouch-test/Metal/MTLIOCompressionContextTest.cs +++ b/tests/monotouch-test/Metal/MTLIOCompressionContextTest.cs @@ -18,7 +18,7 @@ public void SetUp () public void DefaultChunkSize () { TestRuntime.AssertNotSimulator (); // metal api not supported on the sim - Assert.AreNotEqual (-1, MTLIOCompressionContext.DefaultChunkSize); + Assert.That (MTLIOCompressionContext.DefaultChunkSize, Is.Not.EqualTo (-1)); } [Test] @@ -30,7 +30,7 @@ public void CreateAndFlushTest () // create and flush, test should simple pass, no need to asserts var compressIO = MTLIOCompressionContext.Create (outputPath, MTLIOCompressionMethod.Lzfse, MTLIOCompressionContext.DefaultChunkSize); - Assert.NotNull (compressIO, "Null compress IO"); + Assert.That (compressIO, Is.Not.Null, "Null compress IO"); // add data var data = Enumerable.Repeat ((byte) 0x20, 20).ToArray (); compressIO!.AppendData (data); diff --git a/tests/monotouch-test/Metal/MTLIndirectCommandBufferDescriptorTest.cs b/tests/monotouch-test/Metal/MTLIndirectCommandBufferDescriptorTest.cs index c063623d62a3..c9f110af3249 100644 --- a/tests/monotouch-test/Metal/MTLIndirectCommandBufferDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLIndirectCommandBufferDescriptorTest.cs @@ -27,7 +27,7 @@ public void TearDown () public void GetSetCommandTypesTest () { descriptor.CommandTypes = MTLIndirectCommandType.Draw; - Assert.AreEqual (MTLIndirectCommandType.Draw, descriptor.CommandTypes); + Assert.That (descriptor.CommandTypes, Is.EqualTo (MTLIndirectCommandType.Draw)); } #if MONOMAC @@ -35,7 +35,7 @@ public void GetSetCommandTypesTest () public void GetSetInheritPipelineStateTest () { descriptor.InheritPipelineState = true; - Assert.AreEqual (true, descriptor.InheritPipelineState); + Assert.That (descriptor.InheritPipelineState, Is.EqualTo (true)); } #endif @@ -43,21 +43,21 @@ public void GetSetInheritPipelineStateTest () public void GetSetInheritBuffersTest () { descriptor.InheritBuffers = true; - Assert.AreEqual (true, descriptor.InheritBuffers); + Assert.That (descriptor.InheritBuffers, Is.EqualTo (true)); } [Test] public void GetSetMaxVertexBufferBindCountTest () { descriptor.MaxVertexBufferBindCount = 1; - Assert.AreEqual ((nuint) 1, descriptor.MaxVertexBufferBindCount); + Assert.That (descriptor.MaxVertexBufferBindCount, Is.EqualTo ((nuint) 1)); } [Test] public void GetSetMaxFragmentBufferBindCountTest () { descriptor.MaxFragmentBufferBindCount = 1; - Assert.AreEqual ((nuint) 1, descriptor.MaxFragmentBufferBindCount); + Assert.That (descriptor.MaxFragmentBufferBindCount, Is.EqualTo ((nuint) 1)); } } } diff --git a/tests/monotouch-test/Metal/MTLIntersectionFunctionTableDescriptorTest.cs b/tests/monotouch-test/Metal/MTLIntersectionFunctionTableDescriptorTest.cs index a0b33b019fe4..7781b25a79d4 100644 --- a/tests/monotouch-test/Metal/MTLIntersectionFunctionTableDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLIntersectionFunctionTableDescriptorTest.cs @@ -29,7 +29,7 @@ public void FunctionCountTest () Assert.DoesNotThrow (() => { objCount = descriptor.FunctionCount; }, "Getter"); - Assert.AreEqual (newCount, objCount, "Count"); + Assert.That (objCount, Is.EqualTo (newCount), "Count"); } } } diff --git a/tests/monotouch-test/Metal/MTLPipelineBufferDescriptorTests.cs b/tests/monotouch-test/Metal/MTLPipelineBufferDescriptorTests.cs index 344212874705..affee2bd7fa9 100644 --- a/tests/monotouch-test/Metal/MTLPipelineBufferDescriptorTests.cs +++ b/tests/monotouch-test/Metal/MTLPipelineBufferDescriptorTests.cs @@ -27,7 +27,7 @@ public void TearDown () public void GetSetMutabilityTest () { descriptor.Mutability = MTLMutability.Immutable; - Assert.AreEqual (MTLMutability.Immutable, descriptor.Mutability); + Assert.That (descriptor.Mutability, Is.EqualTo (MTLMutability.Immutable)); } } } diff --git a/tests/monotouch-test/Metal/MTLPointerTypeTests.cs b/tests/monotouch-test/Metal/MTLPointerTypeTests.cs index f169c7d9df22..ffec3dd40777 100644 --- a/tests/monotouch-test/Metal/MTLPointerTypeTests.cs +++ b/tests/monotouch-test/Metal/MTLPointerTypeTests.cs @@ -26,31 +26,31 @@ public void TearDown () [Test] public void GetAccessTest () { - Assert.AreEqual (MTLArgumentAccess.ReadOnly, ptrType.Access); + Assert.That (ptrType.Access, Is.EqualTo (MTLArgumentAccess.ReadOnly)); } [Test] public void GetAlignmentTest () { - Assert.AreEqual ((nuint) 0, ptrType.Alignment); + Assert.That (ptrType.Alignment, Is.EqualTo ((nuint) 0)); } [Test] public void GetDataSizeTest () { - Assert.AreEqual ((nuint) 0, ptrType.DataSize); + Assert.That (ptrType.DataSize, Is.EqualTo ((nuint) 0)); } [Test] public void GetElementIsArgumentBufferTest () { - Assert.False (ptrType.ElementIsArgumentBuffer); + Assert.That (ptrType.ElementIsArgumentBuffer, Is.False); } [Test] public void GetElementTypeTest () { - Assert.AreEqual (MTLDataType.None, ptrType.ElementType); + Assert.That (ptrType.ElementType, Is.EqualTo (MTLDataType.None)); } } } diff --git a/tests/monotouch-test/Metal/MTLRasterizationRateLayerDescriptorTest.cs b/tests/monotouch-test/Metal/MTLRasterizationRateLayerDescriptorTest.cs index a61662be522e..87f041b58c5e 100644 --- a/tests/monotouch-test/Metal/MTLRasterizationRateLayerDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLRasterizationRateLayerDescriptorTest.cs @@ -54,9 +54,9 @@ public void Create_1 () var horizontal = new float [] { 1, 2, 3 }; var vertical = new float [] { 5, 6, 7, 8 }; using var obj = MTLRasterizationRateLayerDescriptor.Create (new MTLSize (horizontal.Length, vertical.Length, 42), horizontal, vertical); - Assert.AreEqual ((nint) horizontal.Length, obj.SampleCount.Width, "Width"); - Assert.AreEqual ((nint) vertical.Length, obj.SampleCount.Height, "Height"); - Assert.AreEqual ((nint) 0, obj.SampleCount.Depth, "Depth"); + Assert.That (obj.SampleCount.Width, Is.EqualTo ((nint) horizontal.Length), "Width"); + Assert.That (obj.SampleCount.Height, Is.EqualTo ((nint) vertical.Length), "Height"); + Assert.That (obj.SampleCount.Depth, Is.EqualTo ((nint) 0), "Depth"); Assert.That (obj.HorizontalSampleStorage, Is.EqualTo (horizontal), "HorizontalSampleStorage"); Assert.That (obj.VerticalSampleStorage, Is.EqualTo (vertical), "VerticalSampleStorage"); @@ -72,9 +72,9 @@ public void Create_2 () var horizontal = new float [] { 1, 2, 3 }; var vertical = new float [] { 5, 6, 7, 8 }; using var obj = MTLRasterizationRateLayerDescriptor.Create (horizontal, vertical); - Assert.AreEqual ((nint) horizontal.Length, obj.SampleCount.Width, "Width"); - Assert.AreEqual ((nint) vertical.Length, obj.SampleCount.Height, "Height"); - Assert.AreEqual ((nint) 0, obj.SampleCount.Depth, "Depth"); + Assert.That (obj.SampleCount.Width, Is.EqualTo ((nint) horizontal.Length), "Width"); + Assert.That (obj.SampleCount.Height, Is.EqualTo ((nint) vertical.Length), "Height"); + Assert.That (obj.SampleCount.Depth, Is.EqualTo ((nint) 0), "Depth"); Assert.That (obj.HorizontalSampleStorage, Is.EqualTo (horizontal), "HorizontalSampleStorage"); Assert.That (obj.VerticalSampleStorage, Is.EqualTo (vertical), "VerticalSampleStorage"); @@ -88,9 +88,9 @@ public void Ctor () var horizontal = new float [3]; var vertical = new float [4]; using var obj = new MTLRasterizationRateLayerDescriptor (new MTLSize (horizontal.Length, vertical.Length, 0)); - Assert.AreEqual ((nint) horizontal.Length, obj.SampleCount.Width, "Width"); - Assert.AreEqual ((nint) vertical.Length, obj.SampleCount.Height, "Height"); - Assert.AreEqual ((nint) 0, obj.SampleCount.Depth, "Depth"); + Assert.That (obj.SampleCount.Width, Is.EqualTo ((nint) horizontal.Length), "Width"); + Assert.That (obj.SampleCount.Height, Is.EqualTo ((nint) vertical.Length), "Height"); + Assert.That (obj.SampleCount.Depth, Is.EqualTo ((nint) 0), "Depth"); Assert.That (obj.HorizontalSampleStorage, Is.EqualTo (horizontal), "HorizontalSampleStorage"); Assert.That (obj.VerticalSampleStorage, Is.EqualTo (vertical), "VerticalSampleStorage"); } diff --git a/tests/monotouch-test/Metal/MTLRasterizationRateMapDescriptorTest.cs b/tests/monotouch-test/Metal/MTLRasterizationRateMapDescriptorTest.cs index b021a2d293d2..e1734778d09d 100644 --- a/tests/monotouch-test/Metal/MTLRasterizationRateMapDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLRasterizationRateMapDescriptorTest.cs @@ -27,7 +27,7 @@ public void TearDown () [Test] public void GetLayerTest () - => Assert.Null (descriptor.GetLayer (1)); + => Assert.That (descriptor.GetLayer (1), Is.Null); [Test] public void SetLayerTest () @@ -50,7 +50,7 @@ public void LabelTest () { string label = "my label"; Assert.DoesNotThrow (() => descriptor.Label = label, "Set label"); - Assert.AreEqual (label, descriptor.Label, "Get label"); + Assert.That (descriptor.Label, Is.EqualTo (label), "Get label"); } [Test] diff --git a/tests/monotouch-test/Metal/MTLRenderPassSampleBufferAttachmentDescriptorArrayTest.cs b/tests/monotouch-test/Metal/MTLRenderPassSampleBufferAttachmentDescriptorArrayTest.cs index 537ba2f546f1..e78937d81ffe 100644 --- a/tests/monotouch-test/Metal/MTLRenderPassSampleBufferAttachmentDescriptorArrayTest.cs +++ b/tests/monotouch-test/Metal/MTLRenderPassSampleBufferAttachmentDescriptorArrayTest.cs @@ -35,8 +35,8 @@ public void IndexerTest () Assert.DoesNotThrow (() => { dupe = array [0]; }); - Assert.IsNotNull (dupe, "Dupe"); - Assert.AreNotEqual (IntPtr.Zero, dupe.Handle, "Dupe"); + Assert.That (dupe, Is.Not.Null, "Dupe"); + Assert.That (dupe.Handle, Is.Not.EqualTo (IntPtr.Zero), "Dupe"); } } } diff --git a/tests/monotouch-test/Metal/MTLRenderPassSampleBufferAttachmentDescriptorTest.cs b/tests/monotouch-test/Metal/MTLRenderPassSampleBufferAttachmentDescriptorTest.cs index aab2b431f158..954e89386366 100644 --- a/tests/monotouch-test/Metal/MTLRenderPassSampleBufferAttachmentDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLRenderPassSampleBufferAttachmentDescriptorTest.cs @@ -47,7 +47,7 @@ public void StartOfVertexSampleIndexTest () Assert.DoesNotThrow (() => { objIndex = descriptor.StartOfVertexSampleIndex; }, "Getter"); - Assert.AreEqual (newIndex, objIndex, "Index"); + Assert.That (objIndex, Is.EqualTo (newIndex), "Index"); } [Test] @@ -62,7 +62,7 @@ public void EndOfVertexSampleIndexTest () Assert.DoesNotThrow (() => { objIndex = descriptor.EndOfVertexSampleIndex; }, "Getter"); - Assert.AreEqual (newIndex, objIndex, "Index"); + Assert.That (objIndex, Is.EqualTo (newIndex), "Index"); } [Test] @@ -77,7 +77,7 @@ public void StartOfFragmentSampleIndexTest () Assert.DoesNotThrow (() => { objIndex = descriptor.StartOfFragmentSampleIndex; }, "Getter"); - Assert.AreEqual (newIndex, objIndex, "Index"); + Assert.That (objIndex, Is.EqualTo (newIndex), "Index"); } [Test] @@ -92,7 +92,7 @@ public void EndOfFragmentSampleIndexTest () Assert.DoesNotThrow (() => { objIndex = descriptor.EndOfFragmentSampleIndex; }, "Getter"); - Assert.AreEqual (newIndex, objIndex, "Index"); + Assert.That (objIndex, Is.EqualTo (newIndex), "Index"); } } } diff --git a/tests/monotouch-test/Metal/MTLRenderPipelineDescriptorTest.cs b/tests/monotouch-test/Metal/MTLRenderPipelineDescriptorTest.cs index afc77f4fe416..a10e2d44e586 100644 --- a/tests/monotouch-test/Metal/MTLRenderPipelineDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLRenderPipelineDescriptorTest.cs @@ -29,7 +29,7 @@ public void LabelTest () Assert.DoesNotThrow (() => { descriptor.Label = label; }, "Set label"); - Assert.AreEqual (label, descriptor.Label, "Get label"); + Assert.That (descriptor.Label, Is.EqualTo (label), "Get label"); } [Test] diff --git a/tests/monotouch-test/Metal/MTLResidencySetTests.cs b/tests/monotouch-test/Metal/MTLResidencySetTests.cs index bd04944223b2..a74d3de74f59 100644 --- a/tests/monotouch-test/Metal/MTLResidencySetTests.cs +++ b/tests/monotouch-test/Metal/MTLResidencySetTests.cs @@ -28,18 +28,18 @@ public void AddOrRemoveAllocations () InitialCapacity = 3 }; using var residencySet = device.CreateResidencySet (residencySetDescriptor, out var error); - Assert.IsNull (error, "Error #1"); - Assert.IsNotNull (residencySet, "ResidencySet #1"); + Assert.That (error, Is.Null, "Error #1"); + Assert.That (residencySet, Is.Not.Null, "ResidencySet #1"); residencySet.AddAllocations (heap); - Assert.AreEqual (1, (int) residencySet.AllocationCount, "AllocationCount #1"); + Assert.That ((int) residencySet.AllocationCount, Is.EqualTo (1), "AllocationCount #1"); residencySet.RemoveAllocations (heap); - Assert.AreEqual (0, (int) residencySet.AllocationCount, "AllocationCount #2"); + Assert.That ((int) residencySet.AllocationCount, Is.EqualTo (0), "AllocationCount #2"); residencySet.AddAllocations (new IMTLAllocation [] { heap }); - Assert.AreEqual (1, (int) residencySet.AllocationCount, "AllocationCount #3"); + Assert.That ((int) residencySet.AllocationCount, Is.EqualTo (1), "AllocationCount #3"); residencySet.RemoveAllocations (new IMTLAllocation [] { heap }); - Assert.AreEqual (0, (int) residencySet.AllocationCount, "AllocationCount #4"); + Assert.That ((int) residencySet.AllocationCount, Is.EqualTo (0), "AllocationCount #4"); } } } diff --git a/tests/monotouch-test/Metal/MTLResourceStatePassSampleBufferAttachmentDescriptorArrayTest.cs b/tests/monotouch-test/Metal/MTLResourceStatePassSampleBufferAttachmentDescriptorArrayTest.cs index 21cbdcf79093..b6c1050eb3ee 100644 --- a/tests/monotouch-test/Metal/MTLResourceStatePassSampleBufferAttachmentDescriptorArrayTest.cs +++ b/tests/monotouch-test/Metal/MTLResourceStatePassSampleBufferAttachmentDescriptorArrayTest.cs @@ -36,8 +36,8 @@ public void IndexerTest () Assert.DoesNotThrow (() => { dupe = array [0]; }); - Assert.IsNotNull (dupe, "Dupe"); - Assert.AreNotEqual (IntPtr.Zero, dupe.Handle, "Dupe"); + Assert.That (dupe, Is.Not.Null, "Dupe"); + Assert.That (dupe.Handle, Is.Not.EqualTo (IntPtr.Zero), "Dupe"); } } } diff --git a/tests/monotouch-test/Metal/MTLResourceStatePassSampleBufferAttachmentDescriptorTest.cs b/tests/monotouch-test/Metal/MTLResourceStatePassSampleBufferAttachmentDescriptorTest.cs index 0c7f8dae5b74..212a594ba5c3 100644 --- a/tests/monotouch-test/Metal/MTLResourceStatePassSampleBufferAttachmentDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLResourceStatePassSampleBufferAttachmentDescriptorTest.cs @@ -49,7 +49,7 @@ public void StartOfEncoderSampleIndexTest () Assert.DoesNotThrow (() => { objIndex = descriptor.StartOfEncoderSampleIndex; }, "Getter"); - Assert.AreEqual (newIndex, objIndex, "Value"); + Assert.That (objIndex, Is.EqualTo (newIndex), "Value"); } [Test] @@ -64,7 +64,7 @@ public void EndOfEncoderSampleIndexTest () Assert.DoesNotThrow (() => { objIndex = descriptor.EndOfEncoderSampleIndex; }, "Getter"); - Assert.AreEqual (newIndex, objIndex, "Value"); + Assert.That (objIndex, Is.EqualTo (newIndex), "Value"); } } } diff --git a/tests/monotouch-test/Metal/MTLSharedEventListenerTest.cs b/tests/monotouch-test/Metal/MTLSharedEventListenerTest.cs index c7fdaff66fc6..2a4b123b5c5b 100644 --- a/tests/monotouch-test/Metal/MTLSharedEventListenerTest.cs +++ b/tests/monotouch-test/Metal/MTLSharedEventListenerTest.cs @@ -32,7 +32,7 @@ public void TearDown () [Test] public void GetSetCommandTypesTest () { - Assert.AreEqual (queue, listener.DispatchQueue); + Assert.That (listener.DispatchQueue, Is.EqualTo (queue)); } } } diff --git a/tests/monotouch-test/Metal/MTLStageInRegionIndirectArgumentsTest.cs b/tests/monotouch-test/Metal/MTLStageInRegionIndirectArgumentsTest.cs index 9c46eff30097..283332e01d8d 100644 --- a/tests/monotouch-test/Metal/MTLStageInRegionIndirectArgumentsTest.cs +++ b/tests/monotouch-test/Metal/MTLStageInRegionIndirectArgumentsTest.cs @@ -17,7 +17,7 @@ public void SetUp () public void SizeOfMTLStageInRegionIndirectArgumentsTest () { unsafe { - Assert.AreEqual (sizeof (MTLStageInRegionIndirectArguments), 24); // 24 is the size of the native struct + Assert.That (sizeof (MTLStageInRegionIndirectArguments), Is.EqualTo (24)); // 24 is the size of the native struct } } } diff --git a/tests/monotouch-test/Metal/MTLStageInputOutputDescriptorTest.cs b/tests/monotouch-test/Metal/MTLStageInputOutputDescriptorTest.cs index b78d6bef69b6..332c2041431a 100644 --- a/tests/monotouch-test/Metal/MTLStageInputOutputDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLStageInputOutputDescriptorTest.cs @@ -26,20 +26,20 @@ public void TearDown () [Test] public void GetLayoutsTest () { - Assert.NotNull (descriptor.Layouts); // default value + Assert.That (descriptor.Layouts, Is.Not.Null); // default value } [Test] public void GetAttributesTest () { - Assert.NotNull (descriptor.Attributes); // default value + Assert.That (descriptor.Attributes, Is.Not.Null); // default value } [Test] public void GetSetIndexType () { descriptor.IndexType = MTLIndexType.UInt32; - Assert.AreEqual (MTLIndexType.UInt32, descriptor.IndexType); + Assert.That (descriptor.IndexType, Is.EqualTo (MTLIndexType.UInt32)); } [Test] @@ -47,7 +47,7 @@ public void GetSetIndexBufferTest () { uint index = 5; descriptor.IndexBufferIndex = 5; - Assert.AreEqual (descriptor.IndexBufferIndex, (nuint) index); + Assert.That ((nuint) index, Is.EqualTo (descriptor.IndexBufferIndex)); } } } diff --git a/tests/monotouch-test/Metal/MTLTextureReferenceType.cs b/tests/monotouch-test/Metal/MTLTextureReferenceType.cs index 0cd11f8ce32b..8714aac2ad0e 100644 --- a/tests/monotouch-test/Metal/MTLTextureReferenceType.cs +++ b/tests/monotouch-test/Metal/MTLTextureReferenceType.cs @@ -26,25 +26,25 @@ public void TearDown () [Test] public void GetAccessTest () { - Assert.AreEqual (MTLArgumentAccess.ReadOnly, reference.Access); + Assert.That (reference.Access, Is.EqualTo (MTLArgumentAccess.ReadOnly)); } [Test] public void GetIsDepthTextureTest () { - Assert.False (reference.IsDepthTexture); + Assert.That (reference.IsDepthTexture, Is.False); } [Test] public void GetTextureDataType () { - Assert.AreEqual (MTLDataType.None, reference.TextureDataType); + Assert.That (reference.TextureDataType, Is.EqualTo (MTLDataType.None)); } [Test] public void GetTextureType () { - Assert.AreEqual (MTLTextureType.k1D, reference.TextureType); + Assert.That (reference.TextureType, Is.EqualTo (MTLTextureType.k1D)); } } } diff --git a/tests/monotouch-test/Metal/MTLTileRenderPipelineColorAttachmentDescriptorTests.cs b/tests/monotouch-test/Metal/MTLTileRenderPipelineColorAttachmentDescriptorTests.cs index 7f3f30627140..3a86116c0adb 100644 --- a/tests/monotouch-test/Metal/MTLTileRenderPipelineColorAttachmentDescriptorTests.cs +++ b/tests/monotouch-test/Metal/MTLTileRenderPipelineColorAttachmentDescriptorTests.cs @@ -32,7 +32,7 @@ public void TearDown () public void GetSetPixelFormat () { descriptor.PixelFormat = MTLPixelFormat.RGBA8Snorm; - Assert.AreEqual (MTLPixelFormat.RGBA8Snorm, descriptor.PixelFormat); + Assert.That (descriptor.PixelFormat, Is.EqualTo (MTLPixelFormat.RGBA8Snorm)); } } } diff --git a/tests/monotouch-test/Metal/MTLTileRenderPipelineDescriptor.cs b/tests/monotouch-test/Metal/MTLTileRenderPipelineDescriptor.cs index 82d816e4204a..1916d491a7fd 100644 --- a/tests/monotouch-test/Metal/MTLTileRenderPipelineDescriptor.cs +++ b/tests/monotouch-test/Metal/MTLTileRenderPipelineDescriptor.cs @@ -32,38 +32,38 @@ public void TearDown () public void ColorAttachmentsTest () { var attachments = descriptor.ColorAttachments; - Assert.NotNull (attachments); + Assert.That (attachments, Is.Not.Null); } [Test] public void GetSetLabelTest () { descriptor.Label = "Foo"; - Assert.AreEqual ("Foo", descriptor.Label); + Assert.That (descriptor.Label, Is.EqualTo ("Foo")); } [Test] public void GetSetRasterSampleCount () { descriptor.RasterSampleCount = 2; - Assert.AreEqual ((nuint) 2, descriptor.RasterSampleCount); + Assert.That (descriptor.RasterSampleCount, Is.EqualTo ((nuint) 2)); } [Test] public void GetSetThreadgroupSizeMatchesTileSize () { descriptor.ThreadgroupSizeMatchesTileSize = true; - Assert.AreEqual (true, descriptor.ThreadgroupSizeMatchesTileSize); + Assert.That (descriptor.ThreadgroupSizeMatchesTileSize, Is.EqualTo (true)); descriptor.ThreadgroupSizeMatchesTileSize = false; - Assert.AreEqual (false, descriptor.ThreadgroupSizeMatchesTileSize); + Assert.That (descriptor.ThreadgroupSizeMatchesTileSize, Is.EqualTo (false)); } [Test] public void GetTileBuffers () { var buffers = descriptor.TileBuffers; - Assert.NotNull (buffers); + Assert.That (buffers, Is.Not.Null); } [Test] @@ -71,7 +71,7 @@ public void GetSetMaxTotalThreadsPerThreadgroupTest () { TestRuntime.AssertXcodeVersion (10, 0); descriptor.MaxTotalThreadsPerThreadgroup = 10; - Assert.AreEqual ((nuint) 10, descriptor.MaxTotalThreadsPerThreadgroup); + Assert.That (descriptor.MaxTotalThreadsPerThreadgroup, Is.EqualTo ((nuint) 10)); } } } diff --git a/tests/monotouch-test/Metal/MTLVisibleFunctionTableDescriptorTest.cs b/tests/monotouch-test/Metal/MTLVisibleFunctionTableDescriptorTest.cs index 83673445e6db..aeb09f90bbf7 100644 --- a/tests/monotouch-test/Metal/MTLVisibleFunctionTableDescriptorTest.cs +++ b/tests/monotouch-test/Metal/MTLVisibleFunctionTableDescriptorTest.cs @@ -37,7 +37,7 @@ public void FunctionCountTest () Assert.DoesNotThrow (() => { objFunctionCount = descriptor.FunctionCount; }, "Getter"); - Assert.AreEqual (newFunctionCount, objFunctionCount, "Value"); + Assert.That (objFunctionCount, Is.EqualTo (newFunctionCount), "Value"); } } } diff --git a/tests/monotouch-test/Metal/StructTest.cs b/tests/monotouch-test/Metal/StructTest.cs index d8616ce784bb..fe470f959350 100644 --- a/tests/monotouch-test/Metal/StructTest.cs +++ b/tests/monotouch-test/Metal/StructTest.cs @@ -11,14 +11,14 @@ public class StructTest { public void MTLQuadTessellationFactorsHalfStructSize () { // tested with a native iOS app - Assert.AreEqual (12, Marshal.SizeOf (), $"Reported size was {Marshal.SizeOf ()}"); + Assert.That (Marshal.SizeOf (), Is.EqualTo (12), $"Reported size was {Marshal.SizeOf ()}"); } [Test] public void MTLTriangleTessellationFactorsHalfStructSize () { // tested with a native iOS app - Assert.AreEqual (8, Marshal.SizeOf (), $"Reported size was {Marshal.SizeOf ()}"); + Assert.That (Marshal.SizeOf (), Is.EqualTo (8), $"Reported size was {Marshal.SizeOf ()}"); } } } diff --git a/tests/monotouch-test/MetalPerformanceShaders/KernelTest.cs b/tests/monotouch-test/MetalPerformanceShaders/KernelTest.cs index 017f003de3a0..5c62aaf58749 100644 --- a/tests/monotouch-test/MetalPerformanceShaders/KernelTest.cs +++ b/tests/monotouch-test/MetalPerformanceShaders/KernelTest.cs @@ -123,12 +123,12 @@ public void MPSImageLaplacianPyramidCtorArrTest () }; var valid = new MPSImageLaplacianPyramid (device, 3, 3, validArr); - Assert.NotNull (valid, "Valid Arr"); + Assert.That (valid, Is.Not.Null, "Valid Arr"); Assert.Throws (() => new MPSImageLaplacianPyramid (device, 3, 3, invalidArr), "Invalid Arr"); var bigvalid = new MPSImageLaplacianPyramid (device, 3, 3, bigvalidArr); - Assert.NotNull (valid, "Big valid Arr"); + Assert.That (valid, Is.Not.Null, "Big valid Arr"); } } } diff --git a/tests/monotouch-test/MetalPerformanceShaders/MPSImageBatchTests.cs b/tests/monotouch-test/MetalPerformanceShaders/MPSImageBatchTests.cs index 47947512b1d5..1ecd0812f423 100644 --- a/tests/monotouch-test/MetalPerformanceShaders/MPSImageBatchTests.cs +++ b/tests/monotouch-test/MetalPerformanceShaders/MPSImageBatchTests.cs @@ -62,7 +62,7 @@ public void MPSImageBatchResourceSizeTest () // }); // Assert.That (idx, Is.EqualTo (5), "idx"); - // Assert.IsTrue (hit, "hit"); + // Assert.That (hit, Is.True, "hit"); //} } } diff --git a/tests/monotouch-test/MetalPerformanceShaders/MPSImageHistogramTest.cs b/tests/monotouch-test/MetalPerformanceShaders/MPSImageHistogramTest.cs index acb0d4213051..e9a71f82a349 100644 --- a/tests/monotouch-test/MetalPerformanceShaders/MPSImageHistogramTest.cs +++ b/tests/monotouch-test/MetalPerformanceShaders/MPSImageHistogramTest.cs @@ -38,22 +38,22 @@ public void Constructors () var rv = obj.HistogramInfo; Asserts.AreEqual (info, rv, "HistogramForAlpha"); - Assert.IsTrue (obj.ZeroHistogram, "ZeroHistogram"); + Assert.That (obj.ZeroHistogram, Is.True, "ZeroHistogram"); if (TestRuntime.CheckXcodeVersion (8, 0)) { // HistogramSizeForSourceFormat was introduced in iOS 9, but no matter which MTLPixelFormat value I pass in, // the native histogramSizeForSourceFormat: function rudely aborts the entire process with an abrupt: // > /BuildRoot/Library/Caches/com.apple.xbs/Sources/MetalImage/MetalImage-39.3/MetalImage/Filters/MIHistogram.mm:103: failed assertion `[MPSImageHistogram histogramSizeForSourceFormat:] unsupported texture format: 114' // I made sure the MTLPixelFormat values I tested with were also added in iOS 9, so that's not the problem. // Conclusion: just avoid executing HistogramSizeForSourceFormat on anything below iOS 10.rm - Assert.AreEqual ((nuint) 3072, obj.GetHistogramSize (MTLPixelFormat.RGBA16Sint), "HistogramSizeForSourceFormat"); + Assert.That (obj.GetHistogramSize (MTLPixelFormat.RGBA16Sint), Is.EqualTo ((nuint) 3072), "HistogramSizeForSourceFormat"); } var crs = obj.ClipRectSource; - Assert.AreEqual ((nint) 0, crs.Origin.X, "ClipRectSource.Origin.X"); - Assert.AreEqual ((nint) 0, crs.Origin.Y, "ClipRectSource.Origin.Y"); - Assert.AreEqual ((nint) 0, crs.Origin.Z, "ClipRectSource.Origin.Z"); - Assert.AreEqual ((nint) (-1), crs.Size.Depth, "ClipRectSource.Size.Depth"); - Assert.AreEqual ((nint) (-1), crs.Size.Height, "ClipRectSource.Size.Height"); - Assert.AreEqual ((nint) (-1), crs.Size.Width, "ClipRectSource.Size.Width"); + Assert.That (crs.Origin.X, Is.EqualTo ((nint) 0), "ClipRectSource.Origin.X"); + Assert.That (crs.Origin.Y, Is.EqualTo ((nint) 0), "ClipRectSource.Origin.Y"); + Assert.That (crs.Origin.Z, Is.EqualTo ((nint) 0), "ClipRectSource.Origin.Z"); + Assert.That (crs.Size.Depth, Is.EqualTo ((nint) (-1)), "ClipRectSource.Size.Depth"); + Assert.That (crs.Size.Height, Is.EqualTo ((nint) (-1)), "ClipRectSource.Size.Height"); + Assert.That (crs.Size.Width, Is.EqualTo ((nint) (-1)), "ClipRectSource.Size.Width"); } } } diff --git a/tests/monotouch-test/MetalPerformanceShaders/MPSImageNormalizedHistogramTests.cs b/tests/monotouch-test/MetalPerformanceShaders/MPSImageNormalizedHistogramTests.cs index 3d7b2cf80b25..2cd104d2df5b 100644 --- a/tests/monotouch-test/MetalPerformanceShaders/MPSImageNormalizedHistogramTests.cs +++ b/tests/monotouch-test/MetalPerformanceShaders/MPSImageNormalizedHistogramTests.cs @@ -46,20 +46,20 @@ public void Constructors () Assert.Fail (ex.Message); } #endif - Assert.NotNull (obj, "MPSImageNormalizedHistogram obj"); + Assert.That (obj, Is.Not.Null, "MPSImageNormalizedHistogram obj"); var rv = obj.HistogramInfo; Asserts.AreEqual (info, rv, "HistogramInfo"); - Assert.IsTrue (obj.ZeroHistogram, "ZeroHistogram"); - Assert.AreEqual ((nuint) 3072, obj.GetHistogramSize (MTLPixelFormat.RGBA16Sint), "HistogramSizeForSourceFormat"); + Assert.That (obj.ZeroHistogram, Is.True, "ZeroHistogram"); + Assert.That (obj.GetHistogramSize (MTLPixelFormat.RGBA16Sint), Is.EqualTo ((nuint) 3072), "HistogramSizeForSourceFormat"); var crs = obj.ClipRectSource; - Assert.AreEqual ((nint) 0, crs.Origin.X, "ClipRectSource.Origin.X"); - Assert.AreEqual ((nint) 0, crs.Origin.Y, "ClipRectSource.Origin.Y"); - Assert.AreEqual ((nint) 0, crs.Origin.Z, "ClipRectSource.Origin.Z"); - Assert.AreEqual (nuint.MaxValue, (nuint) crs.Size.Depth, "ClipRectSource.Size.Depth"); - Assert.AreEqual (nuint.MaxValue, (nuint) crs.Size.Height, "ClipRectSource.Size.Height"); - Assert.AreEqual (nuint.MaxValue, (nuint) crs.Size.Width, "ClipRectSource.Size.Width"); + Assert.That (crs.Origin.X, Is.EqualTo ((nint) 0), "ClipRectSource.Origin.X"); + Assert.That (crs.Origin.Y, Is.EqualTo ((nint) 0), "ClipRectSource.Origin.Y"); + Assert.That (crs.Origin.Z, Is.EqualTo ((nint) 0), "ClipRectSource.Origin.Z"); + Assert.That ((nuint) crs.Size.Depth, Is.EqualTo (nuint.MaxValue), "ClipRectSource.Size.Depth"); + Assert.That ((nuint) crs.Size.Height, Is.EqualTo (nuint.MaxValue), "ClipRectSource.Size.Height"); + Assert.That ((nuint) crs.Size.Width, Is.EqualTo (nuint.MaxValue), "ClipRectSource.Size.Width"); } } } diff --git a/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayDescriptorTest.cs b/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayDescriptorTest.cs index 5b3e59bebbc9..65044edff347 100644 --- a/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayDescriptorTest.cs +++ b/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayDescriptorTest.cs @@ -21,7 +21,7 @@ public void PermuteWithDimensionOrderTest () using var desc = MPSNDArrayDescriptor.Create (MPSDataType.Int32, new nuint [] { 10 }); desc.PermuteWithDimensionOrder (new nuint [] { 0 }); - Assert.AreEqual (1, (int) desc.NumberOfDimensions, "NumberOfDimensions"); + Assert.That ((int) desc.NumberOfDimensions, Is.EqualTo (1), "NumberOfDimensions"); } [Test] diff --git a/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayIdentityTest.cs b/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayIdentityTest.cs index a1aa96e60106..873b08595397 100644 --- a/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayIdentityTest.cs +++ b/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayIdentityTest.cs @@ -23,8 +23,8 @@ public void ReshapeA () using var identity = new MPSNDArrayIdentity (device); using var sourceArray = new MPSNDArray (device, 3.14f); using var newArray = identity.Reshape (null, sourceArray, new nuint [] { 1 }, null); - Assert.AreEqual (1, (int) newArray.NumberOfDimensions, "NumberOfDimensions"); - Assert.AreEqual (1, (int) newArray.GetLength (0), "Length #0"); + Assert.That ((int) newArray.NumberOfDimensions, Is.EqualTo (1), "NumberOfDimensions"); + Assert.That ((int) newArray.GetLength (0), Is.EqualTo (1), "Length #0"); } [Test] @@ -39,8 +39,8 @@ public void ReshapeB () using var identity = new MPSNDArrayIdentity (device); using var sourceArray = new MPSNDArray (device, 3.14f); using var newArray = identity.Reshape (null, null, sourceArray, new nuint [] { 1 }, null); - Assert.AreEqual (1, (int) newArray.NumberOfDimensions, "NumberOfDimensions"); - Assert.AreEqual (1, (int) newArray.GetLength (0), "Length #0"); + Assert.That ((int) newArray.NumberOfDimensions, Is.EqualTo (1), "NumberOfDimensions"); + Assert.That ((int) newArray.GetLength (0), Is.EqualTo (1), "Length #0"); } } } diff --git a/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayOffsetsTest.cs b/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayOffsetsTest.cs index 4b5f6d0c6d2f..ec1be5dc26c3 100644 --- a/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayOffsetsTest.cs +++ b/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayOffsetsTest.cs @@ -15,11 +15,11 @@ public class MPSNDArrayOffsetsTest { public void Dimensions () { var value = default (MPSNDArrayOffsets); - CollectionAssert.AreEqual (new nint [16], value.Dimensions, "A"); + Assert.That (value.Dimensions, Is.EqualTo (new nint [16]), "A"); var array = new nint [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; value.Dimensions = array; - CollectionAssert.AreEqual (array, value.Dimensions, "B"); + Assert.That (value.Dimensions, Is.EqualTo (array), "B"); Assert.Throws (() => value.Dimensions = null, "C"); Assert.Throws (() => value.Dimensions = new nint [15], "D"); diff --git a/tests/monotouch-test/MetalPerformanceShaders/MPSNDArraySizesTest.cs b/tests/monotouch-test/MetalPerformanceShaders/MPSNDArraySizesTest.cs index cfa8108db528..f4f8359d1fc4 100644 --- a/tests/monotouch-test/MetalPerformanceShaders/MPSNDArraySizesTest.cs +++ b/tests/monotouch-test/MetalPerformanceShaders/MPSNDArraySizesTest.cs @@ -15,11 +15,11 @@ public class MPSNDArraySizesTest { public void Dimensions () { var value = default (MPSNDArraySizes); - CollectionAssert.AreEqual (new nuint [16], value.Dimensions, "A"); + Assert.That (value.Dimensions, Is.EqualTo (new nuint [16]), "A"); var array = new nuint [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; value.Dimensions = array; - CollectionAssert.AreEqual (array, value.Dimensions, "B"); + Assert.That (value.Dimensions, Is.EqualTo (array), "B"); Assert.Throws (() => value.Dimensions = null, "C"); Assert.Throws (() => value.Dimensions = new nuint [15], "D"); diff --git a/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayTest.cs b/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayTest.cs index fefd2578c8aa..7d235f3af41b 100644 --- a/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayTest.cs +++ b/tests/monotouch-test/MetalPerformanceShaders/MPSNDArrayTest.cs @@ -22,7 +22,7 @@ public void Create () using var array = new MPSNDArray (device, 3.14); using var newArray = array.Create (1, new nuint [] { 1 }, new nuint [] { 1 }); - Assert.IsNull (newArray, "Create"); // creation probably fails because I don't know which arguments to pass. + Assert.That (newArray, Is.Null, "Create"); // creation probably fails because I don't know which arguments to pass. Assert.Throws (() => array.Create (2, new nuint [1], new nuint [2]), "AOORE 1"); Assert.Throws (() => array.Create (2, new nuint [2], new nuint [1]), "AOORE 2"); diff --git a/tests/monotouch-test/MetalPerformanceShaders/MPSStateResourceListTests.cs b/tests/monotouch-test/MetalPerformanceShaders/MPSStateResourceListTests.cs index 7839b738a065..ef43c31f3bdb 100644 --- a/tests/monotouch-test/MetalPerformanceShaders/MPSStateResourceListTests.cs +++ b/tests/monotouch-test/MetalPerformanceShaders/MPSStateResourceListTests.cs @@ -35,7 +35,7 @@ public void Metal () public void CreateTest () { var resList = MPSStateResourceList.Create (); - Assert.NotNull (resList, "Create"); + Assert.That (resList, Is.Not.Null, "Create"); } [Test] @@ -46,7 +46,7 @@ public void MTLTextureDescriptorCreateTest () arr [i] = MTLTextureDescriptor.CreateTexture2DDescriptor (MTLPixelFormat.Depth32Float, 50 + i, 50 + i, false); var resList = MPSStateResourceList.Create (arr [0], arr [1], arr [2], arr [3], arr [4], arr [5], arr [6], arr [7], arr [8], arr [9]); - Assert.NotNull (resList, "resList"); + Assert.That (resList, Is.Not.Null, "resList"); var state = new MPSState (device, resList); Assert.That (state.ResourceCount, Is.EqualTo ((nuint) 10), "ResourceCount"); @@ -56,7 +56,7 @@ public void MTLTextureDescriptorCreateTest () public void SizesCreateTest () { var resList = MPSStateResourceList.Create (1, 2, 3, 4, 5, 241); - Assert.NotNull (resList, "resList"); + Assert.That (resList, Is.Not.Null, "resList"); var state = new MPSState (device, resList); Assert.That (state.ResourceCount, Is.EqualTo ((nuint) 6), "ResourceCount"); diff --git a/tests/monotouch-test/MetalPerformanceShaders/MnistTest.cs b/tests/monotouch-test/MetalPerformanceShaders/MnistTest.cs index 57b5c05669fa..87b90e75b902 100644 --- a/tests/monotouch-test/MetalPerformanceShaders/MnistTest.cs +++ b/tests/monotouch-test/MetalPerformanceShaders/MnistTest.cs @@ -86,8 +86,8 @@ MPSCommandBuffer RunTrainingIterationBatch (float progress) completed = true; }); - Assert.IsTrue (TestRuntime.RunAsync (TimeSpan.FromSeconds (30), () => { - }, () => completed), "Completion"); + Assert.That (TestRuntime.RunAsync (TimeSpan.FromSeconds (30), () => { + }, () => completed), Is.True, "Completion"); // Don't need to commit since EncodeTrainingBatch oddly does that return commandBuffer; diff --git a/tests/monotouch-test/MobileCoreServices/UTTypeTest.cs b/tests/monotouch-test/MobileCoreServices/UTTypeTest.cs index 7bb9e3783c20..d22927e9c259 100644 --- a/tests/monotouch-test/MobileCoreServices/UTTypeTest.cs +++ b/tests/monotouch-test/MobileCoreServices/UTTypeTest.cs @@ -18,98 +18,98 @@ public class UTTypeTest { [Test] public void NSStringConstants () { - Assert.NotNull (UTType.ExportedTypeDeclarationsKey, "ExportedTypeDeclarationsKey"); - Assert.NotNull (UTType.ImportedTypeDeclarationsKey, "ImportedTypeDeclarationsKey"); - Assert.NotNull (UTType.IdentifierKey, "IdentifierKey"); - Assert.NotNull (UTType.TagSpecificationKey, "TagSpecificationKey"); - Assert.NotNull (UTType.ConformsToKey, "ConformsToKey"); - Assert.NotNull (UTType.DescriptionKey, "DescriptionKey"); - Assert.NotNull (UTType.IconFileKey, "IconFileKey"); - Assert.NotNull (UTType.ReferenceURLKey, "ReferenceURLKey"); - Assert.NotNull (UTType.VersionKey, "VersionKey"); - - Assert.NotNull (UTType.TagClassFilenameExtension, "TagClassFilenameExtension"); - Assert.NotNull (UTType.TagClassMIMEType, "TagClassMIMEType"); - - Assert.NotNull (UTType.Item, "Item"); - Assert.NotNull (UTType.Content, "Content"); - Assert.NotNull (UTType.CompositeContent, "CompositeContent"); - Assert.NotNull (UTType.Application, "Application"); - Assert.NotNull (UTType.Message, "Message"); - Assert.NotNull (UTType.Contact, "Contact"); - Assert.NotNull (UTType.Archive, "Archive"); - Assert.NotNull (UTType.DiskImage, "DiskImage"); - - Assert.NotNull (UTType.Data, "Data"); - Assert.NotNull (UTType.Directory, "Directory"); - Assert.NotNull (UTType.Resolvable, "Resolvable"); - Assert.NotNull (UTType.SymLink, "SymLink"); - Assert.NotNull (UTType.MountPoint, "MountPoint"); - Assert.NotNull (UTType.AliasFile, "AliasFile"); - Assert.NotNull (UTType.AliasRecord, "AliasRecord"); - Assert.NotNull (UTType.URL, "URL"); - Assert.NotNull (UTType.FileURL, "FileURL"); - - Assert.NotNull (UTType.Text, "Text"); - Assert.NotNull (UTType.PlainText, "PlainText"); - Assert.NotNull (UTType.UTF8PlainText, "UTF8PlainText"); - Assert.NotNull (UTType.UTF16ExternalPlainText, "UTF16ExternalPlainText"); - Assert.NotNull (UTType.UTF16PlainText, "UTF16PlainText"); - Assert.NotNull (UTType.RTF, "RTF"); - Assert.NotNull (UTType.HTML, "HTML"); - Assert.NotNull (UTType.XML, "XML"); - Assert.NotNull (UTType.SourceCode, "SourceCode"); - Assert.NotNull (UTType.CSource, "CSource"); - Assert.NotNull (UTType.ObjectiveCSource, "ObjectiveCSource"); - Assert.NotNull (UTType.CPlusPlusSource, "CPlusPlusSource"); - Assert.NotNull (UTType.ObjectiveCPlusPlusSource, "ObjectiveCPlusPlusSource"); - Assert.NotNull (UTType.CHeader, "CHeader"); - Assert.NotNull (UTType.CPlusPlusHeader, "CPlusPlusHeader"); - Assert.NotNull (UTType.JavaSource, "JavaSource"); - - Assert.NotNull (UTType.PDF, "PDF"); - Assert.NotNull (UTType.RTFD, "RTFD"); - Assert.NotNull (UTType.FlatRTFD, "FlatRTFD"); - Assert.NotNull (UTType.TXNTextAndMultimediaData, "TXNTextAndMultimediaData"); - Assert.NotNull (UTType.WebArchive, "WebArchive"); - - Assert.NotNull (UTType.Image, "Image"); - Assert.NotNull (UTType.JPEG, "JPEG"); - Assert.NotNull (UTType.JPEG2000, "JPEG2000"); - Assert.NotNull (UTType.TIFF, "TIFF"); - Assert.NotNull (UTType.GIF, "GIF"); - Assert.NotNull (UTType.PNG, "PNG"); - Assert.NotNull (UTType.QuickTimeImage, "QuickTimeImage"); - Assert.NotNull (UTType.AppleICNS, "AppleICNS"); - Assert.NotNull (UTType.BMP, "BMP"); - Assert.NotNull (UTType.ICO, "ICO"); - - Assert.NotNull (UTType.AudiovisualContent, "AudiovisualContent"); - Assert.NotNull (UTType.Movie, "Movie"); - Assert.NotNull (UTType.Video, "Video"); - Assert.NotNull (UTType.Audio, "Audio"); - Assert.NotNull (UTType.QuickTimeMovie, "QuickTimeMovie"); - Assert.NotNull (UTType.MPEG, "MPEG"); - Assert.NotNull (UTType.MPEG4, "MPEG4"); - Assert.NotNull (UTType.MP3, "MP3"); - Assert.NotNull (UTType.MPEG4Audio, "MPEG4Audio"); - Assert.NotNull (UTType.AppleProtectedMPEG4Audio, "AppleProtectedMPEG4Audio"); - - Assert.NotNull (UTType.Folder, "Folder"); - Assert.NotNull (UTType.Volume, "Volume"); - Assert.NotNull (UTType.Package, "Package"); - Assert.NotNull (UTType.Bundle, "Bundle"); - Assert.NotNull (UTType.Framework, "Framework"); - - Assert.NotNull (UTType.ApplicationBundle, "ApplicationBundle"); - Assert.NotNull (UTType.ApplicationFile, "ApplicationFile"); - - Assert.NotNull (UTType.VCard, "VCard"); - - Assert.NotNull (UTType.InkText, "InkText"); + Assert.That (UTType.ExportedTypeDeclarationsKey, Is.Not.Null, "ExportedTypeDeclarationsKey"); + Assert.That (UTType.ImportedTypeDeclarationsKey, Is.Not.Null, "ImportedTypeDeclarationsKey"); + Assert.That (UTType.IdentifierKey, Is.Not.Null, "IdentifierKey"); + Assert.That (UTType.TagSpecificationKey, Is.Not.Null, "TagSpecificationKey"); + Assert.That (UTType.ConformsToKey, Is.Not.Null, "ConformsToKey"); + Assert.That (UTType.DescriptionKey, Is.Not.Null, "DescriptionKey"); + Assert.That (UTType.IconFileKey, Is.Not.Null, "IconFileKey"); + Assert.That (UTType.ReferenceURLKey, Is.Not.Null, "ReferenceURLKey"); + Assert.That (UTType.VersionKey, Is.Not.Null, "VersionKey"); + + Assert.That (UTType.TagClassFilenameExtension, Is.Not.Null, "TagClassFilenameExtension"); + Assert.That (UTType.TagClassMIMEType, Is.Not.Null, "TagClassMIMEType"); + + Assert.That (UTType.Item, Is.Not.Null, "Item"); + Assert.That (UTType.Content, Is.Not.Null, "Content"); + Assert.That (UTType.CompositeContent, Is.Not.Null, "CompositeContent"); + Assert.That (UTType.Application, Is.Not.Null, "Application"); + Assert.That (UTType.Message, Is.Not.Null, "Message"); + Assert.That (UTType.Contact, Is.Not.Null, "Contact"); + Assert.That (UTType.Archive, Is.Not.Null, "Archive"); + Assert.That (UTType.DiskImage, Is.Not.Null, "DiskImage"); + + Assert.That (UTType.Data, Is.Not.Null, "Data"); + Assert.That (UTType.Directory, Is.Not.Null, "Directory"); + Assert.That (UTType.Resolvable, Is.Not.Null, "Resolvable"); + Assert.That (UTType.SymLink, Is.Not.Null, "SymLink"); + Assert.That (UTType.MountPoint, Is.Not.Null, "MountPoint"); + Assert.That (UTType.AliasFile, Is.Not.Null, "AliasFile"); + Assert.That (UTType.AliasRecord, Is.Not.Null, "AliasRecord"); + Assert.That (UTType.URL, Is.Not.Null, "URL"); + Assert.That (UTType.FileURL, Is.Not.Null, "FileURL"); + + Assert.That (UTType.Text, Is.Not.Null, "Text"); + Assert.That (UTType.PlainText, Is.Not.Null, "PlainText"); + Assert.That (UTType.UTF8PlainText, Is.Not.Null, "UTF8PlainText"); + Assert.That (UTType.UTF16ExternalPlainText, Is.Not.Null, "UTF16ExternalPlainText"); + Assert.That (UTType.UTF16PlainText, Is.Not.Null, "UTF16PlainText"); + Assert.That (UTType.RTF, Is.Not.Null, "RTF"); + Assert.That (UTType.HTML, Is.Not.Null, "HTML"); + Assert.That (UTType.XML, Is.Not.Null, "XML"); + Assert.That (UTType.SourceCode, Is.Not.Null, "SourceCode"); + Assert.That (UTType.CSource, Is.Not.Null, "CSource"); + Assert.That (UTType.ObjectiveCSource, Is.Not.Null, "ObjectiveCSource"); + Assert.That (UTType.CPlusPlusSource, Is.Not.Null, "CPlusPlusSource"); + Assert.That (UTType.ObjectiveCPlusPlusSource, Is.Not.Null, "ObjectiveCPlusPlusSource"); + Assert.That (UTType.CHeader, Is.Not.Null, "CHeader"); + Assert.That (UTType.CPlusPlusHeader, Is.Not.Null, "CPlusPlusHeader"); + Assert.That (UTType.JavaSource, Is.Not.Null, "JavaSource"); + + Assert.That (UTType.PDF, Is.Not.Null, "PDF"); + Assert.That (UTType.RTFD, Is.Not.Null, "RTFD"); + Assert.That (UTType.FlatRTFD, Is.Not.Null, "FlatRTFD"); + Assert.That (UTType.TXNTextAndMultimediaData, Is.Not.Null, "TXNTextAndMultimediaData"); + Assert.That (UTType.WebArchive, Is.Not.Null, "WebArchive"); + + Assert.That (UTType.Image, Is.Not.Null, "Image"); + Assert.That (UTType.JPEG, Is.Not.Null, "JPEG"); + Assert.That (UTType.JPEG2000, Is.Not.Null, "JPEG2000"); + Assert.That (UTType.TIFF, Is.Not.Null, "TIFF"); + Assert.That (UTType.GIF, Is.Not.Null, "GIF"); + Assert.That (UTType.PNG, Is.Not.Null, "PNG"); + Assert.That (UTType.QuickTimeImage, Is.Not.Null, "QuickTimeImage"); + Assert.That (UTType.AppleICNS, Is.Not.Null, "AppleICNS"); + Assert.That (UTType.BMP, Is.Not.Null, "BMP"); + Assert.That (UTType.ICO, Is.Not.Null, "ICO"); + + Assert.That (UTType.AudiovisualContent, Is.Not.Null, "AudiovisualContent"); + Assert.That (UTType.Movie, Is.Not.Null, "Movie"); + Assert.That (UTType.Video, Is.Not.Null, "Video"); + Assert.That (UTType.Audio, Is.Not.Null, "Audio"); + Assert.That (UTType.QuickTimeMovie, Is.Not.Null, "QuickTimeMovie"); + Assert.That (UTType.MPEG, Is.Not.Null, "MPEG"); + Assert.That (UTType.MPEG4, Is.Not.Null, "MPEG4"); + Assert.That (UTType.MP3, Is.Not.Null, "MP3"); + Assert.That (UTType.MPEG4Audio, Is.Not.Null, "MPEG4Audio"); + Assert.That (UTType.AppleProtectedMPEG4Audio, Is.Not.Null, "AppleProtectedMPEG4Audio"); + + Assert.That (UTType.Folder, Is.Not.Null, "Folder"); + Assert.That (UTType.Volume, Is.Not.Null, "Volume"); + Assert.That (UTType.Package, Is.Not.Null, "Package"); + Assert.That (UTType.Bundle, Is.Not.Null, "Bundle"); + Assert.That (UTType.Framework, Is.Not.Null, "Framework"); + + Assert.That (UTType.ApplicationBundle, Is.Not.Null, "ApplicationBundle"); + Assert.That (UTType.ApplicationFile, Is.Not.Null, "ApplicationFile"); + + Assert.That (UTType.VCard, Is.Not.Null, "VCard"); + + Assert.That (UTType.InkText, Is.Not.Null, "InkText"); if (TestRuntime.CheckXcodeVersion (7, 0)) - Assert.NotNull (UTType.SwiftSource, "SwiftSource"); + Assert.That (UTType.SwiftSource, Is.Not.Null, "SwiftSource"); } [Test] @@ -119,7 +119,7 @@ public void GetPreferredTag () // so just skip this test for the simulator. TestRuntime.AssertIfSimulatorThenARM64 (); - Assert.NotNull (UTType.GetPreferredTag (UTType.PDF, UTType.TagClassFilenameExtension), "GetPreferredTag"); + Assert.That (UTType.GetPreferredTag (UTType.PDF, UTType.TagClassFilenameExtension), Is.Not.Null, "GetPreferredTag"); } [Test] @@ -129,7 +129,7 @@ public void GetDeclaration () // so just skip this test for the simulator. TestRuntime.AssertIfSimulatorThenARM64 (); - Assert.NotNull (UTType.GetDeclaration (UTType.PDF)); + Assert.That (UTType.GetDeclaration (UTType.PDF), Is.Not.Null); } [Test] @@ -139,7 +139,7 @@ public void GetDeclaringBundleURL () // so just skip this test for the simulator. TestRuntime.AssertIfSimulatorThenARM64 (); - Assert.NotNull (UTType.GetDeclaringBundleUrl (UTType.PDF)); + Assert.That (UTType.GetDeclaringBundleUrl (UTType.PDF), Is.Not.Null); } [Test] @@ -154,7 +154,7 @@ public void CreatePreferredIdentifier () for (int i = 0; i < 100; i++) { foreach (var ext in extensions) { var result = UTType.CreatePreferredIdentifier (UTType.TagClassMIMEType, ext, null); - Assert.NotNull (result, ext + i.ToString ()); + Assert.That (result, Is.Not.Null, ext + i.ToString ()); } } } @@ -162,10 +162,10 @@ public void CreatePreferredIdentifier () [Test] public void Equals () { - Assert.True (UTType.Equals (null, null), "null-null"); - Assert.False (UTType.Equals (null, UTType.PDF), "null-PDF"); - Assert.False (UTType.Equals (UTType.PDF, null), "PDF-null"); - Assert.True (UTType.Equals (UTType.PDF, UTType.PDF), "PDF-PDF"); + Assert.That (UTType.Equals (null, null), Is.True, "null-null"); + Assert.That (UTType.Equals (null, UTType.PDF), Is.False, "null-PDF"); + Assert.That (UTType.Equals (UTType.PDF, null), Is.False, "PDF-null"); + Assert.That (UTType.Equals (UTType.PDF, UTType.PDF), Is.True, "PDF-PDF"); } [Test] @@ -174,7 +174,7 @@ public void CreateAllIdentifiers () TestRuntime.AssertIfSimulatorThenARM64 (); var result = UTType.CreateAllIdentifiers (UTType.TagClassFilenameExtension, "pdf", null); - Assert.NotNull (result, "result"); + Assert.That (result, Is.Not.Null, "result"); Assert.That (result.Length, Is.GreaterThan (0), "Length"); } @@ -184,7 +184,7 @@ public void CopyAllTags () TestRuntime.AssertIfSimulatorThenARM64 (); var result = UTType.CopyAllTags (UTType.PDF, UTType.TagClassFilenameExtension); - Assert.NotNull (result, "result"); + Assert.That (result, Is.Not.Null, "result"); Assert.That (result.Length, Is.GreaterThan (0), "Length"); } @@ -194,7 +194,7 @@ public void GetDescription () TestRuntime.AssertIfSimulatorThenARM64 (); var result = UTType.GetDescription (UTType.PDF); - Assert.NotNull (result, "result"); + Assert.That (result, Is.Not.Null, "result"); Assert.That (result.Length, Is.GreaterThan (0), "Length"); } } diff --git a/tests/monotouch-test/ModelIO/MDLAnimatedValueTypesTests.cs b/tests/monotouch-test/ModelIO/MDLAnimatedValueTypesTests.cs index f4eb784eac64..f2645f80410c 100644 --- a/tests/monotouch-test/ModelIO/MDLAnimatedValueTypesTests.cs +++ b/tests/monotouch-test/ModelIO/MDLAnimatedValueTypesTests.cs @@ -65,8 +65,8 @@ public void MDLAnimatedScalarTest () Asserts.AreEqual (onesFloatArr [i], floatScalar.GetFloat (i), $"onesFloatArr iter: {i}"); floatScalar.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) floatScalar.TimeSampleCount, "floatScalar.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), floatScalar.GetFloatValues (), "floatScalar Empty"); + Assert.That ((int) floatScalar.TimeSampleCount, Is.EqualTo (0), "floatScalar.TimeSampleCount"); + Assert.That (floatScalar.GetFloatValues (), Is.EqualTo (Array.Empty ()), "floatScalar Empty"); // double @@ -88,8 +88,8 @@ public void MDLAnimatedScalarTest () Asserts.AreEqual (onesDoubleArr [i], doubleScalar.GetFloat (i), $"onesDoubleArr iter: {i}"); doubleScalar.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) doubleScalar.TimeSampleCount, "doubleScalar.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), doubleScalar.GetDoubleValues (), "doubleScalar Empty"); + Assert.That ((int) doubleScalar.TimeSampleCount, Is.EqualTo (0), "doubleScalar.TimeSampleCount"); + Assert.That (doubleScalar.GetDoubleValues (), Is.EqualTo (Array.Empty ()), "doubleScalar Empty"); } [Test] @@ -115,8 +115,8 @@ public void MDLAnimatedVector2Test () Asserts.AreEqual (onesVector2Arr [i], vector2Values.GetVector2Value (i), $"onesVector2Arr iter: {i}"); vector2Values.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) vector2Values.TimeSampleCount, "vector2Values.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), vector2Values.GetVector2Values (), "vector2Values Empty"); + Assert.That ((int) vector2Values.TimeSampleCount, Is.EqualTo (0), "vector2Values.TimeSampleCount"); + Assert.That (vector2Values.GetVector2Values (), Is.EqualTo (Array.Empty ()), "vector2Values Empty"); // Vector2d @@ -138,8 +138,8 @@ public void MDLAnimatedVector2Test () Asserts.AreEqual (onesVector2dArr [i], vector2dValues.GetVector2dValue (i), $"onesVector2dArr iter: {i}"); vector2dValues.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) vector2dValues.TimeSampleCount, "vector2dValues.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), vector2dValues.GetVector2dValues (), "vector2dValues Empty"); + Assert.That ((int) vector2dValues.TimeSampleCount, Is.EqualTo (0), "vector2dValues.TimeSampleCount"); + Assert.That (vector2dValues.GetVector2dValues (), Is.EqualTo (Array.Empty ()), "vector2dValues Empty"); } [Test] @@ -165,8 +165,8 @@ public void MDLAnimatedVector3Test () Asserts.AreEqual (onesVector3Arr [i], vector3Values.GetNVector3Value (i), $"onesVector3Arr iter: {i}"); vector3Values.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) vector3Values.TimeSampleCount, "vector3Values.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), vector3Values.GetNVector3Values (), "vector3Values Empty"); + Assert.That ((int) vector3Values.TimeSampleCount, Is.EqualTo (0), "vector3Values.TimeSampleCount"); + Assert.That (vector3Values.GetNVector3Values (), Is.EqualTo (Array.Empty ()), "vector3Values Empty"); // Vector3d @@ -188,8 +188,8 @@ public void MDLAnimatedVector3Test () Asserts.AreEqual (onesVector3dArr [i], vector3dValues.GetNVector3dValue (i), $"onesVector3dArr iter: {i}"); vector3dValues.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) vector3dValues.TimeSampleCount, "vector3dValues.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), vector3dValues.GetNVector3dValues (), "vector3dValues Empty"); + Assert.That ((int) vector3dValues.TimeSampleCount, Is.EqualTo (0), "vector3dValues.TimeSampleCount"); + Assert.That (vector3dValues.GetNVector3dValues (), Is.EqualTo (Array.Empty ()), "vector3dValues Empty"); } [Test] @@ -215,8 +215,8 @@ public void MDLAnimatedVector4Test () Asserts.AreEqual (onesVector4Arr [i], vector4Values.GetVector4Value (i), $"onesVector4Arr iter: {i}"); vector4Values.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) vector4Values.TimeSampleCount, "vector4Values.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), vector4Values.GetVector4Values (), "vector4Values Empty"); + Assert.That ((int) vector4Values.TimeSampleCount, Is.EqualTo (0), "vector4Values.TimeSampleCount"); + Assert.That (vector4Values.GetVector4Values (), Is.EqualTo (Array.Empty ()), "vector4Values Empty"); // Vector4d @@ -238,8 +238,8 @@ public void MDLAnimatedVector4Test () Asserts.AreEqual (onesVector4dArr [i], vector4dValues.GetVector4dValue (i), $"onesVector4dArr iter: {i}"); vector4dValues.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) vector4dValues.TimeSampleCount, "vector4dValues.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), vector4dValues.GetVector4dValues (), "vector4dValues Empty"); + Assert.That ((int) vector4dValues.TimeSampleCount, Is.EqualTo (0), "vector4dValues.TimeSampleCount"); + Assert.That (vector4dValues.GetVector4dValues (), Is.EqualTo (Array.Empty ()), "vector4dValues Empty"); } [Test] @@ -265,8 +265,8 @@ public void MDLAnimatedMatrix4x4Test () Asserts.AreEqual (onesNMatrix4Arr [i], nMatrix4Values.GetNMatrix4Value (i), $"onesNMatrix4Arr iter: {i}"); nMatrix4Values.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) nMatrix4Values.TimeSampleCount, "nMatrix4Values.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), nMatrix4Values.GetNMatrix4Values (), "nMatrix4Values Empty"); + Assert.That ((int) nMatrix4Values.TimeSampleCount, Is.EqualTo (0), "nMatrix4Values.TimeSampleCount"); + Assert.That (nMatrix4Values.GetNMatrix4Values (), Is.EqualTo (Array.Empty ()), "nMatrix4Values Empty"); // NMatrix4d @@ -288,8 +288,8 @@ public void MDLAnimatedMatrix4x4Test () Asserts.AreEqual (onesNMatrix4dArr [i], nMatrix4dValues.GetNMatrix4dValue (i), $"onesNMatrix4dArr iter: {i}"); nMatrix4dValues.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) nMatrix4dValues.TimeSampleCount, "nMatrix4dValues.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), nMatrix4dValues.GetNMatrix4dValues (), "nMatrix4dValues Empty"); + Assert.That ((int) nMatrix4dValues.TimeSampleCount, Is.EqualTo (0), "nMatrix4dValues.TimeSampleCount"); + Assert.That (nMatrix4dValues.GetNMatrix4dValues (), Is.EqualTo (Array.Empty ()), "nMatrix4dValues Empty"); } [Test] @@ -316,8 +316,8 @@ public void MDLAnimatedScalarArrayTest () Asserts.AreEqual (onesFloatArr [i], floatValues [i], $"onesFloatArr iter: {i}"); floatArr.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) floatArr.TimeSampleCount, "floatArr.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), floatArr.GetFloatValues (), "floatArr Empty"); + Assert.That ((int) floatArr.TimeSampleCount, Is.EqualTo (0), "floatArr.TimeSampleCount"); + Assert.That (floatArr.GetFloatValues (), Is.EqualTo (Array.Empty ()), "floatArr Empty"); // Doubles @@ -340,8 +340,8 @@ public void MDLAnimatedScalarArrayTest () Asserts.AreEqual (onesDoubleArr [i], doubleValues [i], $"onesDoubleArr iter: {i}"); doubleArr.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) doubleArr.TimeSampleCount, "doubleArr.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), doubleArr.GetFloatValues (), "doubleArr Empty"); + Assert.That ((int) doubleArr.TimeSampleCount, Is.EqualTo (0), "doubleArr.TimeSampleCount"); + Assert.That (doubleArr.GetFloatValues (), Is.EqualTo (Array.Empty ()), "doubleArr Empty"); } [Test] @@ -368,8 +368,8 @@ public void MDLAnimatedVector3ArrayTest () Asserts.AreEqual (onesnVector3Arr [i], nVector3Values [i], $"onesnVector3Arr iter: {i}"); nVector3Arr.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) nVector3Arr.TimeSampleCount, "nVector3Arr.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), nVector3Arr.GetNVector3Values (), "nVector3Arr Empty"); + Assert.That ((int) nVector3Arr.TimeSampleCount, Is.EqualTo (0), "nVector3Arr.TimeSampleCount"); + Assert.That (nVector3Arr.GetNVector3Values (), Is.EqualTo (Array.Empty ()), "nVector3Arr Empty"); // NVector3d @@ -392,8 +392,8 @@ public void MDLAnimatedVector3ArrayTest () Asserts.AreEqual (onesnVector3dArr [i], nVector3dValues [i], $"onesnVector3dArr iter: {i}"); nVector3dArr.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) nVector3dArr.TimeSampleCount, "nVector3dArr.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), nVector3dArr.GetNVector3dValues (), "nVector3dArr Empty"); + Assert.That ((int) nVector3dArr.TimeSampleCount, Is.EqualTo (0), "nVector3dArr.TimeSampleCount"); + Assert.That (nVector3dArr.GetNVector3dValues (), Is.EqualTo (Array.Empty ()), "nVector3dArr Empty"); } [Test] @@ -420,8 +420,8 @@ public void MDLAnimatedQuaternionArrayTest () Asserts.AreEqual (onesQuaternionArr [i], quaternionValues [i], $"onesQuaternionArr iter: {i}"); quaternionArr.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) quaternionArr.TimeSampleCount, "quaternionArr.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), quaternionArr.GetQuaternionValues (), "quaternionArr Empty"); + Assert.That ((int) quaternionArr.TimeSampleCount, Is.EqualTo (0), "quaternionArr.TimeSampleCount"); + Assert.That (quaternionArr.GetQuaternionValues (), Is.EqualTo (Array.Empty ()), "quaternionArr Empty"); // Quaterniond @@ -444,8 +444,8 @@ public void MDLAnimatedQuaternionArrayTest () Asserts.AreEqual (onesQuaterniondArr [i], quaterniondValues [i], $"onesQuaterniondArr iter: {i}"); quaterniondArr.Reset (Array.Empty (), Array.Empty ()); - Assert.AreEqual (0, (int) quaterniondArr.TimeSampleCount, "quaterniondArr.TimeSampleCount"); - Assert.AreEqual (Array.Empty (), quaterniondArr.GetQuaterniondValues (), "quaterniondArr Empty"); + Assert.That ((int) quaterniondArr.TimeSampleCount, Is.EqualTo (0), "quaterniondArr.TimeSampleCount"); + Assert.That (quaterniondArr.GetQuaterniondValues (), Is.EqualTo (Array.Empty ()), "quaterniondArr Empty"); } [Test] @@ -504,18 +504,18 @@ public void MDLAnimatedQuaternionTest () [Test] public unsafe void OpenTKSizeOfTests () { - Assert.AreEqual (sizeof (Matrix4), Marshal.SizeOf ()); - Assert.AreEqual (sizeof (Matrix4d), Marshal.SizeOf ()); - - Assert.AreEqual (sizeof (Quaternion), Marshal.SizeOf ()); - Assert.AreEqual (sizeof (Quaterniond), Marshal.SizeOf ()); - - Assert.AreEqual (sizeof (Vector2), Marshal.SizeOf ()); - Assert.AreEqual (sizeof (Vector3), Marshal.SizeOf ()); - Assert.AreEqual (sizeof (Vector4), Marshal.SizeOf ()); - Assert.AreEqual (sizeof (Vector2d), Marshal.SizeOf ()); - Assert.AreEqual (sizeof (Vector3d), Marshal.SizeOf ()); - Assert.AreEqual (sizeof (Vector4d), Marshal.SizeOf ()); + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (Matrix4))); + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (Matrix4d))); + + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (Quaternion))); + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (Quaterniond))); + + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (Vector2))); + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (Vector3))); + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (Vector4))); + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (Vector2d))); + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (Vector3d))); + Assert.That (Marshal.SizeOf (), Is.EqualTo (sizeof (Vector4d))); } } diff --git a/tests/monotouch-test/ModelIO/MDLLight.cs b/tests/monotouch-test/ModelIO/MDLLight.cs index c308bb00e66d..2ac86da883c1 100644 --- a/tests/monotouch-test/ModelIO/MDLLight.cs +++ b/tests/monotouch-test/ModelIO/MDLLight.cs @@ -36,12 +36,12 @@ public void IrradianceAtPointTest () { using (var obj = new MDLLight ()) { var color = obj.GetIrradiance (new Vector3 (1, 2, 3)); - Assert.IsNotNull (color, "color 1"); + Assert.That (color, Is.Not.Null, "color 1"); } using (var obj = new MDLLight ()) { var color = obj.GetIrradiance (new Vector3 (1, 2, 3), CGColorSpace.CreateGenericRgb ()); - Assert.IsNotNull (color, "color 2"); + Assert.That (color, Is.Not.Null, "color 2"); } } } diff --git a/tests/monotouch-test/ModelIO/MDLMaterialProperty.cs b/tests/monotouch-test/ModelIO/MDLMaterialProperty.cs index 7ce105d70243..03afb27fd4aa 100644 --- a/tests/monotouch-test/ModelIO/MDLMaterialProperty.cs +++ b/tests/monotouch-test/ModelIO/MDLMaterialProperty.cs @@ -52,18 +52,18 @@ public void Ctors () NSUrl url; using (var obj = new MDLMaterialProperty ("name", MDLMaterialSemantic.AmbientOcclusion)) { - Assert.AreEqual (MDLMaterialSemantic.AmbientOcclusion, obj.Semantic, "1 Semantic"); - Assert.IsNull (obj.Color, "1 Color"); + Assert.That (obj.Semantic, Is.EqualTo (MDLMaterialSemantic.AmbientOcclusion), "1 Semantic"); + Assert.That (obj.Color, Is.Null, "1 Color"); Asserts.AreEqual (Vector2.Zero, obj.Float2Value, "1 Float2Value"); Asserts.AreEqual (Vector3.Zero, obj.Float3Value, "1 Float3Value"); Asserts.AreEqual (Vector4.Zero, obj.Float4Value, "1 Float4Value"); - Assert.AreEqual (0.0f, obj.FloatValue, "1 FloatValue"); + Assert.That (obj.FloatValue, Is.EqualTo (0.0f), "1 FloatValue"); Asserts.AreEqual (Matrix4.Identity, obj.Matrix4x4, "1 Matrix4x4"); - Assert.AreEqual ("name", obj.Name, "1 Name"); - Assert.IsNull (obj.StringValue, "1 StringValue"); - Assert.IsNull (obj.TextureSamplerValue, "1 TextureSamplerValue"); - Assert.AreEqual (MDLMaterialPropertyType.Float, obj.Type, "1 Type"); - Assert.IsNull (obj.UrlValue, "1 UrlValue"); + Assert.That (obj.Name, Is.EqualTo ("name"), "1 Name"); + Assert.That (obj.StringValue, Is.Null, "1 StringValue"); + Assert.That (obj.TextureSamplerValue, Is.Null, "1 TextureSamplerValue"); + Assert.That (obj.Type, Is.EqualTo (MDLMaterialPropertyType.Float), "1 Type"); + Assert.That (obj.UrlValue, Is.Null, "1 UrlValue"); V2 = new Vector2 (1, 2); V3 = new Vector3 (3, 4, 5); @@ -73,10 +73,10 @@ public void Ctors () url = new NSUrl ("http://xamarin.com"); obj.Semantic = MDLMaterialSemantic.Anisotropic; - Assert.AreEqual (MDLMaterialSemantic.Anisotropic, obj.Semantic, "2 Semantic"); + Assert.That (obj.Semantic, Is.EqualTo (MDLMaterialSemantic.Anisotropic), "2 Semantic"); obj.Color = UIColor.Blue.CGColor; - Assert.AreEqual (UIColor.Blue.CGColor.ToString (), obj.Color.ToString (), "2 Color"); + Assert.That (obj.Color.ToString (), Is.EqualTo (UIColor.Blue.CGColor.ToString ()), "2 Color"); obj.Float2Value = V2; Asserts.AreEqual (V2, obj.Float2Value, "2 Float2Value"); @@ -88,7 +88,7 @@ public void Ctors () Asserts.AreEqual (V4, obj.Float4Value, "2 Float4Value"); obj.FloatValue = 3.14f; - Assert.AreEqual (3.14f, obj.FloatValue, "2 FloatValue"); + Assert.That (obj.FloatValue, Is.EqualTo (3.14f), "2 FloatValue"); obj.Matrix4x4 = M4; // It looks like the Matrix4 setter is ignored, assigning a matrix @@ -96,28 +96,28 @@ public void Ctors () Asserts.AreEqual (Matrix4.Identity, obj.Matrix4x4, "2 Matrix4x4"); obj.Name = "new name"; - Assert.AreEqual ("new name", obj.Name, "2 Name"); + Assert.That (obj.Name, Is.EqualTo ("new name"), "2 Name"); obj.StringValue = "string value"; - Assert.AreEqual ("string value", obj.StringValue, "2 StringValue"); + Assert.That (obj.StringValue, Is.EqualTo ("string value"), "2 StringValue"); obj.TextureSamplerValue = tsv; - Assert.AreEqual (tsv.Handle, obj.TextureSamplerValue.Handle, "2 TextureSamplerValue"); + Assert.That (obj.TextureSamplerValue.Handle, Is.EqualTo (tsv.Handle), "2 TextureSamplerValue"); - Assert.AreEqual (MDLMaterialPropertyType.Texture, obj.Type, "2 Type"); + Assert.That (obj.Type, Is.EqualTo (MDLMaterialPropertyType.Texture), "2 Type"); // Looks like the URLValue can't change after construction obj.UrlValue = url; if (TestRuntime.CheckXcodeVersion (9, 0)) { - Assert.AreSame (url, obj.UrlValue, "2 UrlValue"); + Assert.That (obj.UrlValue, Is.SameAs (url), "2 UrlValue"); } else { - Assert.IsNull (obj.UrlValue, "2 UrlValue"); + Assert.That (obj.UrlValue, Is.Null, "2 UrlValue"); } } using (var obj = new MDLMaterialProperty ("name", MDLMaterialSemantic.AmbientOcclusion, url)) { - Assert.AreEqual (url.Handle, obj.UrlValue.Handle, "3 UrlValue"); + Assert.That (obj.UrlValue.Handle, Is.EqualTo (url.Handle), "3 UrlValue"); } using (var obj = new MDLMaterialProperty ("name", MDLMaterialSemantic.AmbientOcclusion, V3)) { @@ -125,11 +125,11 @@ public void Ctors () } using (var obj = new MDLMaterialProperty ("name", MDLMaterialSemantic.AmbientOcclusion, tsv)) { - Assert.AreEqual (tsv.Handle, obj.TextureSamplerValue.Handle, "5 TextureSamplerValue"); + Assert.That (obj.TextureSamplerValue.Handle, Is.EqualTo (tsv.Handle), "5 TextureSamplerValue"); } using (var obj = new MDLMaterialProperty ("name", MDLMaterialSemantic.AmbientOcclusion, "string value")) { - Assert.AreEqual ("string value", obj.StringValue, "6 StringValue"); + Assert.That (obj.StringValue, Is.EqualTo ("string value"), "6 StringValue"); } using (var obj = new MDLMaterialProperty ("name", MDLMaterialSemantic.AmbientOcclusion, M4)) { @@ -143,7 +143,7 @@ public void Ctors () } using (var obj = new MDLMaterialProperty ("name", MDLMaterialSemantic.AmbientOcclusion, UIColor.Red.CGColor)) { - Assert.AreEqual (UIColor.Blue.CGColor.ToString (), obj.Color.ToString (), "9 Color"); + Assert.That (obj.Color.ToString (), Is.EqualTo (UIColor.Blue.CGColor.ToString ()), "9 Color"); } using (var obj = new MDLMaterialProperty ("name", MDLMaterialSemantic.AmbientOcclusion, V2)) { @@ -151,7 +151,7 @@ public void Ctors () } using (var obj = new MDLMaterialProperty ("name", MDLMaterialSemantic.AmbientOcclusion, 3.1415f)) { - Assert.AreEqual (3.1415f, obj.FloatValue, "11 FloatValue"); + Assert.That (obj.FloatValue, Is.EqualTo (3.1415f), "11 FloatValue"); } } @@ -160,7 +160,7 @@ public void Copy () { TestRuntime.AssertXcodeVersion (8, 0); using (var obj = new MDLMaterialProperty ("name", MDLMaterialSemantic.AmbientOcclusion)) { - Assert.IsNotNull (obj.Copy ()); + Assert.That (obj.Copy (), Is.Not.Null); } } } diff --git a/tests/monotouch-test/ModelIO/MDLMesh.cs b/tests/monotouch-test/ModelIO/MDLMesh.cs index 243bdae1fc8e..d5ebc11ad71a 100644 --- a/tests/monotouch-test/ModelIO/MDLMesh.cs +++ b/tests/monotouch-test/ModelIO/MDLMesh.cs @@ -36,13 +36,13 @@ public void CreateBoxWithDimensonTest () Vector3i V3i = new Vector3i (4, 5, 6); using (var obj = MDLMesh.CreateBox (V3, V3i, MDLGeometryType.Triangles, true, null)) { - Assert.IsNotNull (obj, "obj"); + Assert.That (obj, Is.Not.Null, "obj"); Asserts.AreEqual (new MDLAxisAlignedBoundingBox { MaxBounds = new Vector3 (0.5f, 1, 1.5f), MinBounds = new Vector3 (-0.5f, -1, -1.5f) }, obj.BoundingBox, "BoundingBox"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); - Assert.AreEqual (1, obj.VertexBuffers.Length, "VertexBuffers Count"); - Assert.AreEqual (TestRuntime.CheckXcodeVersion (7, 3) ? (nuint) 214 : (nuint) 24, obj.VertexCount, "VertexCount"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); + Assert.That (obj.VertexBuffers.Length, Is.EqualTo (1), "VertexBuffers Count"); + Assert.That (obj.VertexCount, Is.EqualTo (TestRuntime.CheckXcodeVersion (7, 3) ? (nuint) 214 : (nuint) 24), "VertexCount"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -55,13 +55,13 @@ public void CreateBoxWithExtentTest () Vector3i V3i = new Vector3i (4, 5, 6); using (var obj = MDLMesh.CreateBox (V3, V3i, MDLGeometryType.Triangles, true, null, MDLMesh.MDLMeshVectorType.Extent)) { - Assert.IsNotNull (obj, "obj"); + Assert.That (obj, Is.Not.Null, "obj"); Asserts.AreEqual (new MDLAxisAlignedBoundingBox { MaxBounds = new Vector3 (0.5f, 1, 1.5f), MinBounds = new Vector3 (-0.5f, -1, -1.5f) }, obj.BoundingBox, "BoundingBox"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); - Assert.AreEqual (1, obj.VertexBuffers.Length, "VertexBuffers Count"); - Assert.AreEqual (TestRuntime.CheckXcodeVersion (7, 3) ? (nuint) 214 : (nuint) 24, obj.VertexCount, "VertexCount"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); + Assert.That (obj.VertexBuffers.Length, Is.EqualTo (1), "VertexBuffers Count"); + Assert.That (obj.VertexCount, Is.EqualTo (TestRuntime.CheckXcodeVersion (7, 3) ? (nuint) 214 : (nuint) 24), "VertexCount"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -72,13 +72,13 @@ public void CreatePlaneTest () var V2i = new Vector2i (3, 3); using (var obj = MDLMesh.CreatePlane (V2, V2i, MDLGeometryType.Triangles, null)) { - Assert.IsNotNull (obj, "obj"); + Assert.That (obj, Is.Not.Null, "obj"); Asserts.AreEqual (new MDLAxisAlignedBoundingBox { MaxBounds = new Vector3 (1.5f, 0, 1.5f), MinBounds = new Vector3 (-1.5f, 0, -1.5f) }, obj.BoundingBox, "BoundingBox"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); Assert.That (obj.VertexBuffers.Length, Is.GreaterThanOrEqualTo (1), "VertexBuffers Count"); - Assert.AreEqual ((nuint) 16, obj.VertexCount, "VertexCount"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.VertexCount, Is.EqualTo ((nuint) 16), "VertexCount"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -88,13 +88,13 @@ public void CreateEllipsoidTest () Vector3 V3 = new Vector3 (1, 1, 1); using (var obj = MDLMesh.CreateEllipsoid (V3, 3, 3, MDLGeometryType.Triangles, true, true, null)) { - Assert.IsNotNull (obj, "obj"); + Assert.That (obj, Is.Not.Null, "obj"); Asserts.AreEqual (new MDLAxisAlignedBoundingBox { MaxBounds = new Vector3 (0.866025448f, 1f, 0.75f), MinBounds = new Vector3 (-0.433012784f, 0.49999997f, -0.75000006f) }, obj.BoundingBox, "BoundingBox"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); - Assert.AreEqual (1, obj.VertexBuffers.Length, "VertexBuffers Count"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); + Assert.That (obj.VertexBuffers.Length, Is.EqualTo (1), "VertexBuffers Count"); Assert.That (obj.VertexCount, Is.GreaterThanOrEqualTo ((nuint) 9), "VertexCount"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -104,7 +104,7 @@ public void CreateCylindroidTest () var V2 = new Vector2 (1, 1); using (var obj = MDLMesh.CreateCylindroid (1, V2, 3, 1, MDLGeometryType.Triangles, true, null)) { - Assert.IsNotNull (obj, "obj"); + Assert.That (obj, Is.Not.Null, "obj"); #if MONOMAC Asserts.AreEqual (new MDLAxisAlignedBoundingBox { MaxBounds = new Vector3 (0.866025448f, 0.5f, 1f), MinBounds = new Vector3 (-0.866025388f, -0.5f, -0.5f) }, obj.BoundingBox, "BoundingBox"); #else @@ -117,10 +117,10 @@ public void CreateCylindroidTest () } #endif Assert.That (obj.VertexBuffers.Length, Is.GreaterThanOrEqualTo (1), "VertexBuffers Count"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); - Assert.AreEqual ((nuint) 18, obj.VertexCount, "VertexCount"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); + Assert.That (obj.VertexCount, Is.EqualTo ((nuint) 18), "VertexCount"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -133,12 +133,12 @@ public void CreateCylinderTest () var V2i = new Vector2i (3, 3); using (var obj = MDLMesh.CreateCylinder (V3, V2i, true, true, true, MDLGeometryType.Triangles, null)) { - Assert.IsNotNull (obj, "obj"); + Assert.That (obj, Is.Not.Null, "obj"); Assert.That (obj.VertexBuffers.Length, Is.GreaterThanOrEqualTo (1), "VertexBuffers Length"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); - Assert.AreEqual ((nuint) 26, obj.VertexCount, "VertexCount"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); + Assert.That (obj.VertexCount, Is.EqualTo ((nuint) 26), "VertexCount"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -148,12 +148,12 @@ public void CreateEllipticalConeTest () var V2 = new Vector2 (1, 1); using (var obj = MDLMesh.CreateEllipticalCone (5, V2, 3, 1, MDLGeometryType.Triangles, true, null)) { - Assert.IsNotNull (obj, "obj"); + Assert.That (obj, Is.Not.Null, "obj"); Assert.That (obj.VertexBuffers.Length, Is.GreaterThanOrEqualTo (1), "VertexBuffers Length"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); - Assert.AreEqual ((nuint) 13, obj.VertexCount, "VertexCount"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); + Assert.That (obj.VertexCount, Is.EqualTo ((nuint) 13), "VertexCount"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -166,13 +166,13 @@ public void CreateSphereTest () Vector2i V2i = new Vector2i (4, 5); using (var obj = MDLMesh.CreateSphere (V3, V2i, MDLGeometryType.Triangles, true, null)) { - Assert.IsNotNull (obj, "obj"); + Assert.That (obj, Is.Not.Null, "obj"); Asserts.AreEqual (new MDLAxisAlignedBoundingBox { MaxBounds = new Vector3 (0.9510565f, 2, 2.85317f), MinBounds = new Vector3 (-0.9510565f, -2, -2.85317f) }, obj.BoundingBox, "BoundingBox"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); - Assert.AreEqual (1, obj.VertexBuffers.Length, "VertexBuffers Count"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); + Assert.That (obj.VertexBuffers.Length, Is.EqualTo (1), "VertexBuffers Count"); Assert.That (obj.VertexCount, Is.GreaterThanOrEqualTo ((nuint) 22), "VertexCount"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -185,13 +185,13 @@ public void CreateHemisphereTest () Vector2i V2i = new Vector2i (4, 5); using (var obj = MDLMesh.CreateHemisphere (V3, V2i, MDLGeometryType.Triangles, true, true, null)) { - Assert.IsNotNull (obj, "obj"); + Assert.That (obj, Is.Not.Null, "obj"); Asserts.AreEqual (new MDLAxisAlignedBoundingBox { MaxBounds = new Vector3 (0.9510565f, 2, 2.85317f), MinBounds = new Vector3 (-0.9510565f, 0.6180339f, -2.85317f) }, obj.BoundingBox, "BoundingBox"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); - Assert.AreEqual (1, obj.VertexBuffers.Length, "VertexBuffers Count"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); + Assert.That (obj.VertexBuffers.Length, Is.EqualTo (1), "VertexBuffers Count"); Assert.That (obj.VertexCount, Is.GreaterThanOrEqualTo ((nuint) 16), "VertexCount"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -204,12 +204,12 @@ public void CreateCapsuleTest () Vector2i V2i = new Vector2i (4, 5); using (var obj = MDLMesh.CreateCapsule (V3, V2i, MDLGeometryType.Triangles, true, 10, null)) { - Assert.IsNotNull (obj, "obj"); + Assert.That (obj, Is.Not.Null, "obj"); Assert.That (obj.VertexCount, Is.GreaterThanOrEqualTo ((nuint) 122), "VertexCount"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); Assert.That (obj.VertexBuffers.Length, Is.GreaterThanOrEqualTo (1), "VertexBuffers Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -222,12 +222,12 @@ public void CreateConeTest () Vector2i V2i = new Vector2i (4, 5); using (var obj = MDLMesh.CreateCone (V3, V2i, MDLGeometryType.Triangles, true, true, null)) { - Assert.IsNotNull (obj, "obj"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); + Assert.That (obj, Is.Not.Null, "obj"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); Assert.That (obj.VertexBuffers.Length, Is.GreaterThanOrEqualTo (1), "VertexBuffers Count"); - Assert.AreEqual ((nuint) 36, obj.VertexCount, "VertexCount"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.VertexCount, Is.EqualTo ((nuint) 36), "VertexCount"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -240,12 +240,12 @@ public void CreatePaneTest () Vector2i V2i = new Vector2i (4, 5); using (var obj = MDLMesh.CreatePlane (V3, V2i, MDLGeometryType.Triangles, null)) { - Assert.IsNotNull (obj, "obj"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); + Assert.That (obj, Is.Not.Null, "obj"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); Assert.That (obj.VertexBuffers.Length, Is.GreaterThanOrEqualTo (1), "VertexBuffers Count"); - Assert.AreEqual ((nuint) 30, obj.VertexCount, "VertexCount"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.VertexCount, Is.EqualTo ((nuint) 30), "VertexCount"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -257,12 +257,12 @@ public void CreateIcosahedronTest () Vector3 V3 = new Vector3 (1, 2, 3); using (var obj = MDLMesh.CreateIcosahedron (V3, true, MDLGeometryType.Triangles, null)) { - Assert.IsNotNull (obj, "obj"); - Assert.AreEqual ((nuint) 1, obj.Submeshes.Count, "Submeshes Count"); + Assert.That (obj, Is.Not.Null, "obj"); + Assert.That (obj.Submeshes.Count, Is.EqualTo ((nuint) 1), "Submeshes Count"); Assert.That (obj.VertexBuffers.Length, Is.GreaterThanOrEqualTo (1), "VertexBuffers Count"); - Assert.AreEqual ((nuint) 12, obj.VertexCount, "VertexCount"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Attributes.Count, "VertexDescriptor Attributes Count"); - Assert.AreEqual ((nuint) 31, obj.VertexDescriptor.Layouts.Count, "VertexDescriptor Layouts Count"); + Assert.That (obj.VertexCount, Is.EqualTo ((nuint) 12), "VertexCount"); + Assert.That (obj.VertexDescriptor.Attributes.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Attributes Count"); + Assert.That (obj.VertexDescriptor.Layouts.Count, Is.EqualTo ((nuint) 31), "VertexDescriptor Layouts Count"); } } @@ -274,7 +274,7 @@ public void CreateIcosahedronTest () // var V2i = new Vector2i (1, 2); // // using (var obj = MDLMesh.CreateEllipticalCone (5, V2, 3, 1, MDLGeometryKind.Triangles, true, null)) { - // Assert.IsTrue (obj.GenerateAmbientOcclusionTexture (V2i, 1, 1, new MDLObject[] { }, "vname", "mname"), "GenerateAmbientOcclusionTexture"); + // Assert.That (obj.GenerateAmbientOcclusionTexture (V2i, 1, 1, new MDLObject[] { }, "vname", "mname"), Is.True, "GenerateAmbientOcclusionTexture"); // } // } // @@ -286,7 +286,7 @@ public void CreateIcosahedronTest () // var V2i = new Vector2i (1, 2); // // using (var obj = MDLMesh.CreateEllipticalCone (5, V2, 3, 1, MDLGeometryKind.Triangles, true, null)) { - // Assert.IsTrue (obj.GenerateLightMapTexture (V2i, new MDLLight[] {}, new MDLObject[] { }, "vname", "mname"), "GenerateLightMapTexture"); + // Assert.That (obj.GenerateLightMapTexture (V2i, new MDLLight[] {}, new MDLObject[] { }, "vname", "mname"), Is.True, "GenerateLightMapTexture"); // } // } } diff --git a/tests/monotouch-test/ModelIO/MDLObject.cs b/tests/monotouch-test/ModelIO/MDLObject.cs index 8aca264eb9da..c6b0a4368e0c 100644 --- a/tests/monotouch-test/ModelIO/MDLObject.cs +++ b/tests/monotouch-test/ModelIO/MDLObject.cs @@ -41,7 +41,7 @@ public void ProtocolTest () using (var obj = new MDLObject ()) { var p = new Protocol (typeof (IMDLComponent)); obj.SetComponent (new MDLTransform (), p); - Assert.NotNull (obj.GetComponent (p)); + Assert.That (obj.GetComponent (p), Is.Not.Null); } } } diff --git a/tests/monotouch-test/ModelIO/MDLStereoscopicCameraTest.cs b/tests/monotouch-test/ModelIO/MDLStereoscopicCameraTest.cs index b1b58a72350c..fa69cb3c37e5 100644 --- a/tests/monotouch-test/ModelIO/MDLStereoscopicCameraTest.cs +++ b/tests/monotouch-test/ModelIO/MDLStereoscopicCameraTest.cs @@ -40,10 +40,10 @@ public void Setup () public void Properties () { using (var obj = new MDLStereoscopicCamera ()) { - Assert.AreEqual (63f, obj.InterPupillaryDistance, "InterPupillaryDistance"); - Assert.AreEqual (0f, obj.LeftVergence, "LeftVergence"); - Assert.AreEqual (0f, obj.RightVergence, "RightVergence"); - Assert.AreEqual (0f, obj.Overlap, "Overlap"); + Assert.That (obj.InterPupillaryDistance, Is.EqualTo (63f), "InterPupillaryDistance"); + Assert.That (obj.LeftVergence, Is.EqualTo (0f), "LeftVergence"); + Assert.That (obj.RightVergence, Is.EqualTo (0f), "RightVergence"); + Assert.That (obj.Overlap, Is.EqualTo (0f), "Overlap"); var mat1 = new Matrix4 ( 1, 0, 0, -0.63f, diff --git a/tests/monotouch-test/ModelIO/MDLTexture.cs b/tests/monotouch-test/ModelIO/MDLTexture.cs index 6299fa3e7bb5..3520aef046e8 100644 --- a/tests/monotouch-test/ModelIO/MDLTexture.cs +++ b/tests/monotouch-test/ModelIO/MDLTexture.cs @@ -45,14 +45,14 @@ public void CreateIrradianceTextureCubeTest_a () using (var obj = new MDLTexture ()) { using (var txt = MDLTexture.CreateIrradianceTextureCube (obj, "name", V2)) { if (TestRuntime.CheckXcodeVersion (8, 0)) { - Assert.IsNull (txt, "Is Null"); // this is probably because the arguments to CreateIrradianceTextureCube are invalid, but I haven't been able to figure out valid values. + Assert.That (txt, Is.Null, "Is Null"); // this is probably because the arguments to CreateIrradianceTextureCube are invalid, but I haven't been able to figure out valid values. } else { - Assert.IsNotNull (txt, "Ain't Null"); - Assert.AreEqual ((nuint) 4, txt.ChannelCount, "ChannelCount"); - Assert.AreEqual (MDLTextureChannelEncoding.UInt8, txt.ChannelEncoding, "ChannelEncoding"); - Assert.AreEqual (new Vector2i (3, 18), txt.Dimensions, "Dimensions"); - Assert.AreEqual ((nuint) 2, txt.MipLevelCount, "MipLevelCount"); - Assert.AreEqual ((nint) 12, txt.RowStride, "RowStride"); + Assert.That (txt, Is.Not.Null, "Ain't Null"); + Assert.That (txt.ChannelCount, Is.EqualTo ((nuint) 4), "ChannelCount"); + Assert.That (txt.ChannelEncoding, Is.EqualTo (MDLTextureChannelEncoding.UInt8), "ChannelEncoding"); + Assert.That (txt.Dimensions, Is.EqualTo (new Vector2i (3, 18)), "Dimensions"); + Assert.That (txt.MipLevelCount, Is.EqualTo ((nuint) 2), "MipLevelCount"); + Assert.That (txt.RowStride, Is.EqualTo ((nint) 12), "RowStride"); } } } @@ -66,14 +66,14 @@ public void CreateIrradianceTextureCubeTest_b () using (var obj = new MDLTexture ()) { using (var txt = MDLTexture.CreateIrradianceTextureCube (obj, "name", V2, 0.1234f)) { if (TestRuntime.CheckXcodeVersion (8, 0)) { - Assert.IsNull (txt, "Is Null"); // this is probably because the arguments to CreateIrradianceTextureCube are invalid, but I haven't been able to figure out valid values. + Assert.That (txt, Is.Null, "Is Null"); // this is probably because the arguments to CreateIrradianceTextureCube are invalid, but I haven't been able to figure out valid values. } else { - Assert.IsNotNull (txt, "Ain't Null"); - Assert.AreEqual ((nuint) 4, txt.ChannelCount, "ChannelCount"); - Assert.AreEqual (MDLTextureChannelEncoding.UInt8, txt.ChannelEncoding, "ChannelEncoding"); - Assert.AreEqual (new Vector2i (3, 18), txt.Dimensions, "Dimensions"); - Assert.AreEqual ((nuint) 1, txt.MipLevelCount, "MipLevelCount"); - Assert.AreEqual ((nint) 12, txt.RowStride, "RowStride"); + Assert.That (txt, Is.Not.Null, "Ain't Null"); + Assert.That (txt.ChannelCount, Is.EqualTo ((nuint) 4), "ChannelCount"); + Assert.That (txt.ChannelEncoding, Is.EqualTo (MDLTextureChannelEncoding.UInt8), "ChannelEncoding"); + Assert.That (txt.Dimensions, Is.EqualTo (new Vector2i (3, 18)), "Dimensions"); + Assert.That (txt.MipLevelCount, Is.EqualTo ((nuint) 1), "MipLevelCount"); + Assert.That (txt.RowStride, Is.EqualTo ((nint) 12), "RowStride"); } } } diff --git a/tests/monotouch-test/ModelIO/MDLVertexAttribute.cs b/tests/monotouch-test/ModelIO/MDLVertexAttribute.cs index 9cbfcfc5c750..67917cf374a7 100644 --- a/tests/monotouch-test/ModelIO/MDLVertexAttribute.cs +++ b/tests/monotouch-test/ModelIO/MDLVertexAttribute.cs @@ -34,10 +34,10 @@ public void Setup () public void Ctors () { using (var obj = new MDLVertexAttribute ("name", MDLVertexFormat.Float3, 1, 2)) { - Assert.AreEqual ("name", obj.Name, "Name"); - Assert.AreEqual (MDLVertexFormat.Float3, obj.Format, "Format"); - Assert.AreEqual ((nuint) 1, obj.Offset, "Offset"); - Assert.AreEqual ((nuint) 2, obj.BufferIndex, "BufferIndex"); + Assert.That (obj.Name, Is.EqualTo ("name"), "Name"); + Assert.That (obj.Format, Is.EqualTo (MDLVertexFormat.Float3), "Format"); + Assert.That (obj.Offset, Is.EqualTo ((nuint) 1), "Offset"); + Assert.That (obj.BufferIndex, Is.EqualTo ((nuint) 2), "BufferIndex"); Asserts.AreEqual (new Vector4 (0, 0, 0, 1), obj.InitializationValue, "InitializationValue"); } } @@ -49,16 +49,16 @@ public void Properties () using (var obj = new MDLVertexAttribute ("name", MDLVertexFormat.Float3, 1, 2)) { obj.Name = "new name"; - Assert.AreEqual ("new name", obj.Name, "Name"); + Assert.That (obj.Name, Is.EqualTo ("new name"), "Name"); obj.Format = MDLVertexFormat.Float2; - Assert.AreEqual (MDLVertexFormat.Float2, obj.Format, "Format"); + Assert.That (obj.Format, Is.EqualTo (MDLVertexFormat.Float2), "Format"); obj.Offset = 4; - Assert.AreEqual ((nuint) 4, obj.Offset, "Offset"); + Assert.That (obj.Offset, Is.EqualTo ((nuint) 4), "Offset"); obj.BufferIndex = 9; - Assert.AreEqual ((nuint) 9, obj.BufferIndex, "BufferIndex"); + Assert.That (obj.BufferIndex, Is.EqualTo ((nuint) 9), "BufferIndex"); } using (var obj = new MDLVertexAttribute ("name", MDLVertexFormat.Float3, 1, 2)) { diff --git a/tests/monotouch-test/ModelIO/MDLVoxelArrayTest.cs b/tests/monotouch-test/ModelIO/MDLVoxelArrayTest.cs index df68c869ddcb..1d6c1fcbb79c 100644 --- a/tests/monotouch-test/ModelIO/MDLVoxelArrayTest.cs +++ b/tests/monotouch-test/ModelIO/MDLVoxelArrayTest.cs @@ -47,7 +47,7 @@ public void BoundingBoxTest () new Vector4i (1, 2, 3, 4), new Vector4i (5, 6, 7, 8)); var voxels = obj.GetVoxels (extents); - Assert.IsNull (voxels, "GetVoxels"); + Assert.That (voxels, Is.Null, "GetVoxels"); extents = obj.VoxelIndexExtent; Assert.That (extents.MaximumExtent.X, Is.EqualTo (-1).Or.EqualTo (0), "MaxX"); diff --git a/tests/monotouch-test/MonoMac/AssemblyTest.cs b/tests/monotouch-test/MonoMac/AssemblyTest.cs index 5b244f8b4659..fc3bd25cea27 100644 --- a/tests/monotouch-test/MonoMac/AssemblyTest.cs +++ b/tests/monotouch-test/MonoMac/AssemblyTest.cs @@ -21,7 +21,7 @@ public class AssemblyTest { [Test] public void PublicKeyToken () { - Assert.AreEqual (pkt, typeof (NSObject).Assembly.GetName ().GetPublicKeyToken (), "GetPublicKeyToken"); + Assert.That (typeof (NSObject).Assembly.GetName ().GetPublicKeyToken (), Is.EqualTo (pkt), "GetPublicKeyToken"); } } } diff --git a/tests/monotouch-test/MonoMac/CBUUID.cs b/tests/monotouch-test/MonoMac/CBUUID.cs index 97451bb42ea0..41bb77f18772 100644 --- a/tests/monotouch-test/MonoMac/CBUUID.cs +++ b/tests/monotouch-test/MonoMac/CBUUID.cs @@ -21,7 +21,7 @@ public void Roundtrip_16bits () { using (CBUUID uuid = CBUUID.FromString ("1234")) { Assert.That (uuid.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); - Assert.IsNotNull (uuid.Data, "Data"); + Assert.That (uuid.Data, Is.Not.Null, "Data"); Assert.That (uuid.ToString (false), Is.EqualTo ("1234"), "ToString(false)"); Assert.That (uuid.ToString (true), Is.EqualTo ("00001234-0000-1000-8000-00805f9b34fb"), "ToString(true)"); using (CBUUID u2 = CBUUID.FromString (uuid.ToString ())) { @@ -35,7 +35,7 @@ public void Roundtrip_128bits () { using (CBUUID uuid = CBUUID.FromString ("12345678-90AB-CDEF-cafe-c80c20443d0b")) { Assert.That (uuid.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); - Assert.IsNotNull (uuid.Data, "Data"); + Assert.That (uuid.Data, Is.Not.Null, "Data"); Assert.That (uuid.ToString (false), Is.EqualTo (uuid.ToString (true)), "ToString"); using (CBUUID u2 = CBUUID.FromString (uuid.ToString ())) { Assert.That (u2.ToString (), Is.EqualTo (uuid.ToString ()), "Roundtrip"); diff --git a/tests/monotouch-test/MultipeerConnectivity/PeerIDTest.cs b/tests/monotouch-test/MultipeerConnectivity/PeerIDTest.cs index 8056b18e62b0..b0f6ce497c82 100644 --- a/tests/monotouch-test/MultipeerConnectivity/PeerIDTest.cs +++ b/tests/monotouch-test/MultipeerConnectivity/PeerIDTest.cs @@ -27,7 +27,7 @@ public void Defaults () TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 10, 10, throwIfOtherPlatform: false); using (var peer = new MCPeerID ("MyDisplayName")) { - Assert.AreEqual ("MyDisplayName", peer.DisplayName, "DisplayName"); + Assert.That (peer.DisplayName, Is.EqualTo ("MyDisplayName"), "DisplayName"); } } diff --git a/tests/monotouch-test/MultipeerConnectivity/SessionTest.cs b/tests/monotouch-test/MultipeerConnectivity/SessionTest.cs index 6dd76da9339c..2bc5e8fa2dbf 100644 --- a/tests/monotouch-test/MultipeerConnectivity/SessionTest.cs +++ b/tests/monotouch-test/MultipeerConnectivity/SessionTest.cs @@ -32,8 +32,8 @@ public void CtorPeer () using (var peer = new MCPeerID ("me")) using (var s = new MCSession (peer)) { - Assert.AreSame (s.MyPeerID, peer, "MyPeerID"); - Assert.Null (s.SecurityIdentity, "SecurityIdentity"); + Assert.That (peer, Is.SameAs (s.MyPeerID), "MyPeerID"); + Assert.That (s.SecurityIdentity, Is.Null, "SecurityIdentity"); #if MONOMAC var pref = MCEncryptionPreference.Required; #else @@ -51,8 +51,8 @@ public void Ctor_OptionalIdentity () using (var peer = new MCPeerID ("me")) using (var s = new MCSession (peer, null, MCEncryptionPreference.None)) { - Assert.AreSame (s.MyPeerID, peer, "MyPeerID"); - Assert.Null (s.SecurityIdentity, "SecurityIdentity"); + Assert.That (peer, Is.SameAs (s.MyPeerID), "MyPeerID"); + Assert.That (s.SecurityIdentity, Is.Null, "SecurityIdentity"); Assert.That (s.EncryptionPreference, Is.EqualTo (MCEncryptionPreference.None), "EncryptionPreference"); Assert.That (s.ConnectedPeers, Is.Empty, "ConnectedPeers"); } @@ -66,7 +66,7 @@ public void Ctor_Identity () using (var id = IdentityTest.GetIdentity ()) using (var peer = new MCPeerID ("me")) using (var s = new MCSession (peer, id, MCEncryptionPreference.Required)) { - Assert.AreSame (s.MyPeerID, peer, "MyPeerID"); + Assert.That (peer, Is.SameAs (s.MyPeerID), "MyPeerID"); Assert.That (s.SecurityIdentity.Count, Is.EqualTo ((nuint) 1), "SecurityIdentity"); Assert.That (s.SecurityIdentity.GetItem (0).Handle, Is.EqualTo (id.Handle), "SecurityIdentity"); Assert.That (s.EncryptionPreference, Is.EqualTo (MCEncryptionPreference.Required), "EncryptionPreference"); @@ -88,7 +88,7 @@ public void Ctor_Identity_Certificates () certs [i] = trust [i]; using (var s = new MCSession (peer, id, certs, MCEncryptionPreference.Required)) { - Assert.AreSame (s.MyPeerID, peer, "MyPeerID"); + Assert.That (peer, Is.SameAs (s.MyPeerID), "MyPeerID"); Assert.That (s.SecurityIdentity.Count, Is.EqualTo ((nuint) 2), "SecurityIdentity"); Assert.That (s.SecurityIdentity.GetItem (0).Handle, Is.EqualTo (id.Handle), "SecurityIdentity#0"); Assert.That (s.SecurityIdentity.GetItem (1).Handle, Is.EqualTo (certs [0].Handle), "SecurityIdentity#1"); diff --git a/tests/monotouch-test/NativeTypesTest.cs b/tests/monotouch-test/NativeTypesTest.cs index 06f89bacb62e..08d3d81c9a5b 100644 --- a/tests/monotouch-test/NativeTypesTest.cs +++ b/tests/monotouch-test/NativeTypesTest.cs @@ -53,93 +53,93 @@ public void CompareTo () [Test] public void Equals () { - Assert.IsTrue (((nint) 0).Equals ((nint) 0), "eq nint 1"); - Assert.IsTrue (((nint) 0).Equals ((object) (nint) 0), "eq nint 2"); - Assert.IsFalse (((nint) 0).Equals (null), "eq nint 3"); + Assert.That (((nint) 0).Equals ((nint) 0), Is.True, "eq nint 1"); + Assert.That (((nint) 0).Equals ((object) (nint) 0), Is.True, "eq nint 2"); + Assert.That (((nint) 0).Equals (null), Is.False, "eq nint 3"); - Assert.IsTrue (((nuint) 0).Equals ((nuint) 0), "eq nuint 1"); - Assert.IsTrue (((nuint) 0).Equals ((object) (nuint) 0), "eq nuint 2"); - Assert.IsFalse (((nuint) 0).Equals (null), "eq nuint 3"); + Assert.That (((nuint) 0).Equals ((nuint) 0), Is.True, "eq nuint 1"); + Assert.That (((nuint) 0).Equals ((object) (nuint) 0), Is.True, "eq nuint 2"); + Assert.That (((nuint) 0).Equals (null), Is.False, "eq nuint 3"); - Assert.IsTrue (((nfloat) 0).Equals ((nfloat) 0), "eq nfloat 1"); - Assert.IsTrue (((nfloat) 0).Equals ((object) (nfloat) 0), "eq nfloat 2"); - Assert.IsFalse (((nfloat) 0).Equals (null), "eq nfloat 3"); + Assert.That (((nfloat) 0).Equals ((nfloat) 0), Is.True, "eq nfloat 1"); + Assert.That (((nfloat) 0).Equals ((object) (nfloat) 0), Is.True, "eq nfloat 2"); + Assert.That (((nfloat) 0).Equals (null), Is.False, "eq nfloat 3"); } [Test] public void IsInfinity () { - Assert.IsTrue (nfloat.IsInfinity (nfloat.PositiveInfinity), "PositiveInfinity"); - Assert.IsTrue (nfloat.IsInfinity (nfloat.NegativeInfinity), "NegativeInfinity"); - Assert.IsTrue (!nfloat.IsInfinity (12), "12"); - Assert.IsTrue (!nfloat.IsInfinity (nfloat.NaN), "NaN"); + Assert.That (nfloat.IsInfinity (nfloat.PositiveInfinity), Is.True, "PositiveInfinity"); + Assert.That (nfloat.IsInfinity (nfloat.NegativeInfinity), Is.True, "NegativeInfinity"); + Assert.That (!nfloat.IsInfinity (12), Is.True, "12"); + Assert.That (!nfloat.IsInfinity (nfloat.NaN), Is.True, "NaN"); } [Test] public void IsNan () { - Assert.IsTrue (nfloat.IsNaN (nfloat.NaN), "Nan"); - Assert.IsTrue (!nfloat.IsNaN (12), "12"); - Assert.IsTrue (!nfloat.IsNaN (nfloat.PositiveInfinity), "PositiveInfinity"); - Assert.IsTrue (!nfloat.IsNaN (nfloat.PositiveInfinity), "NegativeInfinity"); + Assert.That (nfloat.IsNaN (nfloat.NaN), Is.True, "Nan"); + Assert.That (!nfloat.IsNaN (12), Is.True, "12"); + Assert.That (!nfloat.IsNaN (nfloat.PositiveInfinity), Is.True, "PositiveInfinity"); + Assert.That (!nfloat.IsNaN (nfloat.PositiveInfinity), Is.True, "NegativeInfinity"); } [Test] public void IsNegativeInfinity () { - Assert.IsTrue (nfloat.IsNegativeInfinity (nfloat.NegativeInfinity), "IsNegativeInfinity"); - Assert.IsTrue (!nfloat.IsNegativeInfinity (12), "12"); - Assert.IsTrue (!nfloat.IsNegativeInfinity (nfloat.NaN), "NaN"); + Assert.That (nfloat.IsNegativeInfinity (nfloat.NegativeInfinity), Is.True, "IsNegativeInfinity"); + Assert.That (!nfloat.IsNegativeInfinity (12), Is.True, "12"); + Assert.That (!nfloat.IsNegativeInfinity (nfloat.NaN), Is.True, "NaN"); } [Test] public void IsPositiveInfinity () { - Assert.IsTrue (nfloat.IsPositiveInfinity (nfloat.PositiveInfinity), "PositiveInfinity"); - Assert.IsTrue (!nfloat.IsPositiveInfinity (12), "12"); - Assert.IsTrue (!nfloat.IsPositiveInfinity (nfloat.NaN), "NaN"); + Assert.That (nfloat.IsPositiveInfinity (nfloat.PositiveInfinity), Is.True, "PositiveInfinity"); + Assert.That (!nfloat.IsPositiveInfinity (12), Is.True, "12"); + Assert.That (!nfloat.IsPositiveInfinity (nfloat.NaN), Is.True, "NaN"); } [Test] public void PositiveInfinity_Cast () { float f = float.PositiveInfinity; - Assert.IsTrue (float.IsPositiveInfinity (f), "float PositiveInfinity"); + Assert.That (float.IsPositiveInfinity (f), Is.True, "float PositiveInfinity"); nfloat n = (nfloat) f; // no-op on 32 bits arch - Assert.IsTrue (nfloat.IsPositiveInfinity (n), "nfloat PositiveInfinity 1"); + Assert.That (nfloat.IsPositiveInfinity (n), Is.True, "nfloat PositiveInfinity 1"); double d = double.PositiveInfinity; - Assert.IsTrue (double.IsPositiveInfinity (d), "double PositiveInfinity"); + Assert.That (double.IsPositiveInfinity (d), Is.True, "double PositiveInfinity"); n = (nfloat) d; // no-op on 64 bits arch - Assert.IsTrue (nfloat.IsPositiveInfinity (n), "nfloat PositiveInfinity 2"); + Assert.That (nfloat.IsPositiveInfinity (n), Is.True, "nfloat PositiveInfinity 2"); } [Test] public void NegativeInfinity_Cast () { float f = float.NegativeInfinity; - Assert.IsTrue (float.IsNegativeInfinity (f), "float NegativeInfinity"); + Assert.That (float.IsNegativeInfinity (f), Is.True, "float NegativeInfinity"); nfloat n = (nfloat) f; // no-op on 32 bits arch - Assert.IsTrue (nfloat.IsNegativeInfinity (n), "nfloat NegativeInfinity 1"); + Assert.That (nfloat.IsNegativeInfinity (n), Is.True, "nfloat NegativeInfinity 1"); double d = double.NegativeInfinity; - Assert.IsTrue (double.IsNegativeInfinity (d), "double NegativeInfinity"); + Assert.That (double.IsNegativeInfinity (d), Is.True, "double NegativeInfinity"); n = (nfloat) d; // no-op on 64 bits arch - Assert.IsTrue (nfloat.IsNegativeInfinity (n), "nfloat NegativeInfinity 2"); + Assert.That (nfloat.IsNegativeInfinity (n), Is.True, "nfloat NegativeInfinity 2"); } [Test] public void NaN_Cast () { float f = float.NaN; - Assert.IsTrue (float.IsNaN (f), "float NaN"); + Assert.That (float.IsNaN (f), Is.True, "float NaN"); nfloat n = (nfloat) f; // no-op on 32 bits arch - Assert.IsTrue (nfloat.IsNaN (n), "nfloat NaN 1"); + Assert.That (nfloat.IsNaN (n), Is.True, "nfloat NaN 1"); double d = double.NaN; - Assert.IsTrue (double.IsNaN (d), "double NaN"); + Assert.That (double.IsNaN (d), Is.True, "double NaN"); n = (nfloat) d; // no-op on 64 bits arch - Assert.IsTrue (nfloat.IsNaN (n), "nfloat NaN 2"); + Assert.That (nfloat.IsNaN (n), Is.True, "nfloat NaN 2"); } } } diff --git a/tests/monotouch-test/NaturalLanguage/EmbeddingTest.cs b/tests/monotouch-test/NaturalLanguage/EmbeddingTest.cs index 1f8d62f75b31..0f8fb74bae96 100644 --- a/tests/monotouch-test/NaturalLanguage/EmbeddingTest.cs +++ b/tests/monotouch-test/NaturalLanguage/EmbeddingTest.cs @@ -33,10 +33,10 @@ public void Vector () NLEmbedding e = null; Assert.DoesNotThrow (() => e = NLEmbedding.GetWordEmbedding (v), $"Throws: {v}"); if (e is not null) { - Assert.NotNull (e, "GetWordEmbedding"); - Assert.Null (e.GetVector ("Xamarin"), "GetVector"); - Assert.False (e.TryGetVector ("Xamarin", out var vector), "TryGetVector"); - Assert.Null (vector, "vector"); + Assert.That (e, Is.Not.Null, "GetWordEmbedding"); + Assert.That (e.GetVector ("Xamarin"), Is.Null, "GetVector"); + Assert.That (e.TryGetVector ("Xamarin", out var vector), Is.False, "TryGetVector"); + Assert.That (vector, Is.Null, "vector"); } } } @@ -57,12 +57,12 @@ public void Write () using (var url = NSUrl.FromFilename (temp)) { var strong = NLEmbedding.Write (vd, NLLanguage.French, 1, url, out var error); - Assert.True (strong, "strong"); - Assert.Null (error, "strong error"); + Assert.That (strong, Is.True, "strong"); + Assert.That (error, Is.Null, "strong error"); var weak = NLEmbedding.Write (wd, NLLanguage.French.GetConstant (), 1, url, out error); - Assert.True (strong, "strong"); - Assert.Null (error, "weak error"); + Assert.That (strong, Is.True, "strong"); + Assert.That (error, Is.Null, "weak error"); } } } diff --git a/tests/monotouch-test/NaturalLanguage/GazetteerTest.cs b/tests/monotouch-test/NaturalLanguage/GazetteerTest.cs index 737ea21fab80..08a72ec5a48b 100644 --- a/tests/monotouch-test/NaturalLanguage/GazetteerTest.cs +++ b/tests/monotouch-test/NaturalLanguage/GazetteerTest.cs @@ -25,11 +25,11 @@ public void Dictionary () Assert.That (wd.Count, Is.EqualTo ((nuint) 2), "Count"); using (var weak = new NLGazetteer (wd, NLLanguage.French.GetConstant (), out var error)) { - Assert.Null (error, "weak error"); + Assert.That (error, Is.Null, "weak error"); } using (var strong = new NLGazetteer (sd, NLLanguage.French, out var error)) { - Assert.Null (error, "strong error"); + Assert.That (error, Is.Null, "strong error"); } } } diff --git a/tests/monotouch-test/NaturalLanguage/NLLanguageRecognizerTest.cs b/tests/monotouch-test/NaturalLanguage/NLLanguageRecognizerTest.cs index 1cd9b0383764..5c2a62fe5fa7 100644 --- a/tests/monotouch-test/NaturalLanguage/NLLanguageRecognizerTest.cs +++ b/tests/monotouch-test/NaturalLanguage/NLLanguageRecognizerTest.cs @@ -26,7 +26,7 @@ public void GetDominantLanguageTest () { var text = "Die Kleinen haben friedlich zusammen gespielt."; var lang = NLLanguageRecognizer.GetDominantLanguage (text); - Assert.AreEqual (NLLanguage.German, lang); + Assert.That (lang, Is.EqualTo (NLLanguage.German)); } [Test] diff --git a/tests/monotouch-test/NaturalLanguage/NLTaggerTest.cs b/tests/monotouch-test/NaturalLanguage/NLTaggerTest.cs index 5c2ebb3bbf4a..8b08bd9698f9 100644 --- a/tests/monotouch-test/NaturalLanguage/NLTaggerTest.cs +++ b/tests/monotouch-test/NaturalLanguage/NLTaggerTest.cs @@ -42,7 +42,7 @@ public void GetTags () var tags = tagger.GetTags (new NSRange (0, Text.Length), NLTokenUnit.Word, NLTagScheme.Lemma, NLTaggerOptions.OmitWhitespace | NLTaggerOptions.OmitPunctuation, out var ranges); Assert.That (tags.Length, Is.EqualTo (ranges.Length), "Length"); foreach (var tag in tags) - Assert.NotNull (tag, tag); + Assert.That (tag, Is.Not.Null, tag.ToString ()); } } @@ -55,7 +55,7 @@ public void GetModels () var constant = ((NLTagScheme) scheme).GetConstant (); if (constant is null) continue; // can vary by SDK version - Assert.That (tagger.GetModels (constant), Is.Empty, constant); + Assert.That (tagger.GetModels (constant), Is.Empty, constant.ToString ()); } } } diff --git a/tests/monotouch-test/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValuesTest.cs b/tests/monotouch-test/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValuesTest.cs index 4a08cb90971a..2cf728ebdb29 100644 --- a/tests/monotouch-test/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValuesTest.cs +++ b/tests/monotouch-test/NearbyInteraction/NIAlgorithmConvergenceStatusReasonValuesTest.cs @@ -21,7 +21,7 @@ public void Setup () public void GetConvergenceStatusReasonTest () { var reason = NIAlgorithmConvergenceStatusReason.InsufficientHorizontalSweep; - Assert.IsNotNull (NIAlgorithmConvergenceStatusReasonValues.GetConvergenceStatusReason (reason), "NIAlgorithmConvergenceStatusReason should not be null."); + Assert.That (NIAlgorithmConvergenceStatusReasonValues.GetConvergenceStatusReason (reason), Is.Not.Null, "NIAlgorithmConvergenceStatusReason should not be null."); } } } diff --git a/tests/monotouch-test/Network/NSUrlTest.cs b/tests/monotouch-test/Network/NSUrlTest.cs index c0e0c752fbca..e836ae4b293c 100644 --- a/tests/monotouch-test/Network/NSUrlTest.cs +++ b/tests/monotouch-test/Network/NSUrlTest.cs @@ -9,7 +9,7 @@ public void ImplicitConversion () { global::System.Uri uri = null; NSUrl sUrl = uri; - Assert.IsNull (sUrl); + Assert.That (sUrl, Is.Null); } } } diff --git a/tests/monotouch-test/Network/NWBrowserDescriptorTest.cs b/tests/monotouch-test/Network/NWBrowserDescriptorTest.cs index e5f7e3ed2805..4de53ac19720 100644 --- a/tests/monotouch-test/Network/NWBrowserDescriptorTest.cs +++ b/tests/monotouch-test/Network/NWBrowserDescriptorTest.cs @@ -27,25 +27,25 @@ public void TearDown () [Test] public void TestIncludeTxtRecordProperty () { - Assert.IsFalse (descriptor.IncludeTxtRecord, "Get default value."); + Assert.That (descriptor.IncludeTxtRecord, Is.False, "Get default value."); descriptor.IncludeTxtRecord = true; - Assert.IsTrue (descriptor.IncludeTxtRecord, "Get new value."); + Assert.That (descriptor.IncludeTxtRecord, Is.True, "Get new value."); } [Test] public void TestCreateNullDomain () { using (var newDescriptor = NWBrowserDescriptor.CreateBonjourService (type)) { - Assert.AreEqual (type, descriptor.BonjourType, "service type"); - Assert.IsNull (newDescriptor.BonjourDomain); + Assert.That (descriptor.BonjourType, Is.EqualTo (type), "service type"); + Assert.That (newDescriptor.BonjourDomain, Is.Null); } } [Test] - public void TestBonjourTypeProperty () => Assert.AreEqual (type, descriptor.BonjourType); + public void TestBonjourTypeProperty () => Assert.That (descriptor.BonjourType, Is.EqualTo (type)); [Test] - public void TestBonjourDomainProperty () => Assert.AreEqual (domain, descriptor.BonjourDomain); + public void TestBonjourDomainProperty () => Assert.That (descriptor.BonjourDomain, Is.EqualTo (domain)); [Test] public void TestApplicationServiceConstructor () @@ -57,7 +57,7 @@ public void TestApplicationServiceConstructor () var appName = "myService"; using var appServiceDescriptor = NWBrowserDescriptor.CreateApplicationServiceName (appName); - Assert.AreEqual (appName, appServiceDescriptor.ApplicationServiceName); + Assert.That (appServiceDescriptor.ApplicationServiceName, Is.EqualTo (appName)); } } } diff --git a/tests/monotouch-test/Network/NWBrowserTest.cs b/tests/monotouch-test/Network/NWBrowserTest.cs index 52a549b49ce0..08798722d889 100644 --- a/tests/monotouch-test/Network/NWBrowserTest.cs +++ b/tests/monotouch-test/Network/NWBrowserTest.cs @@ -37,9 +37,9 @@ public void TearDown () public void TestConstructorNullParameters () { using (var otherBrowser = new NWBrowser (descriptor)) { - Assert.IsNotNull (otherBrowser.Descriptor, "Descriptor"); + Assert.That (otherBrowser.Descriptor, Is.Not.Null, "Descriptor"); // we expect the default parameters - Assert.IsNotNull (otherBrowser.Parameters, "Parameters"); + Assert.That (otherBrowser.Parameters, Is.Not.Null, "Parameters"); } } @@ -49,11 +49,11 @@ public void TestConstructorNullParameters () [Test] public void TestStart () { - Assert.IsFalse (browser.IsActive, "Idle"); + Assert.That (browser.IsActive, Is.False, "Idle"); browser.Start (); - Assert.IsTrue (browser.IsActive, "Active"); + Assert.That (browser.IsActive, Is.True, "Active"); browser.Cancel (); - Assert.IsFalse (browser.IsActive, "Cancel"); + Assert.That (browser.IsActive, Is.False, "Cancel"); } [Test] @@ -153,7 +153,7 @@ public void TestStateChangesHandler () log ($"listener.SetStateChangedHandler ({s}, {e} (ErrorCode = {e?.ErrorCode}, ErrorDomain = {e?.ErrorDomain}, CFError: {e?.CFError}, CFError.FailureReason: {e?.CFError?.FailureReason}))"); }); listener.Start (); - Assert.IsTrue (changesEvent.Wait (30000), $"changesEvent.Wait (){printLog ()}"); + Assert.That (changesEvent.Wait (30000), Is.True, $"changesEvent.Wait (){printLog ()}"); listener.Cancel (); listeningDone = true; finalEvent.Set (); @@ -169,17 +169,17 @@ public void TestStateChangesHandler () Assert.Ignore ("This test requires access to the local network, and this has not been granted."); } - Assert.IsNull (browserErrorState, "Ready Error"); + Assert.That (browserErrorState, Is.Null, "Ready Error"); Assert.That (state, Is.EqualTo (NWBrowserState.Ready), "NWBrowserState"); Assert.That (finishedBeforeTimeout, Is.True, $"RunAsync timeout{printLog ()}"); Assert.That (finalEvent.WaitOne (30000), Is.True, $"Final event{printLog ()}"); - Assert.IsNull (browserErrorState?.CFError, $"Error.CFError{printLog ()}"); - Assert.IsNull (browserErrorState, $"Error{printLog ()}"); - Assert.IsTrue (listeningDone, $"listeningDone{printLog ()}"); - Assert.IsNull (ex, $"Exception{printLog ()}"); - Assert.IsTrue (didRun, $"didRan{printLog ()}"); - Assert.IsTrue (receivedNotNullChange, $"receivedNotNullChange{printLog ()}"); + Assert.That (browserErrorState?.CFError, Is.Null, $"Error.CFError{printLog ()}"); + Assert.That (browserErrorState, Is.Null, $"Error{printLog ()}"); + Assert.That (listeningDone, Is.True, $"listeningDone{printLog ()}"); + Assert.That (ex, Is.Null, $"Exception{printLog ()}"); + Assert.That (didRun, Is.True, $"didRan{printLog ()}"); + Assert.That (receivedNotNullChange, Is.True, $"receivedNotNullChange{printLog ()}"); log ($"about to cancel..."); browser.Cancel (); log ($"cancelled..."); diff --git a/tests/monotouch-test/Network/NWConnectionGroupTest.cs b/tests/monotouch-test/Network/NWConnectionGroupTest.cs index 8df1604f5714..9a24fa346693 100644 --- a/tests/monotouch-test/Network/NWConnectionGroupTest.cs +++ b/tests/monotouch-test/Network/NWConnectionGroupTest.cs @@ -40,11 +40,11 @@ public void TearDown () [Test] public void GroupDescriptorTest () - => Assert.NotNull (connectionGroup.GroupDescriptor); + => Assert.That (connectionGroup.GroupDescriptor, Is.Not.Null); [Test] public void ParametersTest () - => Assert.NotNull (connectionGroup.Parameters); + => Assert.That (connectionGroup.Parameters, Is.Not.Null); [Test] public void SetQueueTest () diff --git a/tests/monotouch-test/Network/NWConnectionTest.cs b/tests/monotouch-test/Network/NWConnectionTest.cs index 833d526ebec9..0d6b7832e8df 100644 --- a/tests/monotouch-test/Network/NWConnectionTest.cs +++ b/tests/monotouch-test/Network/NWConnectionTest.cs @@ -23,10 +23,10 @@ public void SetUp () public void TearDown () => manager?.Dispose (); [Test] - public void TestEndpointProperty () => Assert.IsNotNull (connection.Endpoint); + public void TestEndpointProperty () => Assert.That (connection.Endpoint, Is.Not.Null); [Test] - public void TestParametersProperty () => Assert.IsNotNull (connection.Parameters); + public void TestParametersProperty () => Assert.That (connection.Parameters, Is.Not.Null); [Test] public void TestSetQPropertyNull () => Assert.Throws (() => connection.SetQueue (null)); @@ -44,10 +44,10 @@ public void TestCancel () } }); connection.Cancel (); - Assert.IsTrue (cancelled.WaitOne (3000), "Cancelled"); + Assert.That (cancelled.WaitOne (3000), Is.True, "Cancelled"); connection.Cancel (); // lib should ignore the second call - Assert.IsFalse (cancelled.WaitOne (3000)); + Assert.That (cancelled.WaitOne (3000), Is.False); } [Test] @@ -64,10 +64,10 @@ public void TestForceCancel () } }); connection.ForceCancel (); - Assert.IsTrue (cancelled.WaitOne (3000), "Cancelled"); + Assert.That (cancelled.WaitOne (3000), Is.True, "Cancelled"); connection.ForceCancel (); // lib should ignore the second call - Assert.IsFalse (cancelled.WaitOne (3000)); + Assert.That (cancelled.WaitOne (3000), Is.False); } } @@ -138,7 +138,7 @@ public NWConnection CreateConnection (out NWParameters parameters) } }); connection.Start (); - Assert.True (connectedEvent.WaitOne (20000), "Connection timed out."); + Assert.That (connectedEvent.WaitOne (20000), Is.True, "Connection timed out."); Assert.That (e, Is.Null, "No exception"); return connection; } diff --git a/tests/monotouch-test/Network/NWEndpointTests.cs b/tests/monotouch-test/Network/NWEndpointTests.cs index 4f9102f468ae..f3aff2d0ecbb 100644 --- a/tests/monotouch-test/Network/NWEndpointTests.cs +++ b/tests/monotouch-test/Network/NWEndpointTests.cs @@ -24,39 +24,39 @@ public void TearDown () } [Test] - public void TypeTest () => Assert.AreEqual (NWEndpointType.Url, endpoint.Type); + public void TypeTest () => Assert.That (endpoint.Type, Is.EqualTo (NWEndpointType.Url)); [Test] - public void HostNameTest () => Assert.AreEqual ("github.com", endpoint.Hostname); + public void HostNameTest () => Assert.That (endpoint.Hostname, Is.EqualTo ("github.com")); [Test] - public void PortTest () => Assert.AreEqual ("443", endpoint.Port); + public void PortTest () => Assert.That (endpoint.Port, Is.EqualTo ("443")); [Test] - public void BonjourServiceNameTest () => Assert.Null (endpoint.BonjourServiceName); + public void BonjourServiceNameTest () => Assert.That (endpoint.BonjourServiceName, Is.Null); [Test] - public void BonjourServiceTypeTest () => Assert.Null (endpoint.BonjourServiceType); + public void BonjourServiceTypeTest () => Assert.That (endpoint.BonjourServiceType, Is.Null); [Test] - public void BonjourServiceDomainTest () => Assert.Null (endpoint.BonjourServiceDomain); + public void BonjourServiceDomainTest () => Assert.That (endpoint.BonjourServiceDomain, Is.Null); [Test] - public void UrlTest () => Assert.AreEqual ("https://github.com", endpoint.Url); + public void UrlTest () => Assert.That (endpoint.Url, Is.EqualTo ("https://github.com")); [Test] public void SignatureTest () { TestRuntime.AssertXcodeVersion (14, 0); var signature = endpoint.Signature; - Assert.AreEqual (0, signature.Length); + Assert.That (signature.Length, Is.EqualTo (0)); } [Test] public void TxtRecordTest () { TestRuntime.AssertXcodeVersion (14, 0); - Assert.Null (endpoint.TxtRecord); + Assert.That (endpoint.TxtRecord, Is.Null); } } } diff --git a/tests/monotouch-test/Network/NWEstablishmentReportTest.cs b/tests/monotouch-test/Network/NWEstablishmentReportTest.cs index cf64ccd41594..29a49a2a6a01 100644 --- a/tests/monotouch-test/Network/NWEstablishmentReportTest.cs +++ b/tests/monotouch-test/Network/NWEstablishmentReportTest.cs @@ -28,7 +28,7 @@ public void Init () report = r; reportEvent.Set (); }); - Assert.True (reportEvent.WaitOne (20000), "Connection timed out."); + Assert.That (reportEvent.WaitOne (20000), Is.True, "Connection timed out."); } [OneTimeTearDown] @@ -42,34 +42,34 @@ public void Dispose () public void TestUsedProxy () { TestRuntime.IgnoreInCI ("CI bots might have proxies setup and will mean that the test will fail."); - Assert.IsFalse (report.UsedProxy, "Used proxy"); + Assert.That (report.UsedProxy, Is.False, "Used proxy"); } [Test] public void TestProxyConfigured () { TestRuntime.IgnoreInCI ("CI bots might have proxies setup and will mean that the test will fail."); - Assert.IsFalse (report.ProxyConfigured, "Proxy configured."); + Assert.That (report.ProxyConfigured, Is.False, "Proxy configured."); } [Test] - public void TestPreviousAttemptCount () => Assert.AreNotEqual (uint.MaxValue, report.PreviousAttemptCount); + public void TestPreviousAttemptCount () => Assert.That (report.PreviousAttemptCount, Is.Not.EqualTo (uint.MaxValue)); [Test] - public void TestDuration () => Assert.IsTrue (report.Duration > TimeSpan.MinValue); + public void TestDuration () => Assert.That (report.Duration > TimeSpan.MinValue, Is.True); [Test] - public void TestConnectionSetupTime () => Assert.IsTrue (report.ConnectionSetupTime > TimeSpan.MinValue); + public void TestConnectionSetupTime () => Assert.That (report.ConnectionSetupTime > TimeSpan.MinValue, Is.True); [Test] public void TestEnumerateResolutions () { var e = new AutoResetEvent (false); report.EnumerateResolutions ((source, duration, count, endpoint, preferred) => { - Assert.IsTrue (duration > TimeSpan.MinValue, "Durantion"); - Assert.AreNotEqual (0, count, "Count"); - Assert.IsNotNull (endpoint, "endpoint"); - Assert.IsNotNull (preferred, "preferred"); + Assert.That (duration > TimeSpan.MinValue, Is.True, "Durantion"); + Assert.That (count, Is.Not.EqualTo (0), "Count"); + Assert.That (endpoint, Is.Not.Null, "endpoint"); + Assert.That (preferred, Is.Not.Null, "preferred"); e.Set (); }); e.WaitOne (); @@ -79,7 +79,7 @@ public void TestEnumerateResolutions () public void TestProxyEnpoint () { TestRuntime.IgnoreInCI ("CI bots might have proxies setup and will mean that the test will fail."); - Assert.IsNull (report.ProxyEndpoint); + Assert.That (report.ProxyEndpoint, Is.Null); } [Test] diff --git a/tests/monotouch-test/Network/NWFramerMessageTest.cs b/tests/monotouch-test/Network/NWFramerMessageTest.cs index bea1d4a102fa..21ef6c4d2cf7 100644 --- a/tests/monotouch-test/Network/NWFramerMessageTest.cs +++ b/tests/monotouch-test/Network/NWFramerMessageTest.cs @@ -43,15 +43,15 @@ public void TestGetObject () message.SetObject ("test", storedValue); var result = message.GetObject ("test"); - Assert.IsNotNull (result, "Null"); - Assert.AreEqual (storedValue, result, "Equal"); + Assert.That (result, Is.Not.Null, "Null"); + Assert.That (result, Is.EqualTo (storedValue), "Equal"); } [Test] public void TestGetObjectMissingKey () { var result = message.GetObject ("test"); - Assert.IsNull (result, "Null"); + Assert.That (result, Is.Null, "Null"); } [Test] @@ -64,9 +64,9 @@ public void TestGetData () ReadOnlySpan outData; var found = message.GetData ("test", data.Length, out outData); - Assert.IsTrue (found, "Found"); - Assert.AreEqual (data.Length, outData.Length, "Legth"); - Assert.AreEqual (dataString, Encoding.UTF8.GetString (outData), "Equal"); + Assert.That (found, Is.True, "Found"); + Assert.That (outData.Length, Is.EqualTo (data.Length), "Legth"); + Assert.That (Encoding.UTF8.GetString (outData), Is.EqualTo (dataString), "Equal"); } [Test] @@ -74,8 +74,8 @@ public void TestGetDataMissingKey () { ReadOnlySpan outData; var found = message.GetData ("test", 23, out outData); - Assert.IsFalse (found, "Found"); - Assert.AreEqual (0, outData.Length, "Length"); + Assert.That (found, Is.False, "Found"); + Assert.That (outData.Length, Is.EqualTo (0), "Length"); } } } diff --git a/tests/monotouch-test/Network/NWIPProtocolMetadataTest.cs b/tests/monotouch-test/Network/NWIPProtocolMetadataTest.cs index c8de9cd4b645..60efb232b632 100644 --- a/tests/monotouch-test/Network/NWIPProtocolMetadataTest.cs +++ b/tests/monotouch-test/Network/NWIPProtocolMetadataTest.cs @@ -48,9 +48,9 @@ public void TestReceiveTimeProperty () [Test] public void TestMetadataType () { - Assert.True (metadata.IsIP, "IsIP"); - Assert.False (metadata.IsTcp, "IsTcp"); - Assert.False (metadata.IsUdp, "IsUdp"); + Assert.That (metadata.IsIP, Is.True, "IsIP"); + Assert.That (metadata.IsTcp, Is.False, "IsTcp"); + Assert.That (metadata.IsUdp, Is.False, "IsUdp"); } } } diff --git a/tests/monotouch-test/Network/NWListenerTest.cs b/tests/monotouch-test/Network/NWListenerTest.cs index 1b2e8547d933..1a4b488ec908 100644 --- a/tests/monotouch-test/Network/NWListenerTest.cs +++ b/tests/monotouch-test/Network/NWListenerTest.cs @@ -36,9 +36,9 @@ public void TestConnectionLimit () TestRuntime.AssertXcodeVersion (11, 0); var defaultValue = 4294967295; // got it from running the code, if changes we will have an error. - Assert.AreEqual (defaultValue, listener.ConnectionLimit); + Assert.That (listener.ConnectionLimit, Is.EqualTo (defaultValue)); listener.ConnectionLimit = 10; - Assert.AreEqual (10, listener.ConnectionLimit, "New value was not stored."); + Assert.That (listener.ConnectionLimit, Is.EqualTo (10), "New value was not stored."); } [Test] @@ -58,7 +58,7 @@ public void TestCreateLaunchd () { using var parameters = NWParameters.CreateTcp (); using var instance = NWListener.Create (parameters, "xamarinlaunchdkey"); - Assert.IsNotNull (instance, "Create"); + Assert.That (instance, Is.Not.Null, "Create"); } #endif } diff --git a/tests/monotouch-test/Network/NWMulticastGroupTest.cs b/tests/monotouch-test/Network/NWMulticastGroupTest.cs index d64bc76340d2..82c665cc9d41 100644 --- a/tests/monotouch-test/Network/NWMulticastGroupTest.cs +++ b/tests/monotouch-test/Network/NWMulticastGroupTest.cs @@ -35,7 +35,7 @@ public void DisabledUnicastTrafficTest () descriptor.DisabledUnicastTraffic = true; }, "Setter"); Assert.DoesNotThrow (() => { - Assert.IsTrue (descriptor.DisabledUnicastTraffic, "Value"); + Assert.That (descriptor.DisabledUnicastTraffic, Is.True, "Value"); }, "Getter"); } @@ -52,7 +52,7 @@ public void AddEndpointTest () var e = new AutoResetEvent (false); descriptor.EnumerateEndpoints ((endPoint) => { - Assert.IsNotNull (endPoint); + Assert.That (endPoint, Is.Not.Null); e.Set (); return true; }); diff --git a/tests/monotouch-test/Network/NWParametersTest.cs b/tests/monotouch-test/Network/NWParametersTest.cs index b25f5636cd8f..7d59a66f8953 100644 --- a/tests/monotouch-test/Network/NWParametersTest.cs +++ b/tests/monotouch-test/Network/NWParametersTest.cs @@ -90,8 +90,8 @@ public void CreateSecureUpdTest () using (var endpoint = NWEndpoint.Create (NetworkResources.MicrosoftUri.Host, "80")) { secureEvent.WaitOne (); configureEvent.WaitOne (); - Assert.True (secureConnectionWasSet, "Configure TLS handler was not called."); - Assert.True (protocolConfigured, "Protocol configure handler was not called."); + Assert.That (secureConnectionWasSet, Is.True, "Configure TLS handler was not called."); + Assert.That (protocolConfigured, Is.True, "Protocol configure handler was not called."); } } @@ -103,8 +103,8 @@ public void CreateSecureUpdTestDoNotSetUpProtocol () using (var parameters = NWParameters.CreateSecureUdp (configureTls: setUpTls)) using (var endpoint = NWEndpoint.Create (NetworkResources.MicrosoftUri.Host, "80")) { secureEvent.WaitOne (); - Assert.True (secureConnectionWasSet, "Configure TLS handler was not called."); - Assert.False (protocolConfigured, "Protocol configure handler was called."); + Assert.That (secureConnectionWasSet, Is.True, "Configure TLS handler was not called."); + Assert.That (protocolConfigured, Is.False, "Protocol configure handler was called."); } } @@ -116,8 +116,8 @@ public void CreateSecureUpdTestDoNotSetUpTls () using (var parameters = NWParameters.CreateSecureUdp (configureTls: null, configureUdp: setUpProtocol)) using (var endpoint = NWEndpoint.Create (NetworkResources.MicrosoftUri.Host, "80")) { configureEvent.WaitOne (); - Assert.False (secureConnectionWasSet, "Configure TLS handler was not called."); - Assert.True (protocolConfigured, "Protocol configure handler was not called."); + Assert.That (secureConnectionWasSet, Is.False, "Configure TLS handler was not called."); + Assert.That (protocolConfigured, Is.True, "Protocol configure handler was not called."); } } @@ -131,8 +131,8 @@ public void CreateSecureTcpTest () using (var endpoint = NWEndpoint.Create (NetworkResources.MicrosoftUri.Host, "80")) { secureEvent.WaitOne (); configureEvent.WaitOne (); - Assert.True (secureConnectionWasSet, "Configure TLS handler was not called."); - Assert.True (protocolConfigured, "Protocol configure handler was not called."); + Assert.That (secureConnectionWasSet, Is.True, "Configure TLS handler was not called."); + Assert.That (protocolConfigured, Is.True, "Protocol configure handler was not called."); } } @@ -145,8 +145,8 @@ public void CreateSecureTcpTestDoNotSetUpProtocol () using (var parameters = NWParameters.CreateSecureTcp (configureTls: setUpTls)) using (var endpoint = NWEndpoint.Create (NetworkResources.MicrosoftUri.Host, "80")) { secureEvent.WaitOne (); - Assert.True (secureConnectionWasSet, "Configure TLS handler was not called."); - Assert.False (protocolConfigured, "Protocol configure handler was called."); + Assert.That (secureConnectionWasSet, Is.True, "Configure TLS handler was not called."); + Assert.That (protocolConfigured, Is.False, "Protocol configure handler was called."); } } @@ -158,8 +158,8 @@ public void CreateSecureTcpTestDoNotSetUpTls () using (var parameters = NWParameters.CreateSecureTcp (configureTls: null, configureTcp: setUpProtocol)) using (var endpoint = NWEndpoint.Create (NetworkResources.MicrosoftUri.Host, "80")) { configureEvent.WaitOne (); - Assert.False (secureConnectionWasSet, "Configure TLS handler was called."); - Assert.True (protocolConfigured, "Protocol configure handler was not called."); + Assert.That (secureConnectionWasSet, Is.False, "Configure TLS handler was called."); + Assert.That (protocolConfigured, Is.True, "Protocol configure handler was not called."); } } @@ -173,7 +173,7 @@ public void CreateCustomIP () using (var parameters = NWParameters.CreateCustomIP (ipVersion, setUpProtocol)) using (var endpoint = NWEndpoint.Create ("wwww.google.com", "80")) { configureEvent.WaitOne (); - Assert.True (protocolConfigured, "Protocol configure handler was not called."); + Assert.That (protocolConfigured, Is.True, "Protocol configure handler was not called."); } } #endif @@ -183,10 +183,10 @@ public void MultiPathServicePropertyTest () { using (var parameters = new NWParameters ()) { var defaultValue = parameters.MultipathService; - Assert.AreEqual (defaultValue, NWMultiPathService.Disabled, "Default value changed."); + Assert.That (NWMultiPathService.Disabled, Is.EqualTo (defaultValue), "Default value changed."); var newValue = NWMultiPathService.Aggregate; parameters.MultipathService = newValue; - Assert.AreEqual (newValue, parameters.MultipathService, "New value was not stored."); + Assert.That (parameters.MultipathService, Is.EqualTo (newValue), "New value was not stored."); } } @@ -195,7 +195,7 @@ public void ProtocolStackPropertyTest () { using (var parameters = new NWParameters ()) { var stack = parameters.ProtocolStack; - Assert.AreNotEqual (IntPtr.Zero, stack.Handle); + Assert.That (stack.Handle, Is.Not.EqualTo (IntPtr.Zero)); } } @@ -204,9 +204,9 @@ public void LocalOnlyPropertyTest () { using (var parameters = new NWParameters ()) { var defaultValue = parameters.LocalOnly; - Assert.False (defaultValue, "Default value changed."); + Assert.That (defaultValue, Is.False, "Default value changed."); parameters.LocalOnly = true; - Assert.True (parameters.LocalOnly, "New value was not stored."); + Assert.That (parameters.LocalOnly, Is.True, "New value was not stored."); } } @@ -215,9 +215,9 @@ public void PreferNoProxyPropertyTest () { using (var parameters = new NWParameters ()) { var defaultValue = parameters.PreferNoProxy; - Assert.False (defaultValue, "Default value changed."); + Assert.That (defaultValue, Is.False, "Default value changed."); parameters.PreferNoProxy = true; - Assert.True (parameters.PreferNoProxy, "New value was not stored."); + Assert.That (parameters.PreferNoProxy, Is.True, "New value was not stored."); } } @@ -226,9 +226,9 @@ public void ExpiredDnsBehaviorPropertyTest () { using (var parameters = new NWParameters ()) { var defaultValue = parameters.ExpiredDnsBehavior; - Assert.AreEqual (NWParametersExpiredDnsBehavior.Default, defaultValue, "Default value changed."); + Assert.That (defaultValue, Is.EqualTo (NWParametersExpiredDnsBehavior.Default), "Default value changed."); parameters.ExpiredDnsBehavior = NWParametersExpiredDnsBehavior.Allow; - Assert.AreEqual (NWParametersExpiredDnsBehavior.Allow, parameters.ExpiredDnsBehavior, "New value was not stored."); + Assert.That (parameters.ExpiredDnsBehavior, Is.EqualTo (NWParametersExpiredDnsBehavior.Allow), "New value was not stored."); } } @@ -238,12 +238,12 @@ public void RequiredInterfacePropertyTest () using (var parameters = new NWParameters ()) { var defaultValue = parameters.RequiredInterface; - Assert.IsNull (defaultValue, "Default value changed."); + Assert.That (defaultValue, Is.Null, "Default value changed."); // try to set a null value, we should have no issues parameters.RequiredInterface = null; - Assert.IsNull (parameters.RequiredInterface, "Value should still be null."); + Assert.That (parameters.RequiredInterface, Is.Null, "Value should still be null."); parameters.RequiredInterface = interfaces [0]; - Assert.AreNotEqual (IntPtr.Zero, parameters.RequiredInterface.Handle, "New value was not set."); + Assert.That (parameters.RequiredInterface.Handle, Is.Not.EqualTo (IntPtr.Zero), "New value was not set."); } } @@ -252,7 +252,7 @@ public void ProhibitInterfaceTest () { using (var parameters = new NWParameters ()) { Assert.Throws (() => parameters.ProhibitInterface (null), ""); - Assert.AreNotEqual (0, interfaces.Count, "No network interfaces found."); + Assert.That (interfaces.Count, Is.Not.EqualTo (0), "No network interfaces found."); parameters.ProhibitInterface (interfaces [0]); } } @@ -262,9 +262,9 @@ public void RequiredInterfaceTypePropertyTest () { using (var parameters = new NWParameters ()) { var defaultValue = parameters.RequiredInterfaceType; - Assert.AreEqual (NWInterfaceType.Other, defaultValue, "Default value changed."); + Assert.That (defaultValue, Is.EqualTo (NWInterfaceType.Other), "Default value changed."); parameters.RequiredInterfaceType = NWInterfaceType.Wifi; - Assert.AreEqual (NWInterfaceType.Wifi, parameters.RequiredInterfaceType, "BNe value was not stored."); + Assert.That (parameters.RequiredInterfaceType, Is.EqualTo (NWInterfaceType.Wifi), "BNe value was not stored."); } } @@ -275,7 +275,7 @@ public void ProhibitInterfaceTypeTest () var types = new List (); parameters.ProhibitInterfaceType (NWInterfaceType.Wifi); parameters.IterateProhibitedInterfaces ((type) => { types.Add (type); return true; }); - Assert.True (types.Contains (NWInterfaceType.Wifi), "Type was not prohibited."); + Assert.That (types.Contains (NWInterfaceType.Wifi), Is.True, "Type was not prohibited."); } } @@ -284,9 +284,9 @@ public void ReuseLocalAddressPropertyTest () { using (var parameters = new NWParameters ()) { var defaultValue = parameters.ReuseLocalAddress; - Assert.False (defaultValue, "Default value changed."); + Assert.That (defaultValue, Is.False, "Default value changed."); parameters.ReuseLocalAddress = true; - Assert.True (parameters.ReuseLocalAddress, "New value was not stored."); + Assert.That (parameters.ReuseLocalAddress, Is.True, "New value was not stored."); } } @@ -295,9 +295,9 @@ public void FastOpenEnabledPropertyTest () { using (var parameters = new NWParameters ()) { var defaultValue = parameters.FastOpenEnabled; - Assert.False (defaultValue, "Defalue value changed."); + Assert.That (defaultValue, Is.False, "Defalue value changed."); parameters.FastOpenEnabled = true; - Assert.True (parameters.FastOpenEnabled, "New value was not stored."); + Assert.That (parameters.FastOpenEnabled, Is.True, "New value was not stored."); } } @@ -306,9 +306,9 @@ public void ServiceClassPropertyTest () { using (var parameters = new NWParameters ()) { var defaultValue = parameters.ServiceClass; - Assert.AreEqual (NWServiceClass.BestEffort, defaultValue, "Default value changed."); + Assert.That (defaultValue, Is.EqualTo (NWServiceClass.BestEffort), "Default value changed."); parameters.ServiceClass = NWServiceClass.InteractiveVideo; - Assert.AreEqual (NWServiceClass.InteractiveVideo, parameters.ServiceClass, "New value was not stored."); + Assert.That (parameters.ServiceClass, Is.EqualTo (NWServiceClass.InteractiveVideo), "New value was not stored."); } } @@ -319,9 +319,9 @@ public void LocalEndpointPropertyTest () using (var parameters = NWParameters.CreateUdp ()) using (var endpoint = NWEndpoint.Create (NetworkResources.MicrosoftUri.Host, "80")) { var defaultValue = parameters.LocalEndpoint; - Assert.IsNull (defaultValue, "Default value changed."); + Assert.That (defaultValue, Is.Null, "Default value changed."); parameters.LocalEndpoint = endpoint; - Assert.IsNotNull (parameters.LocalEndpoint, "New value was not stored."); + Assert.That (parameters.LocalEndpoint, Is.Not.Null, "New value was not stored."); } } @@ -330,9 +330,9 @@ public void IncludePeerToPeerPropertyTest () { using (var parameters = new NWParameters ()) { var defaultValue = parameters.IncludePeerToPeer; - Assert.False (defaultValue, "Default value changed."); + Assert.That (defaultValue, Is.False, "Default value changed."); parameters.IncludePeerToPeer = true; - Assert.True (parameters.IncludePeerToPeer, "New value was not stored."); + Assert.That (parameters.IncludePeerToPeer, Is.True, "New value was not stored."); } } @@ -342,9 +342,9 @@ public void TestProhibitConstrained () TestRuntime.AssertXcodeVersion (11, 0); using (var parameters = new NWParameters ()) { var defaultValue = false; - Assert.False (defaultValue, "Default value changed."); + Assert.That (defaultValue, Is.False, "Default value changed."); parameters.ProhibitConstrained = true; - Assert.True (parameters.ProhibitConstrained, "New value was not stored."); + Assert.That (parameters.ProhibitConstrained, Is.True, "New value was not stored."); } } @@ -356,7 +356,7 @@ public void AttributionPropertyTest () Assert.DoesNotThrow (() => { parameters.Attribution = NWParametersAttribution.Developer; }); - Assert.AreEqual (NWParametersAttribution.Developer, parameters.Attribution); + Assert.That (parameters.Attribution, Is.EqualTo (NWParametersAttribution.Developer)); } } @@ -378,7 +378,7 @@ public void CreateApplicationServiceTest () { TestRuntime.AssertXcodeVersion (14, 0); using var nwParams = NWParameters.CreateApplicationService (); - Assert.NotNull (nwParams); + Assert.That (nwParams, Is.Not.Null); } [Test] diff --git a/tests/monotouch-test/Network/NWPathMonitorTest.cs b/tests/monotouch-test/Network/NWPathMonitorTest.cs index 29d8dffa3ed8..9bfd0ee91158 100644 --- a/tests/monotouch-test/Network/NWPathMonitorTest.cs +++ b/tests/monotouch-test/Network/NWPathMonitorTest.cs @@ -69,12 +69,12 @@ public void PathIsAlwaysUpdatedWithNewHandlerTest () TestRuntime.RunAsync (TimeSpan.FromSeconds (3), () => { }, () => newPath is not null); monitor.Cancel (); - Assert.IsNotNull (oldPath, "oldPath set (no timeout)"); - Assert.IsNotNull (newPath, "newPath set (no timeout)"); + Assert.That (oldPath, Is.Not.Null, "oldPath set (no timeout)"); + Assert.That (newPath, Is.Not.Null, "newPath set (no timeout)"); // they might be the same native objects (happens on macOS and Catalyst) and, // in such case, they will have the same `Handle` value, making them equal on the // .net profile. However what we want to know here is if the path was updated - Assert.False (Object.ReferenceEquals (oldPath, newPath), "different instances"); + Assert.That (Object.ReferenceEquals (oldPath, newPath), Is.False, "different instances"); } [Test] @@ -93,7 +93,7 @@ public void CreateForEthernetChannelTest () { TestRuntime.AssertXcodeVersion (14, 0); using var pathMonitor = NWPathMonitor.CreateForEthernetChannel (); - Assert.NotNull (pathMonitor); + Assert.That (pathMonitor, Is.Not.Null); } #endif } diff --git a/tests/monotouch-test/Network/NWPathTest.cs b/tests/monotouch-test/Network/NWPathTest.cs index e5724c6572f1..1be97cba6e6b 100644 --- a/tests/monotouch-test/Network/NWPathTest.cs +++ b/tests/monotouch-test/Network/NWPathTest.cs @@ -56,13 +56,13 @@ public void TearDown () [Test] public void StatusPropertyTest () { - Assert.AreEqual (NWPathStatus.Satisfied, path.Status, $"Unexpected status {path.Status}"); + Assert.That (path.Status, Is.EqualTo (NWPathStatus.Satisfied), $"Unexpected status {path.Status}"); } [Test] public void IsExpensivePropertyTest () { - Assert.False (path.IsExpensive, "Path was not expected to be expensive."); // To be tested as part of NWProtocolStack + Assert.That (path.IsExpensive, Is.False, "Path was not expected to be expensive."); // To be tested as part of NWProtocolStack } [Test] @@ -70,17 +70,17 @@ public void HasIPV4PropertyTest () { #if !MONOMAC && !__MACCATALYST__ if (Runtime.Arch != Arch.DEVICE) - Assert.False (path.HasIPV4, "By default the interface does not support IPV4 on the simulator"); + Assert.That (path.HasIPV4, Is.False, "By default the interface does not support IPV4 on the simulator"); else #endif - Assert.True (path.HasIPV4, "By default the interface does support IPV4 on the device"); + Assert.That (path.HasIPV4, Is.True, "By default the interface does support IPV4 on the device"); } [Test] public void HasIPV6PropertyTest () { Assert.Ignore ("We cannot test the use of IPV6 since it is different per machine configuraton and makes the test flaky."); - Assert.False (path.HasIPV6, "By default the interface does not support IPV6"); // To be tested as part of NWProtocolStack + Assert.That (path.HasIPV6, Is.False, "By default the interface does not support IPV6"); // To be tested as part of NWProtocolStack } [Test] @@ -88,17 +88,17 @@ public void HasDnsPropertyTest () { #if !MONOMAC && !__MACCATALYST__ if (Runtime.Arch != Arch.DEVICE) - Assert.False (path.HasDns, "By default the interface does not support DNS on the simulator"); + Assert.That (path.HasDns, Is.False, "By default the interface does not support DNS on the simulator"); else #endif - Assert.True (path.HasDns, "By default the interface does support DNS on the device"); + Assert.That (path.HasDns, Is.True, "By default the interface does support DNS on the device"); } [Test] public void UsesInterfaceTypeTest () { foreach (var i in interfaces) { - Assert.True (path.UsesInterfaceType (i.InterfaceType), $"Type {i.InterfaceType} should be in use."); + Assert.That (path.UsesInterfaceType (i.InterfaceType), Is.True, $"Type {i.InterfaceType} should be in use."); } } @@ -140,7 +140,7 @@ public void EnumerateGatewayTest () e1.Task); if (!rv) Assert.Ignore ("No gateways on this machine?"); // no gateways isn't all that uncommon, so just always ignore in this case. - Assert.IsTrue (rv, "Called back"); + Assert.That (rv, Is.True, "Called back"); } finally { monitor.Cancel (); monitor.Dispose (); diff --git a/tests/monotouch-test/Network/NWProtocolDefinitionTest.cs b/tests/monotouch-test/Network/NWProtocolDefinitionTest.cs index c82062b2ed9b..b9d351dddcdd 100644 --- a/tests/monotouch-test/Network/NWProtocolDefinitionTest.cs +++ b/tests/monotouch-test/Network/NWProtocolDefinitionTest.cs @@ -15,28 +15,28 @@ public class NWProtocolDefinitionTest { public void IPDefinitionTest () { using (var definition = NWProtocolDefinition.CreateIPDefinition ()) - Assert.NotNull (definition); + Assert.That (definition, Is.Not.Null); } [Test] public void TcpDefinitionTest () { using (var definition = NWProtocolDefinition.CreateTcpDefinition ()) - Assert.NotNull (definition); + Assert.That (definition, Is.Not.Null); } [Test] public void TlsDefinitionTest () { using (var definition = NWProtocolDefinition.CreateTlsDefinition ()) - Assert.NotNull (definition); + Assert.That (definition, Is.Not.Null); } [Test] public void UdpDefinitionTest () { using (var definition = NWProtocolDefinition.CreateUdpDefinition ()) - Assert.NotNull (definition); + Assert.That (definition, Is.Not.Null); } [Test] @@ -44,7 +44,7 @@ public void WebSocketDefinitionTest () { TestRuntime.AssertXcodeVersion (11, 0); using (var definition = NWProtocolDefinition.CreateWebSocketDefinition ()) - Assert.NotNull (definition); + Assert.That (definition, Is.Not.Null); } } } diff --git a/tests/monotouch-test/Network/NWProtocolIPOptionsTest.cs b/tests/monotouch-test/Network/NWProtocolIPOptionsTest.cs index 29bcee78a625..59480cd55376 100644 --- a/tests/monotouch-test/Network/NWProtocolIPOptionsTest.cs +++ b/tests/monotouch-test/Network/NWProtocolIPOptionsTest.cs @@ -39,7 +39,7 @@ public void Dispose () public void SetUp () { options = stack.InternetProtocol as NWProtocolIPOptions; - Assert.NotNull (options, "options"); + Assert.That (options, Is.Not.Null, "options"); } // we cannot assert that the C code those the right thing, BUT we do know diff --git a/tests/monotouch-test/Network/NWProtocolMetadataTest.cs b/tests/monotouch-test/Network/NWProtocolMetadataTest.cs index 8b6580b6dd07..41822b28e86a 100644 --- a/tests/monotouch-test/Network/NWProtocolMetadataTest.cs +++ b/tests/monotouch-test/Network/NWProtocolMetadataTest.cs @@ -18,10 +18,10 @@ public void IP () using (var m = new NWIPMetadata ()) { Assert.That (m.EcnFlag, Is.EqualTo (NWIPEcnFlag.NonEct), "IPMetadataEcnFlag"); Assert.That (m.ReceiveTime, Is.EqualTo (TimeSpan.Zero), "IPMetadataReceiveTime"); - Assert.True (m.IsIP, "IsIP"); - Assert.False (m.IsTcp, "IsTcp"); - Assert.False (m.IsUdp, "IsUdp"); - Assert.NotNull (m.ProtocolDefinition, "ProtocolDefinition"); + Assert.That (m.IsIP, Is.True, "IsIP"); + Assert.That (m.IsTcp, Is.False, "IsTcp"); + Assert.That (m.IsUdp, Is.False, "IsUdp"); + Assert.That (m.ProtocolDefinition, Is.Not.Null, "ProtocolDefinition"); Assert.That (m.ServiceClass, Is.EqualTo (NWServiceClass.BestEffort), "ServiceClass"); } } @@ -30,10 +30,10 @@ public void IP () public void Udp () { using (var m = new NWUdpMetadata ()) { - Assert.False (m.IsIP, "IsIP"); - Assert.False (m.IsTcp, "IsTcp"); - Assert.True (m.IsUdp, "IsUdp"); - Assert.NotNull (m.ProtocolDefinition, "ProtocolDefinition"); + Assert.That (m.IsIP, Is.False, "IsIP"); + Assert.That (m.IsTcp, Is.False, "IsTcp"); + Assert.That (m.IsUdp, Is.True, "IsUdp"); + Assert.That (m.ProtocolDefinition, Is.Not.Null, "ProtocolDefinition"); } } @@ -44,11 +44,11 @@ public void Quic () using (var m = new NWIPMetadata ()) { Assert.That (m.EcnFlag, Is.EqualTo (NWIPEcnFlag.NonEct), "IPMetadataEcnFlag"); Assert.That (m.ReceiveTime, Is.EqualTo (TimeSpan.Zero), "IPMetadataReceiveTime"); - Assert.True (m.IsIP, "IsIP"); - Assert.False (m.IsTcp, "IsTcp"); - Assert.False (m.IsUdp, "IsUdp"); - Assert.False (m.IsQuic, "IsQuic"); - Assert.NotNull (m.ProtocolDefinition, "ProtocolDefinition"); + Assert.That (m.IsIP, Is.True, "IsIP"); + Assert.That (m.IsTcp, Is.False, "IsTcp"); + Assert.That (m.IsUdp, Is.False, "IsUdp"); + Assert.That (m.IsQuic, Is.False, "IsQuic"); + Assert.That (m.ProtocolDefinition, Is.Not.Null, "ProtocolDefinition"); Assert.That (m.ServiceClass, Is.EqualTo (NWServiceClass.BestEffort), "ServiceClass"); } } diff --git a/tests/monotouch-test/Network/NWProtocolOptionsTest.cs b/tests/monotouch-test/Network/NWProtocolOptionsTest.cs index ac3389da19cd..6d0163551ba2 100644 --- a/tests/monotouch-test/Network/NWProtocolOptionsTest.cs +++ b/tests/monotouch-test/Network/NWProtocolOptionsTest.cs @@ -18,7 +18,7 @@ public void CreateTlsTest () using (var options = new NWProtocolTlsOptions ()) { var sec = options.ProtocolOptions; // we cannot test much more :( - Assert.AreNotEqual (IntPtr.Zero, options.Handle); + Assert.That (options.Handle, Is.Not.EqualTo (IntPtr.Zero)); } } @@ -27,7 +27,7 @@ public void CreateTcpTest () { using (var options = new NWProtocolTcpOptions ()) { // we cannot test much more :( - Assert.AreNotEqual (IntPtr.Zero, options.Handle); + Assert.That (options.Handle, Is.Not.EqualTo (IntPtr.Zero)); } } @@ -36,7 +36,7 @@ public void CreateUdpTest () { using (var options = new NWProtocolUdpOptions ()) { // we cannot test much more :( - Assert.AreNotEqual (IntPtr.Zero, options.Handle); + Assert.That (options.Handle, Is.Not.EqualTo (IntPtr.Zero)); } } diff --git a/tests/monotouch-test/Network/NWProtocolStackTest.cs b/tests/monotouch-test/Network/NWProtocolStackTest.cs index a7dc0008efe5..135f52e6932f 100644 --- a/tests/monotouch-test/Network/NWProtocolStackTest.cs +++ b/tests/monotouch-test/Network/NWProtocolStackTest.cs @@ -65,7 +65,7 @@ public void ClearApplicationProtocolsTest () options = new List (); stack.ClearApplicationProtocols (); stack.IterateProtocols (InterateProtocolsHandler); - Assert.AreEqual (0, options.Count, "Cleared options"); + Assert.That (options.Count, Is.EqualTo (0), "Cleared options"); } /* [Test] @@ -73,7 +73,7 @@ public void TransportProtocolPropertyTest () { using (var options = stack.TransportProtocol) { - Assert.IsNotNull (options, "Transport protocol should not be null."); + Assert.That (options, Is.Not.Null, "Transport protocol should not be null."); } using (var options = NWProtocolOptions.CreateUdp ()) { diff --git a/tests/monotouch-test/Network/NWProtocolTlsOptionsTest.cs b/tests/monotouch-test/Network/NWProtocolTlsOptionsTest.cs index 4170ee48c57c..770fecfd8eb2 100644 --- a/tests/monotouch-test/Network/NWProtocolTlsOptionsTest.cs +++ b/tests/monotouch-test/Network/NWProtocolTlsOptionsTest.cs @@ -22,7 +22,7 @@ public void SetUp () [Test] public void ProtocolOptionsTest () { - Assert.NotNull (options.ProtocolOptions); + Assert.That (options.ProtocolOptions, Is.Not.Null); } } } diff --git a/tests/monotouch-test/Network/NWProxyConfigTests.cs b/tests/monotouch-test/Network/NWProxyConfigTests.cs index 07850bcc02e4..ce038b80c144 100644 --- a/tests/monotouch-test/Network/NWProxyConfigTests.cs +++ b/tests/monotouch-test/Network/NWProxyConfigTests.cs @@ -39,7 +39,7 @@ public void CreateRelayTest () try { Assert.DoesNotThrow ( () => capturedConfig = NWProxyConfig.CreateRelay (hop, null), "Throws"); - Assert.NotNull (capturedConfig, "Not null"); + Assert.That (capturedConfig, Is.Not.Null, "Not null"); } finally { capturedConfig?.Dispose (); } @@ -52,7 +52,7 @@ public void CreateObliviousHttpTest () try { Assert.DoesNotThrow ( () => capturedConfig = NWProxyConfig.CreateObliviousHttp (hop, "", new byte [0]), "Throws"); - Assert.Null (capturedConfig, "Not null"); + Assert.That (capturedConfig, Is.Null, "Not null"); } finally { capturedConfig?.Dispose (); } @@ -66,7 +66,7 @@ public void CreateHttpConnectTest () Assert.DoesNotThrow ( () => capturedConfig = NWProxyConfig.CreateHttpConnect (endpoint, null), "Throws"); - Assert.NotNull (capturedConfig, "Not null"); + Assert.That (capturedConfig, Is.Not.Null, "Not null"); } finally { capturedConfig?.Dispose (); } @@ -80,7 +80,7 @@ public void CreateSocksV5Test () Assert.DoesNotThrow ( () => capturedConfig = NWProxyConfig.CreateSocksV5 (endpoint), "Throws"); - Assert.NotNull (capturedConfig, "Not null"); + Assert.That (capturedConfig, Is.Not.Null, "Not null"); } finally { capturedConfig?.Dispose (); } @@ -104,7 +104,7 @@ public void SetUsernameAndPasswordTest () public void FailoverAllowedTest () { config.FailoverAllowed = true; - Assert.True (config.FailoverAllowed); + Assert.That (config.FailoverAllowed, Is.True); } [Test] @@ -188,10 +188,10 @@ public void EnumerateExcludedDomainsTest () public void DefaultSessionConfigurationProxyConfigurationsTests () { var defaultConfig = NSUrlSessionConfiguration.DefaultSessionConfiguration; - Assert.AreEqual (0, defaultConfig.ProxyConfigurations.Length, "getter"); + Assert.That (defaultConfig.ProxyConfigurations.Length, Is.EqualTo (0), "getter"); defaultConfig.ProxyConfigurations = new [] { config }; - Assert.AreEqual (1, defaultConfig.ProxyConfigurations.Length, "setter"); + Assert.That (defaultConfig.ProxyConfigurations.Length, Is.EqualTo (1), "setter"); } } } diff --git a/tests/monotouch-test/Network/NWResolutionReportTest.cs b/tests/monotouch-test/Network/NWResolutionReportTest.cs index 8b47ed5d579e..db3adff145f3 100644 --- a/tests/monotouch-test/Network/NWResolutionReportTest.cs +++ b/tests/monotouch-test/Network/NWResolutionReportTest.cs @@ -30,12 +30,12 @@ public void Init () report = r; reportEvent.Set (); }); - Assert.True (reportEvent.WaitOne (20000), "Timed out fetching establishment reports."); + Assert.That (reportEvent.WaitOne (20000), Is.True, "Timed out fetching establishment reports."); report.EnumerateResolutionReports ((r) => { resolutionReport = Runtime.GetINativeObject (r.Handle, false); resolutionEvent.Set (); }); - Assert.True (resolutionEvent.WaitOne (20000), "Timed out enumerating resolution reports."); + Assert.That (resolutionEvent.WaitOne (20000), Is.True, "Timed out enumerating resolution reports."); } [OneTimeTearDown] diff --git a/tests/monotouch-test/Network/NWResolverConfigTest.cs b/tests/monotouch-test/Network/NWResolverConfigTest.cs index 591d153abd26..cc2fd728214b 100644 --- a/tests/monotouch-test/Network/NWResolverConfigTest.cs +++ b/tests/monotouch-test/Network/NWResolverConfigTest.cs @@ -26,8 +26,8 @@ public void TearDown () public void HttpConstructorTest () { using var resolver = new NWResolverConfig (endpoint, NWResolverConfigEndpointType.Https); - Assert.NotNull (resolver, "Not null https"); - Assert.AreNotEqual (IntPtr.Zero, resolver.Handle, "Zero Handle htttps"); + Assert.That (resolver, Is.Not.Null, "Not null https"); + Assert.That (resolver.Handle, Is.Not.EqualTo (IntPtr.Zero), "Zero Handle htttps"); } [Test] diff --git a/tests/monotouch-test/Network/NWTxtRecordTest.cs b/tests/monotouch-test/Network/NWTxtRecordTest.cs index f7dfa43bc253..9e7f1ee5ceab 100644 --- a/tests/monotouch-test/Network/NWTxtRecordTest.cs +++ b/tests/monotouch-test/Network/NWTxtRecordTest.cs @@ -27,7 +27,7 @@ public void TestFromBytes () var e = new AutoResetEvent (false); record.GetRawBytes ( (d) => { - Assert.AreNotEqual (0, d.Length, "Raw data length."); + Assert.That (d.Length, Is.Not.EqualTo (0), "Raw data length."); e.Set (); } ); @@ -41,26 +41,26 @@ public void TearDown () } [Test] - public void TestMissingKey () => Assert.AreEqual (NWTxtRecordFindKey.NotPresent, record.FindKey ("foo")); + public void TestMissingKey () => Assert.That (record.FindKey ("foo"), Is.EqualTo (NWTxtRecordFindKey.NotPresent)); [Test] - public void TestPresentKey () => Assert.AreEqual (NWTxtRecordFindKey.NonEmptyValue, record.FindKey (randomKey)); + public void TestPresentKey () => Assert.That (record.FindKey (randomKey), Is.EqualTo (NWTxtRecordFindKey.NonEmptyValue)); [Test] public void TestAddByteValue () { var data = new byte [] { 10, 20, 30, 40 }; var mySecondKey = "secondKey"; - Assert.True (record.Add (mySecondKey, data), "Add"); - Assert.AreEqual (NWTxtRecordFindKey.NonEmptyValue, record.FindKey (mySecondKey)); + Assert.That (record.Add (mySecondKey, data), Is.True, "Add"); + Assert.That (record.FindKey (mySecondKey), Is.EqualTo (NWTxtRecordFindKey.NonEmptyValue)); } [Test] public void TestAddNoValue () { var mySecondKey = "secondLKey"; - Assert.True (record.Add (mySecondKey), "Add"); - Assert.AreEqual (NWTxtRecordFindKey.NoValue, record.FindKey (mySecondKey)); + Assert.That (record.Add (mySecondKey), Is.True, "Add"); + Assert.That (record.FindKey (mySecondKey), Is.EqualTo (NWTxtRecordFindKey.NoValue)); } [Test] @@ -68,8 +68,8 @@ public void TestAddStringValue () { var data = "hello"; var mySecondKey = "secondLKey"; - Assert.True (record.Add (mySecondKey, data), "Add"); - Assert.AreEqual (NWTxtRecordFindKey.NonEmptyValue, record.FindKey (mySecondKey)); + Assert.That (record.Add (mySecondKey, data), Is.True, "Add"); + Assert.That (record.FindKey (mySecondKey), Is.EqualTo (NWTxtRecordFindKey.NonEmptyValue)); } [Test] @@ -77,28 +77,28 @@ public void TestAddNullStringValue () { string data = null; var mySecondKey = "secondLKey"; - Assert.True (record.Add (mySecondKey, data), "Add"); - Assert.AreEqual (NWTxtRecordFindKey.NoValue, record.FindKey (mySecondKey)); + Assert.That (record.Add (mySecondKey, data), Is.True, "Add"); + Assert.That (record.FindKey (mySecondKey), Is.EqualTo (NWTxtRecordFindKey.NoValue)); } [Test] - public void TestRemoveMissingKey () => Assert.IsFalse (record.Remove ("NotPresentKey")); + public void TestRemoveMissingKey () => Assert.That (record.Remove ("NotPresentKey"), Is.False); [Test] public void TestRemovePresentKey () { - Assert.True (record.Remove (randomKey), "Remove"); - Assert.AreEqual (NWTxtRecordFindKey.NotPresent, record.FindKey (randomKey), "FindKey"); + Assert.That (record.Remove (randomKey), Is.True, "Remove"); + Assert.That (record.FindKey (randomKey), Is.EqualTo (NWTxtRecordFindKey.NotPresent), "FindKey"); } [Test] - public void TestKeyCount () => Assert.AreEqual (1, record.KeyCount); + public void TestKeyCount () => Assert.That (record.KeyCount, Is.EqualTo (1)); [Test] - public void TestIsDictionary () => Assert.IsTrue (record.IsDictionary); + public void TestIsDictionary () => Assert.That (record.IsDictionary, Is.True); [Test] - public void TestNotNullEquals () => Assert.IsFalse (record.Equals (null)); + public void TestNotNullEquals () => Assert.That (record.Equals (null), Is.False); [Test] public void TestApply () @@ -112,10 +112,10 @@ public void TestApply () var keyCount2 = 0; record.Apply ((k, r, v) => { keyCount2++; - Assert.IsTrue (keys.Contains (k), k); + Assert.That (keys.Contains (k), Is.True, k); return true; }); - Assert.AreEqual (keys.Count, keyCount2, "keycount2"); + Assert.That (keyCount2, Is.EqualTo (keys.Count), "keycount2"); } [Test] @@ -123,9 +123,9 @@ public void TestGetValueMissing () { var missing = "missingKey"; record.GetValue (missing, (k, r, value) => { - Assert.AreEqual (missing, k, "key"); - Assert.AreEqual (NWTxtRecordFindKey.NotPresent, r, "result"); - Assert.AreEqual (0, value.Length, "value"); + Assert.That (k, Is.EqualTo (missing), "key"); + Assert.That (r, Is.EqualTo (NWTxtRecordFindKey.NotPresent), "result"); + Assert.That (value.Length, Is.EqualTo (0), "value"); }); } @@ -133,9 +133,9 @@ public void TestGetValueMissing () public void TestGetValuePresent () { record.GetValue (randomKey, (k, r, value) => { - Assert.AreEqual (randomKey, k, "key"); - Assert.AreEqual (NWTxtRecordFindKey.NonEmptyValue, r, "result"); - Assert.AreNotEqual (0, value.Length, "value"); + Assert.That (k, Is.EqualTo (randomKey), "key"); + Assert.That (r, Is.EqualTo (NWTxtRecordFindKey.NonEmptyValue), "result"); + Assert.That (value.Length, Is.Not.EqualTo (0), "value"); }); } @@ -145,7 +145,7 @@ public void TestGetRaw () var e = new AutoResetEvent (false); record.GetRawBytes ( (d) => { - Assert.AreNotEqual (0, d.Length); + Assert.That (d.Length, Is.Not.EqualTo (0)); e.Set (); } ); diff --git a/tests/monotouch-test/Network/NWWebSocketMetadataTest.cs b/tests/monotouch-test/Network/NWWebSocketMetadataTest.cs index 74d5fbced07e..2dfad06cfc06 100644 --- a/tests/monotouch-test/Network/NWWebSocketMetadataTest.cs +++ b/tests/monotouch-test/Network/NWWebSocketMetadataTest.cs @@ -45,7 +45,7 @@ public void TestConstructor () public void TestServerResponse () { var resposne = metadata.ServerResponse; - Assert.IsNull (resposne); // did not make a request, null is expected + Assert.That (resposne, Is.Null); // did not make a request, null is expected } } } diff --git a/tests/monotouch-test/Network/NWWebSocketOptionsTest.cs b/tests/monotouch-test/Network/NWWebSocketOptionsTest.cs index 17b6fd1ead03..f1441725bd7d 100644 --- a/tests/monotouch-test/Network/NWWebSocketOptionsTest.cs +++ b/tests/monotouch-test/Network/NWWebSocketOptionsTest.cs @@ -29,7 +29,7 @@ public void TestConstructorInvalidVersion () { Assert.DoesNotThrow (() => { using (var otherOptions = new NWWebSocketOptions (NWWebSocketVersion.Invalid)) - Assert.AreNotEqual (IntPtr.Zero, otherOptions.Handle); + Assert.That (otherOptions.Handle, Is.Not.EqualTo (IntPtr.Zero)); }); } @@ -53,27 +53,27 @@ public void TestConstructorInvalidVersion () public void TestAutoReplyPing () { var defaultValue = options.AutoReplyPing; - Assert.IsFalse (defaultValue, "defaultValue"); + Assert.That (defaultValue, Is.False, "defaultValue"); options.AutoReplyPing = true; - Assert.IsTrue (options.AutoReplyPing, "new value"); + Assert.That (options.AutoReplyPing, Is.True, "new value"); } [Test] public void TestMaxMessageSize () { var defaultValue = options.MaximumMessageSize; - Assert.AreEqual (defaultValue, (nuint) 0, "defaultValue"); + Assert.That (defaultValue, Is.EqualTo ((nuint) 0), "defaultValue"); nuint newValue = 40; options.MaximumMessageSize = newValue; - Assert.AreEqual (newValue, options.MaximumMessageSize, "new value"); + Assert.That (options.MaximumMessageSize, Is.EqualTo (newValue), "new value"); } [Test] public void TestSkipHandShake () { - Assert.IsFalse (options.SkipHandShake, "defaultValue"); + Assert.That (options.SkipHandShake, Is.False, "defaultValue"); options.SkipHandShake = true; - Assert.IsTrue (options.SkipHandShake, "new value"); + Assert.That (options.SkipHandShake, Is.True, "new value"); } [Test] diff --git a/tests/monotouch-test/NetworkExtension/NEHotspotEapSettingsTest.cs b/tests/monotouch-test/NetworkExtension/NEHotspotEapSettingsTest.cs index 4609cc19862a..73d2c308b0c4 100644 --- a/tests/monotouch-test/NetworkExtension/NEHotspotEapSettingsTest.cs +++ b/tests/monotouch-test/NetworkExtension/NEHotspotEapSettingsTest.cs @@ -16,7 +16,7 @@ public void SupportedEapTypes_Default () { using var settings = new NEHotspotEapSettings (); var types = settings.SupportedEapTypes; - Assert.IsNotNull (types, "Default value should not be null"); + Assert.That (types, Is.Not.Null, "Default value should not be null"); Assert.That (types.Length, Is.EqualTo (0), "Default length"); } @@ -30,7 +30,7 @@ public void SupportedEapTypes_Roundtrip () }; settings.SupportedEapTypes = expected; var actual = settings.SupportedEapTypes; - Assert.IsNotNull (actual, "not null"); + Assert.That (actual, Is.Not.Null, "not null"); Assert.That (actual.Length, Is.EqualTo (2), "Length"); Assert.That (actual [0], Is.EqualTo (NEHotspotConfigurationEapType.Tls), "[0]"); Assert.That (actual [1], Is.EqualTo (NEHotspotConfigurationEapType.Peap), "[1]"); diff --git a/tests/monotouch-test/NetworkExtension/OnDemandTest.cs b/tests/monotouch-test/NetworkExtension/OnDemandTest.cs index 3014521d83d0..848315006014 100644 --- a/tests/monotouch-test/NetworkExtension/OnDemandTest.cs +++ b/tests/monotouch-test/NetworkExtension/OnDemandTest.cs @@ -20,35 +20,35 @@ public class OnDemandTest { void OnDemandRule (NEOnDemandRule rule) { - Assert.Null (rule.DnsSearchDomainMatch, "DnsSearchDomainMatch"); + Assert.That (rule.DnsSearchDomainMatch, Is.Null, "DnsSearchDomainMatch"); rule.DnsSearchDomainMatch = new string [] { "1" }; Assert.That (rule.DnsSearchDomainMatch.Length, Is.EqualTo (1), "DnsSearchDomainMatch-2"); rule.DnsSearchDomainMatch = null; - Assert.Null (rule.DnsSearchDomainMatch, "DnsSearchDomainMatch-3"); + Assert.That (rule.DnsSearchDomainMatch, Is.Null, "DnsSearchDomainMatch-3"); - Assert.Null (rule.DnsServerAddressMatch, ""); + Assert.That (rule.DnsServerAddressMatch, Is.Null, ""); rule.DnsServerAddressMatch = new string [] { "1", "2" }; Assert.That (rule.DnsServerAddressMatch.Length, Is.EqualTo (2), "DnsServerAddressMatch-2"); rule.DnsServerAddressMatch = null; - Assert.Null (rule.DnsServerAddressMatch, "DnsServerAddressMatch-3"); + Assert.That (rule.DnsServerAddressMatch, Is.Null, "DnsServerAddressMatch-3"); Assert.That (rule.InterfaceTypeMatch, Is.EqualTo ((NEOnDemandRuleInterfaceType) 0), "InterfaceTypeMatch"); rule.InterfaceTypeMatch = NEOnDemandRuleInterfaceType.WiFi; Assert.That (rule.InterfaceTypeMatch, Is.EqualTo (NEOnDemandRuleInterfaceType.WiFi), "InterfaceTypeMatch-2"); - Assert.Null (rule.ProbeUrl, "ProbeUrl"); + Assert.That (rule.ProbeUrl, Is.Null, "ProbeUrl"); using (var url = new NSUrl ("http://www.xamarin.com")) { rule.ProbeUrl = url; - Assert.AreSame (url, rule.ProbeUrl, "ProbeUrl-2"); + Assert.That (rule.ProbeUrl, Is.SameAs (url), "ProbeUrl-2"); } rule.ProbeUrl = null; - Assert.Null (rule.ProbeUrl, "ProbeUrl-3"); + Assert.That (rule.ProbeUrl, Is.Null, "ProbeUrl-3"); - Assert.Null (rule.SsidMatch, "SsidMatch"); + Assert.That (rule.SsidMatch, Is.Null, "SsidMatch"); rule.SsidMatch = new string [] { "1", "2", "3" }; Assert.That (rule.SsidMatch.Length, Is.EqualTo (3), "SsidMatch-2"); rule.SsidMatch = null; - Assert.Null (rule.SsidMatch, "SsidMatch-3"); + Assert.That (rule.SsidMatch, Is.Null, "SsidMatch-3"); } [Test] @@ -97,13 +97,13 @@ public void NEOnDemandRuleEvaluateConnection () Assert.That (rule.Action, Is.EqualTo (NEOnDemandRuleAction.EvaluateConnection), "Action"); OnDemandRule (rule); // - Assert.IsNull (rule.ConnectionRules, "ConnectionRules"); + Assert.That (rule.ConnectionRules, Is.Null, "ConnectionRules"); rule.ConnectionRules = new NEEvaluateConnectionRule [] { new NEEvaluateConnectionRule () }; - Assert.IsNotNull (rule.ConnectionRules, "ConnectionRules-2"); + Assert.That (rule.ConnectionRules, Is.Not.Null, "ConnectionRules-2"); rule.ConnectionRules = null; - Assert.IsNull (rule.ConnectionRules, "ConnectionRules-3"); + Assert.That (rule.ConnectionRules, Is.Null, "ConnectionRules-3"); } } @@ -115,9 +115,9 @@ public void EvaluateConnectionRule_Default () using (var rule = new NEEvaluateConnectionRule ()) { Assert.That (rule.Action, Is.EqualTo ((NEEvaluateConnectionRuleAction) 0), "Action"); - Assert.Null (rule.MatchDomains, "MatchDomains"); - Assert.Null (rule.ProbeUrl, "ProbeUrl"); - Assert.Null (rule.UseDnsServers, "UseDnsServers"); + Assert.That (rule.MatchDomains, Is.Null, "MatchDomains"); + Assert.That (rule.ProbeUrl, Is.Null, "ProbeUrl"); + Assert.That (rule.UseDnsServers, Is.Null, "UseDnsServers"); } } @@ -130,19 +130,19 @@ public void EvaluateConnectionRule () using (var rule = new NEEvaluateConnectionRule (new [] { "xamarin.com" }, NEEvaluateConnectionRuleAction.ConnectIfNeeded)) { Assert.That (rule.Action, Is.EqualTo (NEEvaluateConnectionRuleAction.ConnectIfNeeded), "Action"); Assert.That (rule.MatchDomains [0], Is.EqualTo ("xamarin.com"), "MatchDomains"); - Assert.Null (rule.ProbeUrl, "ProbeUrl"); + Assert.That (rule.ProbeUrl, Is.Null, "ProbeUrl"); using (var url = new NSUrl ("http://www.xamarin.com")) { rule.ProbeUrl = url; - Assert.AreSame (url, rule.ProbeUrl, "ProbeUrl-2"); + Assert.That (rule.ProbeUrl, Is.SameAs (url), "ProbeUrl-2"); } rule.ProbeUrl = null; - Assert.Null (rule.ProbeUrl, "ProbeUrl-3"); + Assert.That (rule.ProbeUrl, Is.Null, "ProbeUrl-3"); - Assert.Null (rule.UseDnsServers, "UseDnsServers"); + Assert.That (rule.UseDnsServers, Is.Null, "UseDnsServers"); rule.UseDnsServers = new [] { "8.8.8.8" }; Assert.That (rule.UseDnsServers [0], Is.EqualTo ("8.8.8.8"), "UseDnsServers-2"); rule.UseDnsServers = null; - Assert.Null (rule.UseDnsServers, "UseDnsServers-3"); + Assert.That (rule.UseDnsServers, Is.Null, "UseDnsServers-3"); } } } diff --git a/tests/monotouch-test/NetworkExtension/VpnManagerTest.cs b/tests/monotouch-test/NetworkExtension/VpnManagerTest.cs index 55bb85801975..cb742738da41 100644 --- a/tests/monotouch-test/NetworkExtension/VpnManagerTest.cs +++ b/tests/monotouch-test/NetworkExtension/VpnManagerTest.cs @@ -31,9 +31,9 @@ public void SharedManager () Assert.That (shared.Connection.Status, Is.EqualTo (NEVpnStatus.Invalid), "Connection"); #if MONOMAC || __MACCATALYST__ - Assert.True (shared.Enabled, "Enabled"); + Assert.That (shared.Enabled, Is.True, "Enabled"); #else - Assert.False (shared.Enabled, "Enabled"); + Assert.That (shared.Enabled, Is.False, "Enabled"); #endif #if __IOS__ var HasLocalizedDescription = TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 9, 0); @@ -41,13 +41,13 @@ public void SharedManager () var HasLocalizedDescription = true; #endif if (HasLocalizedDescription) { - Assert.AreEqual ("MonoTouchTest", shared.LocalizedDescription, "LocalizedDescription"); + Assert.That (shared.LocalizedDescription, Is.EqualTo ("MonoTouchTest"), "LocalizedDescription"); } else { - Assert.IsNull (shared.LocalizedDescription, "LocalizedDescription"); + Assert.That (shared.LocalizedDescription, Is.Null, "LocalizedDescription"); } - Assert.False (shared.OnDemandEnabled, "OnDemandEnabled"); - Assert.Null (shared.OnDemandRules, "OnDemandRules"); - Assert.Null (shared.Protocol, "Protocol"); + Assert.That (shared.OnDemandEnabled, Is.False, "OnDemandEnabled"); + Assert.That (shared.OnDemandRules, Is.Null, "OnDemandRules"); + Assert.That (shared.Protocol, Is.Null, "Protocol"); } [Test] diff --git a/tests/monotouch-test/ObjCRuntime/BlocksTest.cs b/tests/monotouch-test/ObjCRuntime/BlocksTest.cs index 79ecaa3cbf66..c76ee00c5fc3 100644 --- a/tests/monotouch-test/ObjCRuntime/BlocksTest.cs +++ b/tests/monotouch-test/ObjCRuntime/BlocksTest.cs @@ -36,7 +36,7 @@ public unsafe void SignatureA () #else var boolIsB = true; #endif - Assert.AreEqual (boolIsB ? "v@?B" : "v@?c", GetBlockSignature (&block), $"Signature ARM64: {Runtime.IsARM64CallingConvention}"); + Assert.That (GetBlockSignature (&block), Is.EqualTo (boolIsB ? "v@?B" : "v@?c"), $"Signature ARM64: {Runtime.IsARM64CallingConvention}"); } [Test] @@ -45,7 +45,7 @@ public unsafe void SignatureB () { delegate* unmanaged trampoline = &SignatureTestB; using var block = new BlockLiteral (trampoline, null, typeof (BlocksTest), nameof (SignatureTestB)); - Assert.AreEqual ("v@?@", GetBlockSignature (&block), "Signature"); + Assert.That (GetBlockSignature (&block), Is.EqualTo ("v@?@"), "Signature"); } [Test] @@ -56,7 +56,7 @@ public unsafe void SignatureC () using var block = new BlockLiteral (trampoline, null, typeof (BlocksTest), nameof (SignatureTestC)); // This is the wrong signature, but the registrar has no way of figuring out the correct // one without the UserDelegateType attribute on the target method. - Assert.AreEqual ("v@?^v^v", GetBlockSignature (&block), "Signature"); + Assert.That (GetBlockSignature (&block), Is.EqualTo ("v@?^v^v"), "Signature"); } [UserDelegateType (typeof (Action))] @@ -111,9 +111,9 @@ public void TestSetupBlock () using (var obj = new TestClass ()) { TestClass.OnCallback = ((IntPtr blockArgument, NativeHandle self, IntPtr argument) => { - Assert.AreNotEqual (IntPtr.Zero, blockArgument, "block"); - Assert.AreEqual (obj.Handle, self, "self"); - Assert.AreEqual (argument, (IntPtr) 0x12345678, "argument"); + Assert.That (blockArgument, Is.Not.EqualTo (IntPtr.Zero), "block"); + Assert.That (self, Is.EqualTo (obj.Handle), "self"); + Assert.That (argument, Is.EqualTo ((IntPtr) 0x12345678), "argument"); }); Messaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("testBlocks:"), (IntPtr) 0x12345678); } diff --git a/tests/monotouch-test/ObjCRuntime/CategoryTest.cs b/tests/monotouch-test/ObjCRuntime/CategoryTest.cs index 0194d5cac4da..61b9ee29ef59 100644 --- a/tests/monotouch-test/ObjCRuntime/CategoryTest.cs +++ b/tests/monotouch-test/ObjCRuntime/CategoryTest.cs @@ -56,12 +56,12 @@ public class CategoryTest { public void Static () { using (var str = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (new NSString ("").ClassHandle, Selector.GetHandle ("toUpper")))) { - Assert.AreEqual ("TOUPPER", str.ToString (), "#1"); + Assert.That (str.ToString (), Is.EqualTo ("TOUPPER"), "#1"); } using (var istr = (NSString) "test-string") { using (var str = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend_IntPtr (new NSString ("").ClassHandle, Selector.GetHandle ("toUpper:"), istr.Handle))) { - Assert.AreEqual ("TEST-STRING", str.ToString (), "#2"); + Assert.That (str.ToString (), Is.EqualTo ("TEST-STRING"), "#2"); } } } @@ -71,13 +71,13 @@ public void Instance () { using (var istr = (NSString) "SoMeUpPeRcAsElEtTeRs") { using (var str = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (istr.Handle, Selector.GetHandle ("toLower")))) { - Assert.AreEqual ("someuppercaseletters", str.ToString (), "#1"); + Assert.That (str.ToString (), Is.EqualTo ("someuppercaseletters"), "#1"); } } using (var istr = (NSString) "fIrSt") { using (var istr2 = (NSString) "secOND") { using (var str = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend_IntPtr (istr.Handle, Selector.GetHandle ("joinLower:"), istr2.Handle))) { - Assert.AreEqual ("firstsecond", str.ToString (), "#2"); + Assert.That (str.ToString (), Is.EqualTo ("firstsecond"), "#2"); } } } diff --git a/tests/monotouch-test/ObjCRuntime/ClassTest.cs b/tests/monotouch-test/ObjCRuntime/ClassTest.cs index 2c61b9da7782..56a67d590319 100644 --- a/tests/monotouch-test/ObjCRuntime/ClassTest.cs +++ b/tests/monotouch-test/ObjCRuntime/ClassTest.cs @@ -49,13 +49,13 @@ public void Ctor () { Assert.DoesNotThrow (() => new Class (typeof (NSObject)), "NSObject"); if (Runtime.DynamicRegistrationSupported) { - Assert.AreEqual (NativeHandle.Zero, new Class (typeof (string)).Handle, "string"); + Assert.That (new Class (typeof (string)).Handle, Is.EqualTo (NativeHandle.Zero), "string"); } else { try { new Class (typeof (string)); } catch (Exception e) { - Assert.AreEqual (typeof (RuntimeException), e.GetType (), "string exc"); - Assert.AreEqual ("Can't register the class System.String when the dynamic registrar has been linked away.", e.Message, "exc message"); + Assert.That (e.GetType (), Is.EqualTo (typeof (RuntimeException)), "string exc"); + Assert.That (e.Message, Is.EqualTo ("Can't register the class System.String when the dynamic registrar has been linked away."), "exc message"); } } } @@ -63,36 +63,36 @@ public void Ctor () [Test] public void GetHandle () { - Assert.AreNotEqual (NativeHandle.Zero, Class.GetHandle (typeof (NSObject)), "NSObject"); + Assert.That (Class.GetHandle (typeof (NSObject)), Is.Not.EqualTo (NativeHandle.Zero), "NSObject"); if (Runtime.DynamicRegistrationSupported) { - Assert.AreEqual (NativeHandle.Zero, Class.GetHandle (typeof (string)), "string 1"); + Assert.That (Class.GetHandle (typeof (string)), Is.EqualTo (NativeHandle.Zero), "string 1"); } else { try { Class.GetHandle (typeof (string)); } catch (Exception e) { - Assert.AreEqual (typeof (RuntimeException), e.GetType (), "string exc"); - Assert.AreEqual ("Can't register the class System.String when the dynamic registrar has been linked away.", e.Message, "exc message"); + Assert.That (e.GetType (), Is.EqualTo (typeof (RuntimeException)), "string exc"); + Assert.That (e.Message, Is.EqualTo ("Can't register the class System.String when the dynamic registrar has been linked away."), "exc message"); } } #pragma warning disable IL3050 // Using member 'System.Type.MakeArrayType()' which has 'RequiresDynamicCodeAttribute' can break functionality when AOT compiling. The code for an array of the specified type might not be available. - Assert.AreEqual (NativeHandle.Zero, Class.GetHandle (typeof (NSObject).MakeByRefType ()), "NSObject&"); - Assert.AreEqual (NativeHandle.Zero, Class.GetHandle (typeof (NSObject).MakeArrayType ()), "NSObject[]"); - Assert.AreEqual (NativeHandle.Zero, Class.GetHandle (typeof (NSObject).MakePointerType ()), "NSObject*"); + Assert.That (Class.GetHandle (typeof (NSObject).MakeByRefType ()), Is.EqualTo (NativeHandle.Zero), "NSObject&"); + Assert.That (Class.GetHandle (typeof (NSObject).MakeArrayType ()), Is.EqualTo (NativeHandle.Zero), "NSObject[]"); + Assert.That (Class.GetHandle (typeof (NSObject).MakePointerType ()), Is.EqualTo (NativeHandle.Zero), "NSObject*"); #pragma warning restore IL3050 } [Test] public void Lookup () { - Assert.AreEqual (typeof (NSObject), Class.Lookup (new Class (typeof (NSObject))), "NSObject"); - Assert.AreEqual (typeof (NSString), Class.Lookup (new Class (typeof (NSString))), "NSString"); - Assert.AreNotEqual (typeof (NSObject), Class.Lookup (new Class (typeof (NSString))), "neq"); + Assert.That (Class.Lookup (new Class (typeof (NSObject))), Is.EqualTo (typeof (NSObject)), "NSObject"); + Assert.That (Class.Lookup (new Class (typeof (NSString))), Is.EqualTo (typeof (NSString)), "NSString"); + Assert.That (Class.Lookup (new Class (typeof (NSString))), Is.Not.EqualTo (typeof (NSObject)), "neq"); try { Class.Lookup (new Class ("NSProxy")); } catch (Exception e) { - Assert.AreEqual (typeof (RuntimeException), e.GetType (), "NSProxy exception"); + Assert.That (e.GetType (), Is.EqualTo (typeof (RuntimeException)), "NSProxy exception"); if (Runtime.DynamicRegistrationSupported) { - Assert.AreEqual ("The ObjectiveC class 'NSProxy' could not be registered, it does not seem to derive from any known ObjectiveC class (including NSObject).", e.Message, "NSProxy exception message"); + Assert.That (e.Message, Is.EqualTo ("The ObjectiveC class 'NSProxy' could not be registered, it does not seem to derive from any known ObjectiveC class (including NSObject)."), "NSProxy exception message"); } else { Assert.That (e.Message, Does.Match ("Can't lookup the Objective-C class 0x.* w"), "NSProxy exception message 2"); } @@ -100,7 +100,7 @@ public void Lookup () Assert.Throws (() => new Class ("InexistentClass"), "inexistent"); // Private class which we've obviously not bound, but we've bound a super class. // And yes, NSMutableString is the first public superclass of __NSCFConstantString. - Assert.AreEqual (typeof (NSMutableString), Class.Lookup (new Class ("__NSCFConstantString")), "private class"); + Assert.That (Class.Lookup (new Class ("__NSCFConstantString")), Is.EqualTo (typeof (NSMutableString)), "private class"); } [Test] @@ -187,7 +187,7 @@ public void Bug33981 () startPistol.Set (); stopLine.Wait (); - Assert.IsNull (ex); + Assert.That (ex, Is.Null); } } } diff --git a/tests/monotouch-test/ObjCRuntime/DelegateAndDataSourceTest.cs b/tests/monotouch-test/ObjCRuntime/DelegateAndDataSourceTest.cs index 41cd2bf6f978..748cc67173d7 100644 --- a/tests/monotouch-test/ObjCRuntime/DelegateAndDataSourceTest.cs +++ b/tests/monotouch-test/ObjCRuntime/DelegateAndDataSourceTest.cs @@ -68,10 +68,12 @@ public void DelegateAndDataSourceAllowsNull () dataSource.SetValue (instance, null, null); } } + } catch (NotSupportedException e) when (e.Message.Contains ("This object cannot be invoked because no code was generated for it")) { + Console.WriteLine ($"Not testing {t.FullName}, because it's been partially trimmed away."); } catch (TargetInvocationException e) { failingTypes.Add (t, e.InnerException.Message); } catch (Exception e) { - Assert.Fail ("Unexpected exception {0} while testing {1}", e, t); + Assert.Fail ($"Unexpected exception {e} while testing {t}"); } } } @@ -82,7 +84,7 @@ public void DelegateAndDataSourceAllowsNull () Console.WriteLine ("{0} failing types:", failingTypes.Count); foreach (var kvp in failingTypes) Console.WriteLine ("{0}: {1}", kvp.Key, kvp.Value); - Assert.Fail ("{0} failing types", failingTypes.Count); + Assert.Fail ($"{failingTypes.Count} failing types"); } } @@ -220,7 +222,7 @@ public void DelegateAndDataSourceHaveArgumentSemanticAttribute () Console.WriteLine ("{0} failing types:", failingTypes.Count); foreach (var kvp in failingTypes) Console.WriteLine ("{0}: {1}", kvp.Key, kvp.Value); - Assert.Fail ("{0} failing types", failingTypes.Count); + Assert.Fail ($"{failingTypes.Count} failing types"); } } @@ -258,7 +260,7 @@ public void TargetArgumentSemanticAttribute () Console.WriteLine ("{0} failing types:", failingTypes.Count); foreach (var kvp in failingTypes) Console.WriteLine ("{0}: {1}", kvp.Key, kvp.Value); - Assert.Fail ("{0} failing types", failingTypes.Count); + Assert.Fail ($"{failingTypes.Count} failing types"); } } diff --git a/tests/monotouch-test/ObjCRuntime/DisposableObjectTest.cs b/tests/monotouch-test/ObjCRuntime/DisposableObjectTest.cs index bcc8dd3926e1..55448a43e719 100644 --- a/tests/monotouch-test/ObjCRuntime/DisposableObjectTest.cs +++ b/tests/monotouch-test/ObjCRuntime/DisposableObjectTest.cs @@ -20,8 +20,8 @@ public Subclassed (NativeHandle handle, bool owns, bool verify) : base (handle, public void DefaultCtor () { var obj = new Subclassed (); - Assert.AreEqual (NativeHandle.Zero, obj.Handle, "Handle"); - Assert.AreEqual (false, obj.Owns, "Owns"); + Assert.That (obj.Handle, Is.EqualTo (NativeHandle.Zero), "Handle"); + Assert.That (obj.Owns, Is.EqualTo (false), "Owns"); } [Test] @@ -36,19 +36,19 @@ public void CtorOwns () Assert.That (ex.Message, Does.Contain ("Could not initialize an instance of the type"), "Ex 2"); obj = new Subclassed ((NativeHandle) (IntPtr) 1, true); - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.Handle, "Handle 3"); - Assert.AreEqual (true, obj.Owns, "Owns 3"); - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.GetCheckedHandle (), "GetCheckedHandle 3"); + Assert.That (obj.Handle, Is.EqualTo ((NativeHandle) (IntPtr) 1), "Handle 3"); + Assert.That (obj.Owns, Is.EqualTo (true), "Owns 3"); + Assert.That (obj.GetCheckedHandle (), Is.EqualTo ((NativeHandle) (IntPtr) 1), "GetCheckedHandle 3"); obj.Dispose (); - Assert.AreEqual (NativeHandle.Zero, obj.Handle, "Handle 3b"); + Assert.That (obj.Handle, Is.EqualTo (NativeHandle.Zero), "Handle 3b"); Assert.Throws (() => obj.GetCheckedHandle (), "GetCheckedHandle 3b"); obj = new Subclassed ((NativeHandle) (IntPtr) 1, false); - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.Handle, "Handle 4"); - Assert.AreEqual (false, obj.Owns, "Owns 4"); - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.GetCheckedHandle (), "GetCheckedHandle 4"); + Assert.That (obj.Handle, Is.EqualTo ((NativeHandle) (IntPtr) 1), "Handle 4"); + Assert.That (obj.Owns, Is.EqualTo (false), "Owns 4"); + Assert.That (obj.GetCheckedHandle (), Is.EqualTo ((NativeHandle) (IntPtr) 1), "GetCheckedHandle 4"); obj.Dispose (); - Assert.AreEqual (NativeHandle.Zero, obj.Handle, "Handle 4b"); + Assert.That (obj.Handle, Is.EqualTo (NativeHandle.Zero), "Handle 4b"); Assert.Throws (() => obj.GetCheckedHandle (), "GetCheckedHandle 4b"); } @@ -56,33 +56,33 @@ public void CtorOwns () public void CtorOwnsVerify () { var obj = new Subclassed (NativeHandle.Zero, true, false); - Assert.AreEqual (NativeHandle.Zero, obj.Handle, "Handle 1"); - Assert.AreEqual (true, obj.Owns, "Owns 1"); + Assert.That (obj.Handle, Is.EqualTo (NativeHandle.Zero), "Handle 1"); + Assert.That (obj.Owns, Is.EqualTo (true), "Owns 1"); Assert.Throws (() => obj.GetCheckedHandle (), "GetCheckedHandle 1"); obj.Dispose (); - Assert.AreEqual (NativeHandle.Zero, obj.Handle, "Handle 1b"); + Assert.That (obj.Handle, Is.EqualTo (NativeHandle.Zero), "Handle 1b"); Assert.Throws (() => obj.GetCheckedHandle (), "GetCheckedHandle 1b"); obj = new Subclassed (NativeHandle.Zero, false, false); - Assert.AreEqual (NativeHandle.Zero, obj.Handle, "Handle 2"); - Assert.AreEqual (false, obj.Owns, "Owns 2"); + Assert.That (obj.Handle, Is.EqualTo (NativeHandle.Zero), "Handle 2"); + Assert.That (obj.Owns, Is.EqualTo (false), "Owns 2"); Assert.Throws (() => obj.GetCheckedHandle (), "GetCheckedHandle 2"); obj.Dispose (); - Assert.AreEqual (NativeHandle.Zero, obj.Handle, "Handle 2b"); + Assert.That (obj.Handle, Is.EqualTo (NativeHandle.Zero), "Handle 2b"); Assert.Throws (() => obj.GetCheckedHandle (), "GetCheckedHandle 2b"); obj = new Subclassed ((NativeHandle) (IntPtr) 1, true, false); - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.Handle, "Handle 3"); - Assert.AreEqual (true, obj.Owns, "Owns 3"); - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.GetCheckedHandle (), "GetCheckedHandle 3"); + Assert.That (obj.Handle, Is.EqualTo ((NativeHandle) (IntPtr) 1), "Handle 3"); + Assert.That (obj.Owns, Is.EqualTo (true), "Owns 3"); + Assert.That (obj.GetCheckedHandle (), Is.EqualTo ((NativeHandle) (IntPtr) 1), "GetCheckedHandle 3"); obj.Dispose (); - Assert.AreEqual (NativeHandle.Zero, obj.Handle, "Handle 3b"); + Assert.That (obj.Handle, Is.EqualTo (NativeHandle.Zero), "Handle 3b"); Assert.Throws (() => obj.GetCheckedHandle (), "GetCheckedHandle 3b"); obj = new Subclassed ((NativeHandle) (IntPtr) 1, false, false); - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.Handle, "Handle 4"); - Assert.AreEqual (false, obj.Owns, "Owns 4"); - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.GetCheckedHandle (), "GetCheckedHandle 4"); + Assert.That (obj.Handle, Is.EqualTo ((NativeHandle) (IntPtr) 1), "Handle 4"); + Assert.That (obj.Owns, Is.EqualTo (false), "Owns 4"); + Assert.That (obj.GetCheckedHandle (), Is.EqualTo ((NativeHandle) (IntPtr) 1), "GetCheckedHandle 4"); var ex = Assert.Throws (() => obj = new Subclassed (NativeHandle.Zero, true, true), "Handle 1V"); @@ -92,19 +92,19 @@ public void CtorOwnsVerify () Assert.That (ex.Message, Does.Contain ("Could not initialize an instance of the type"), "Ex 2V"); obj = new Subclassed ((NativeHandle) (IntPtr) 1, true, true); - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.Handle, "Handle 3V"); - Assert.AreEqual (true, obj.Owns, "Owns 3V"); - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.GetCheckedHandle (), "GetCheckedHandle 3V"); + Assert.That (obj.Handle, Is.EqualTo ((NativeHandle) (IntPtr) 1), "Handle 3V"); + Assert.That (obj.Owns, Is.EqualTo (true), "Owns 3V"); + Assert.That (obj.GetCheckedHandle (), Is.EqualTo ((NativeHandle) (IntPtr) 1), "GetCheckedHandle 3V"); obj.Dispose (); - Assert.AreEqual (NativeHandle.Zero, obj.Handle, "Handle 3Vb"); + Assert.That (obj.Handle, Is.EqualTo (NativeHandle.Zero), "Handle 3Vb"); Assert.Throws (() => obj.GetCheckedHandle (), "GetCheckedHandle 3Vb"); obj = new Subclassed ((NativeHandle) (IntPtr) 1, false, true); - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.Handle, "Handle 4V"); - Assert.AreEqual (false, obj.Owns, "Owns 4V"); - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.GetCheckedHandle (), "GetCheckedHandle 4V"); + Assert.That (obj.Handle, Is.EqualTo ((NativeHandle) (IntPtr) 1), "Handle 4V"); + Assert.That (obj.Owns, Is.EqualTo (false), "Owns 4V"); + Assert.That (obj.GetCheckedHandle (), Is.EqualTo ((NativeHandle) (IntPtr) 1), "GetCheckedHandle 4V"); obj.Dispose (); - Assert.AreEqual (NativeHandle.Zero, obj.Handle, "Handle 4Vb"); + Assert.That (obj.Handle, Is.EqualTo (NativeHandle.Zero), "Handle 4Vb"); Assert.Throws (() => obj.GetCheckedHandle (), "GetCheckedHandle 4Vb"); } @@ -112,10 +112,10 @@ public void CtorOwnsVerify () public void Handle () { var obj = new Subclassed (); - Assert.AreEqual (NativeHandle.Zero, obj.Handle, "Handle"); + Assert.That (obj.Handle, Is.EqualTo (NativeHandle.Zero), "Handle"); var ex = Assert.Throws (() => obj.Handle = NativeHandle.Zero, "SetHandle ex"); obj.Handle = (NativeHandle) (IntPtr) 1; - Assert.AreEqual ((NativeHandle) (IntPtr) 1, obj.Handle, "GetHandle"); + Assert.That (obj.Handle, Is.EqualTo ((NativeHandle) (IntPtr) 1), "GetHandle"); } } } diff --git a/tests/monotouch-test/ObjCRuntime/DlfcnTest.cs b/tests/monotouch-test/ObjCRuntime/DlfcnTest.cs index aeda262d8b76..f8a827d39460 100644 --- a/tests/monotouch-test/ObjCRuntime/DlfcnTest.cs +++ b/tests/monotouch-test/ObjCRuntime/DlfcnTest.cs @@ -13,6 +13,53 @@ namespace MonoTouchFixtures.ObjCRuntime { [Preserve (AllMembers = true)] public class DlfcnTest { + // These tests exercise [Field]-backed properties from Apple frameworks. + // The generated binding code calls Dlfcn.GetStringConstant / GetIntPtr / etc. + // under the hood, which is what InlineDlfcnMethodsStep transforms. + + [Test] + public void StringConstant_NSLocaleNotification () + { + var value = NSLocale.CurrentLocaleDidChangeNotification; + Assert.That (value, Is.Not.Null, "CurrentLocaleDidChangeNotification"); + Assert.That ((string) value, Is.EqualTo ("kCFLocaleCurrentLocaleDidChangeNotification"), "value"); + } + + [Test] + public void StringConstant_NSBundleNotification () + { + var value = NSBundle.BundleDidLoadNotification; + Assert.That (value, Is.Not.Null, "BundleDidLoadNotification"); + Assert.That ((string) value, Is.EqualTo ("NSBundleDidLoadNotification"), "value"); + } + + [Test] + public void StringConstant_NSUserDefaultsNotification () + { + var value = NSUserDefaults.DidChangeNotification; + Assert.That (value, Is.Not.Null, "DidChangeNotification"); + Assert.That ((string) value, Is.EqualTo ("NSUserDefaultsDidChangeNotification"), "value"); + } + + [Test] + public void StringConstant_NSUndoManagerNotification () + { + var value = NSUndoManager.CheckpointNotification; + Assert.That (value, Is.Not.Null, "CheckpointNotification"); + Assert.That ((string) value, Is.EqualTo ("NSUndoManagerCheckpointNotification"), "value"); + } + + [Test] + public void StringConstant_CachePointer () + { + // Access several string constants multiple times to test caching behavior. + // The binding code uses Dlfcn.CachePointer for repeated accesses. + for (int i = 0; i < 3; i++) { + var value = NSLocale.CurrentLocaleDidChangeNotification; + Assert.That (value, Is.Not.Null, $"iteration {i}"); + } + } + [Test] public void OpenClose_libSystem () { @@ -32,86 +79,88 @@ public void OpenClose_libSystem () [Test] public void GetVariables () { - var symbol = "x_native_field"; + const string symbol = "x_native_field"; var handle = (IntPtr) Dlfcn.RTLD.Default; - Assert.AreNotEqual (IntPtr.Zero, Dlfcn.dlsym (handle, symbol), "Symbol"); + Assert.That (Dlfcn.dlsym (handle, symbol), Is.Not.EqualTo (IntPtr.Zero), "Symbol"); var originalValue = Dlfcn.GetUInt64 (handle, symbol); Assert.Multiple (() => { unchecked { // the n(uint) and (U)IntPtr asserts only work in 64-bit, which is fine because we only care about 64-bit right now. - Assert.AreEqual ((ushort) 0x8899, (ushort) Dlfcn.GetInt16 (handle, symbol), "GetInt16"); - Assert.AreEqual ((uint) 0xeeff8899, (uint) Dlfcn.GetInt32 (handle, symbol), "GetInt32"); - Assert.AreEqual ((ulong) 0xaabbccddeeff8899, (ulong) Dlfcn.GetInt64 (handle, symbol), "GetInt64"); - Assert.AreEqual ((nuint) 0xaabbccddeeff8899, (nuint) Dlfcn.GetNInt (handle, symbol), "GetNInt"); - Assert.AreEqual ((ushort) 0x8899, Dlfcn.GetUInt16 (handle, symbol), "GetUInt16"); - Assert.AreEqual ((uint) 0xeeff8899, Dlfcn.GetUInt32 (handle, symbol), "GetUInt32"); - Assert.AreEqual ((ulong) 0xaabbccddeeff8899, Dlfcn.GetUInt64 (handle, symbol), "GetUInt64"); - Assert.AreEqual ((nuint) 0xaabbccddeeff8899, Dlfcn.GetNUInt (handle, symbol), "GetNUInt"); - Assert.AreEqual ((nfloat) (-7.757653393002521E-103), Dlfcn.GetNFloat (handle, symbol), "GetNFloat"); - Assert.AreEqual (-7.7576533930025207E-103d, Dlfcn.GetDouble (handle, symbol), "GetDouble"); - Assert.AreEqual ((nuint) 0xaabbccddeeff8899, (nuint) Dlfcn.GetIntPtr (handle, symbol), "GetIntPtr"); // won't work in 32-bit, but we don't care about that anymore - Assert.AreEqual ((nuint) 0xaabbccddeeff8899, Dlfcn.GetUIntPtr (handle, symbol), "GetUIntPtr"); - Assert.AreEqual ((nint) 0xaabbccddeeff8899, Dlfcn.GetStruct (handle, symbol), "GetStruct"); // won't work in 32-bit, but we don't care about that anymore - Assert.AreEqual ((nuint) 0xaabbccddeeff8899, Dlfcn.GetStruct (handle, symbol), "GetStruct"); // won't work in 32-bit, but we don't care about that anymore - Assert.AreEqual ((long) 0xaabbccddeeff8899, Dlfcn.GetStruct (handle, symbol), "GetStruct"); - Assert.AreEqual ((ulong) 0xaabbccddeeff8899, Dlfcn.GetStruct (handle, symbol), "GetStruct"); - Assert.AreEqual ((int) 0xeeff8899, Dlfcn.GetStruct (handle, symbol), "GetStruct"); - Assert.AreEqual ((uint) 0xeeff8899, Dlfcn.GetStruct (handle, symbol), "GetStruct"); - Assert.AreEqual ((ulong) 0xaabbccddeeff8899, Dlfcn.GetStruct (handle, symbol).Value, "GetStruct"); - Assert.AreEqual (-3.9541907E+28f, Dlfcn.GetStruct (handle, symbol), "GetStruct"); - Assert.AreEqual (-7.7576533930025207E-103d, Dlfcn.GetStruct (handle, symbol), "GetStruct"); - - Assert.AreEqual ((ulong) 0, Dlfcn.GetStruct (handle, "inexistent_symbol"), "GetStruct inexistent"); - Assert.AreEqual ((ulong) 0, Dlfcn.GetStruct (handle, "inexistent_symbol").Value, "GetStruct inexistent"); + Assert.That ((ushort) Dlfcn.GetInt16 (handle, symbol), Is.EqualTo ((ushort) 0x8899), "GetInt16"); + Assert.That ((uint) Dlfcn.GetInt32 (handle, symbol), Is.EqualTo ((uint) 0xeeff8899), "GetInt32"); + Assert.That ((ulong) Dlfcn.GetInt64 (handle, symbol), Is.EqualTo ((ulong) 0xaabbccddeeff8899), "GetInt64"); + Assert.That ((nuint) Dlfcn.GetNInt (handle, symbol), Is.EqualTo ((nuint) 0xaabbccddeeff8899), "GetNInt"); + Assert.That (Dlfcn.GetUInt16 (handle, symbol), Is.EqualTo ((ushort) 0x8899), "GetUInt16"); + Assert.That (Dlfcn.GetUInt32 (handle, symbol), Is.EqualTo ((uint) 0xeeff8899), "GetUInt32"); + Assert.That (Dlfcn.GetUInt64 (handle, symbol), Is.EqualTo ((ulong) 0xaabbccddeeff8899), "GetUInt64"); + Assert.That (Dlfcn.GetNUInt (handle, symbol), Is.EqualTo ((nuint) 0xaabbccddeeff8899), "GetNUInt"); + Assert.That (Dlfcn.GetNFloat (handle, symbol), Is.EqualTo ((nfloat) (-7.757653393002521E-103)), "GetNFloat"); + Assert.That (Dlfcn.GetDouble (handle, symbol), Is.EqualTo (-7.7576533930025207E-103d), "GetDouble"); + Assert.That ((nuint) Dlfcn.GetIntPtr (handle, symbol), Is.EqualTo ((nuint) 0xaabbccddeeff8899), "GetIntPtr"); // won't work in 32-bit, but we don't care about that anymore + Assert.That (Dlfcn.GetUIntPtr (handle, symbol), Is.EqualTo ((nuint) 0xaabbccddeeff8899), "GetUIntPtr"); + Assert.That (Dlfcn.GetStruct (handle, symbol), Is.EqualTo ((nint) 0xaabbccddeeff8899), "GetStruct"); // won't work in 32-bit, but we don't care about that anymore + Assert.That (Dlfcn.GetStruct (handle, symbol), Is.EqualTo ((nuint) 0xaabbccddeeff8899), "GetStruct"); // won't work in 32-bit, but we don't care about that anymore + Assert.That (Dlfcn.GetStruct (handle, symbol), Is.EqualTo ((long) 0xaabbccddeeff8899), "GetStruct"); + Assert.That (Dlfcn.GetStruct (handle, symbol), Is.EqualTo ((ulong) 0xaabbccddeeff8899), "GetStruct"); + Assert.That (Dlfcn.GetStruct (handle, symbol), Is.EqualTo ((int) 0xeeff8899), "GetStruct"); + Assert.That (Dlfcn.GetStruct (handle, symbol), Is.EqualTo ((uint) 0xeeff8899), "GetStruct"); + Assert.That (Dlfcn.GetStruct (handle, symbol).Value, Is.EqualTo ((ulong) 0xaabbccddeeff8899), "GetStruct"); + Assert.That (Dlfcn.GetStruct (handle, symbol), Is.EqualTo (-3.9541907E+28f), "GetStruct"); + Assert.That (Dlfcn.GetStruct (handle, symbol), Is.EqualTo (-7.7576533930025207E-103d), "GetStruct"); + +#if !STATIC_NATIVE_SYMBOL_LOOKUP + Assert.That (Dlfcn.GetStruct (handle, "inexistent_symbol"), Is.EqualTo ((ulong) 0), "GetStruct inexistent"); + Assert.That (Dlfcn.GetStruct (handle, "inexistent_symbol").Value, Is.EqualTo ((ulong) 0), "GetStruct inexistent"); +#endif Dlfcn.SetInt16 (handle, symbol, 0x77); - Assert.AreEqual ((short) 0x77, Dlfcn.GetInt16 (handle, symbol), "SetInt16"); + Assert.That (Dlfcn.GetInt16 (handle, symbol), Is.EqualTo ((short) 0x77), "SetInt16"); Dlfcn.SetUInt64 (handle, symbol, originalValue); Dlfcn.SetInt32 (handle, symbol, 0x77); - Assert.AreEqual ((int) 0x77, Dlfcn.GetInt32 (handle, symbol), "SetInt32"); + Assert.That (Dlfcn.GetInt32 (handle, symbol), Is.EqualTo ((int) 0x77), "SetInt32"); Dlfcn.SetUInt64 (handle, symbol, originalValue); Dlfcn.SetInt64 (handle, symbol, 0x77); - Assert.AreEqual ((long) 0x77, Dlfcn.GetInt64 (handle, symbol), "SetInt64"); + Assert.That (Dlfcn.GetInt64 (handle, symbol), Is.EqualTo ((long) 0x77), "SetInt64"); Dlfcn.SetUInt64 (handle, symbol, originalValue); Dlfcn.SetNInt (handle, symbol, 0x77); - Assert.AreEqual ((nint) 0x77, Dlfcn.GetNInt (handle, symbol), "SetNInt"); + Assert.That (Dlfcn.GetNInt (handle, symbol), Is.EqualTo ((nint) 0x77), "SetNInt"); Dlfcn.SetUInt64 (handle, symbol, originalValue); Dlfcn.SetUInt16 (handle, symbol, 0x77); - Assert.AreEqual ((ushort) 0x77, Dlfcn.GetUInt16 (handle, symbol), "SetUInt16"); + Assert.That (Dlfcn.GetUInt16 (handle, symbol), Is.EqualTo ((ushort) 0x77), "SetUInt16"); Dlfcn.SetUInt64 (handle, symbol, originalValue); Dlfcn.SetUInt32 (handle, symbol, 0x77); - Assert.AreEqual ((uint) 0x77, Dlfcn.GetUInt32 (handle, symbol), "SetUInt32"); + Assert.That (Dlfcn.GetUInt32 (handle, symbol), Is.EqualTo ((uint) 0x77), "SetUInt32"); Dlfcn.SetUInt64 (handle, symbol, originalValue); Dlfcn.SetUInt64 (handle, symbol, 0x77); - Assert.AreEqual ((ulong) 0x77, Dlfcn.GetUInt64 (handle, symbol), "SetUInt64"); + Assert.That (Dlfcn.GetUInt64 (handle, symbol), Is.EqualTo ((ulong) 0x77), "SetUInt64"); Dlfcn.SetUInt64 (handle, symbol, originalValue); Dlfcn.SetNUInt (handle, symbol, 0x77); - Assert.AreEqual ((nuint) 0x77, Dlfcn.GetNUInt (handle, symbol), "SetNUInt"); + Assert.That (Dlfcn.GetNUInt (handle, symbol), Is.EqualTo ((nuint) 0x77), "SetNUInt"); Dlfcn.SetUInt64 (handle, symbol, originalValue); Dlfcn.SetNFloat (handle, symbol, 0x77); - Assert.AreEqual ((nfloat) 0x77, Dlfcn.GetNFloat (handle, symbol), "SetNFloat"); + Assert.That (Dlfcn.GetNFloat (handle, symbol), Is.EqualTo ((nfloat) 0x77), "SetNFloat"); Dlfcn.SetUInt64 (handle, symbol, originalValue); Dlfcn.SetDouble (handle, symbol, 0x77); - Assert.AreEqual (0x77, Dlfcn.GetDouble (handle, symbol), "SetDouble"); + Assert.That (Dlfcn.GetDouble (handle, symbol), Is.EqualTo (0x77), "SetDouble"); Dlfcn.SetUInt64 (handle, symbol, originalValue); Dlfcn.SetIntPtr (handle, symbol, 0x77); - Assert.AreEqual ((nint) 0x77, Dlfcn.GetIntPtr (handle, symbol), "SetIntPtr"); + Assert.That (Dlfcn.GetIntPtr (handle, symbol), Is.EqualTo ((nint) 0x77), "SetIntPtr"); Dlfcn.SetUInt64 (handle, symbol, originalValue); Dlfcn.SetUIntPtr (handle, symbol, 0x77); - Assert.AreEqual ((nuint) 0x77, Dlfcn.GetUIntPtr (handle, symbol), "SetUIntPtr"); + Assert.That (Dlfcn.GetUIntPtr (handle, symbol), Is.EqualTo ((nuint) 0x77), "SetUIntPtr"); Dlfcn.SetUInt64 (handle, symbol, originalValue); } }); @@ -122,5 +171,24 @@ struct SomeValue { public ulong Value; } #pragma warning restore CS0649 + + [Test] + public void FieldProperty_CGRect () + { + Assert.Multiple (() => { + // CGRect.Null is backed by [Field("CGRectNull")] which calls Dlfcn.GetCGRect. + var value = global::CoreGraphics.CGRect.Null; + Assert.That (value.X, Is.EqualTo (nfloat.PositiveInfinity), "CGRectNull.X"); + Assert.That (value.Y, Is.EqualTo (nfloat.PositiveInfinity), "CGRectNull.Y"); + Assert.That (value.Width, Is.EqualTo ((nfloat) 0), "CGRectNull.Width"); + Assert.That (value.Height, Is.EqualTo ((nfloat) 0), "CGRectNull.Height"); + + var infinite = global::CoreGraphics.CGRect.Infinite; + Assert.That (infinite.X, Is.EqualTo (nfloat.MinValue / 2), "CGRectInfinite.X"); + Assert.That (infinite.Y, Is.EqualTo (nfloat.MinValue / 2), "CGRectInfinite.Y"); + Assert.That (infinite.Width, Is.EqualTo (nfloat.MaxValue), "CGRectInfinite.Width"); + Assert.That (infinite.Height, Is.EqualTo (nfloat.MaxValue), "CGRectInfinite.Height"); + }); + } } } diff --git a/tests/monotouch-test/ObjCRuntime/EveryFrameworkSmokeTest.cs b/tests/monotouch-test/ObjCRuntime/EveryFrameworkSmokeTest.cs index 33cfce365583..5b9c61d7341b 100644 --- a/tests/monotouch-test/ObjCRuntime/EveryFrameworkSmokeTest.cs +++ b/tests/monotouch-test/ObjCRuntime/EveryFrameworkSmokeTest.cs @@ -85,8 +85,8 @@ LoadStatus CheckLoadFailure (string libraryName, string path) [Test] public void ExpectedLibrariesAreLoaded () { - if (TestRuntime.IsLinkAll) - Assert.Ignore ("This test will fail when all assemblies are linked, since we won't link with all frameworks in that case."); + if (TestRuntime.IsLinkAny) + Assert.Ignore ("This test will fail when assemblies are linked, since we won't link with all frameworks in that case."); List failures = new List (); diff --git a/tests/monotouch-test/ObjCRuntime/ExceptionsTest.cs b/tests/monotouch-test/ObjCRuntime/ExceptionsTest.cs index d6e7226db2be..5c58e9927997 100644 --- a/tests/monotouch-test/ObjCRuntime/ExceptionsTest.cs +++ b/tests/monotouch-test/ObjCRuntime/ExceptionsTest.cs @@ -86,12 +86,12 @@ public void ObjCException () } catch (ObjCException ex) { thrownException = ex; } - Assert.AreEqual ("exception was thrown", thrownException.Reason, "objc reason"); - Assert.AreEqual ("Some exception", thrownException.Name, "objc name"); - Assert.AreEqual (1, objcEventArgs.Count, "objc exception"); - Assert.AreEqual (thrownException.NSException.Handle, objcEventArgs [0].Exception.Handle, "objc exception"); - Assert.AreEqual (defaultObjectiveCExceptionMode, objcEventArgs [0].ExceptionMode, "objc mode"); - Assert.AreEqual (0, managedEventArgs.Count, "managed exception"); + Assert.That (thrownException.Reason, Is.EqualTo ("exception was thrown"), "objc reason"); + Assert.That (thrownException.Name, Is.EqualTo ("Some exception"), "objc name"); + Assert.That (objcEventArgs.Count, Is.EqualTo (1), "objc exception"); + Assert.That (objcEventArgs [0].Exception.Handle, Is.EqualTo (thrownException.NSException.Handle), "objc exception"); + Assert.That (objcEventArgs [0].ExceptionMode, Is.EqualTo (defaultObjectiveCExceptionMode), "objc mode"); + Assert.That (managedEventArgs.Count, Is.EqualTo (0), "managed exception"); } } finally { UninstallHandlers (); @@ -134,23 +134,23 @@ public void ManagedExceptionPassthrough () } catch (Exception ex) { thrownException = ex; } - Assert.AreSame (e.Exception, thrownException, "exception"); + Assert.That (thrownException, Is.SameAs (e.Exception), "exception"); Assert.That (thrownException.Message, Does.StartWith ("3,14"), "1 thrown message"); - Assert.AreSame (typeof (ApplicationException), thrownException.GetType (), "1 thrown type"); + Assert.That (thrownException.GetType (), Is.SameAs (typeof (ApplicationException)), "1 thrown type"); if (hasDebugger) { - Assert.AreEqual (0, objcEventArgs.Count, "1 objc exception"); + Assert.That (objcEventArgs.Count, Is.EqualTo (0), "1 objc exception"); } else { - Assert.AreEqual (1, objcEventArgs.Count, "1 objc exception"); - Assert.AreEqual (defaultObjectiveCExceptionMode, objcEventArgs [0].ExceptionMode, "1 objc mode"); - Assert.AreEqual ("System.ApplicationException", objcEventArgs [0].Exception.Name, "1 objc reason"); + Assert.That (objcEventArgs.Count, Is.EqualTo (1), "1 objc exception"); + Assert.That (objcEventArgs [0].ExceptionMode, Is.EqualTo (defaultObjectiveCExceptionMode), "1 objc mode"); + Assert.That (objcEventArgs [0].Exception.Name, Is.EqualTo ("System.ApplicationException"), "1 objc reason"); Assert.That (objcEventArgs [0].Exception.Reason, Does.StartWith ("3,14"), "1 objc message"); } if (hasDebugger) { - Assert.AreEqual (0, managedEventArgs.Count, "1 managed count"); + Assert.That (managedEventArgs.Count, Is.EqualTo (0), "1 managed count"); } else { - Assert.AreEqual (1, managedEventArgs.Count, "1 managed count"); - Assert.AreEqual (defaultManagedExceptionMode, managedEventArgs [0].ExceptionMode, "1 managed mode"); - Assert.AreSame (thrownException, managedEventArgs [0].Exception, "1 managed exception"); + Assert.That (managedEventArgs.Count, Is.EqualTo (1), "1 managed count"); + Assert.That (managedEventArgs [0].ExceptionMode, Is.EqualTo (defaultManagedExceptionMode), "1 managed mode"); + Assert.That (managedEventArgs [0].Exception, Is.SameAs (thrownException), "1 managed exception"); } ClearExceptionData (); @@ -163,27 +163,27 @@ public void ManagedExceptionPassthrough () thrownException = ex; } if (hasDebugger) { - Assert.AreSame (e.Exception, thrownException, "exception"); + Assert.That (thrownException, Is.SameAs (e.Exception), "exception"); } else { - Assert.AreNotSame (e.Exception, thrownException, "exception"); - Assert.AreSame (typeof (ObjCException), thrownException.GetType (), "2 thrown type"); - Assert.AreEqual ("Caught exception", ((ObjCException) thrownException).Name, "2 thrown name"); + Assert.That (thrownException, Is.Not.SameAs (e.Exception), "exception"); + Assert.That (thrownException.GetType (), Is.SameAs (typeof (ObjCException)), "2 thrown type"); + Assert.That (((ObjCException) thrownException).Name, Is.EqualTo ("Caught exception"), "2 thrown name"); Assert.That (((ObjCException) thrownException).Reason, Does.StartWith ("exception was rethrown"), "2 thrown reason"); } if (hasDebugger) { - Assert.AreEqual (0, objcEventArgs.Count, "2 objc exception"); + Assert.That (objcEventArgs.Count, Is.EqualTo (0), "2 objc exception"); } else { - Assert.AreEqual (1, objcEventArgs.Count, "2 objc exception"); - Assert.AreEqual (defaultObjectiveCExceptionMode, objcEventArgs [0].ExceptionMode, "2 objc mode"); - Assert.AreEqual ("Caught exception", objcEventArgs [0].Exception.Name, "2 objc reason"); + Assert.That (objcEventArgs.Count, Is.EqualTo (1), "2 objc exception"); + Assert.That (objcEventArgs [0].ExceptionMode, Is.EqualTo (defaultObjectiveCExceptionMode), "2 objc mode"); + Assert.That (objcEventArgs [0].Exception.Name, Is.EqualTo ("Caught exception"), "2 objc reason"); Assert.That (objcEventArgs [0].Exception.Reason, Does.StartWith ("exception was rethrown"), "2 objc message"); } if (hasDebugger) { - Assert.AreEqual (0, managedEventArgs.Count, "2 managed count"); + Assert.That (managedEventArgs.Count, Is.EqualTo (0), "2 managed count"); } else { - Assert.AreEqual (1, managedEventArgs.Count, "2 managed count"); - Assert.AreEqual (defaultManagedExceptionMode, managedEventArgs [0].ExceptionMode, "2 managed mode"); - Assert.AreSame (e.Exception, managedEventArgs [0].Exception, "2 managed exception"); + Assert.That (managedEventArgs.Count, Is.EqualTo (1), "2 managed count"); + Assert.That (managedEventArgs [0].ExceptionMode, Is.EqualTo (defaultManagedExceptionMode), "2 managed mode"); + Assert.That (managedEventArgs [0].Exception, Is.SameAs (e.Exception), "2 managed exception"); } ClearExceptionData (); @@ -191,10 +191,10 @@ public void ManagedExceptionPassthrough () objcTargetMode = MarshalObjectiveCExceptionMode.ThrowManagedException; managedTargetMode = MarshalManagedExceptionMode.ThrowObjectiveCException; e.InvokeManagedExceptionThrowerAndCatch (); // no exception. - Assert.AreEqual (0, objcEventArgs.Count, "3 objc exception"); - Assert.AreEqual (1, managedEventArgs.Count, "3 managed count"); - Assert.AreEqual (defaultManagedExceptionMode, managedEventArgs [0].ExceptionMode, "3 managed mode"); - Assert.AreSame (e.Exception, managedEventArgs [0].Exception, "3 managed exception"); + Assert.That (objcEventArgs.Count, Is.EqualTo (0), "3 objc exception"); + Assert.That (managedEventArgs.Count, Is.EqualTo (1), "3 managed count"); + Assert.That (managedEventArgs [0].ExceptionMode, Is.EqualTo (defaultManagedExceptionMode), "3 managed mode"); + Assert.That (managedEventArgs [0].Exception, Is.SameAs (e.Exception), "3 managed exception"); } } } finally { diff --git a/tests/monotouch-test/ObjCRuntime/GCHandleSwitchRaceTest.cs b/tests/monotouch-test/ObjCRuntime/GCHandleSwitchRaceTest.cs index 866625f472e6..167c0b0f794c 100644 --- a/tests/monotouch-test/ObjCRuntime/GCHandleSwitchRaceTest.cs +++ b/tests/monotouch-test/ObjCRuntime/GCHandleSwitchRaceTest.cs @@ -73,8 +73,8 @@ public void RunTest () if (!fetchThread.Join (TimeSpan.FromSeconds (30))) Assert.Fail ("Fetch thread is hung."); - Assert.IsNull (switchException, $"Switch thread failed: {switchException}"); - Assert.IsNull (fetchException, $"Fetch thread failed: {fetchException}"); + Assert.That (switchException, Is.Null, $"Switch thread failed: {switchException}"); + Assert.That (fetchException, Is.Null, $"Fetch thread failed: {fetchException}"); } } } diff --git a/tests/monotouch-test/ObjCRuntime/NativeHandleTest.cs b/tests/monotouch-test/ObjCRuntime/NativeHandleTest.cs index b9cb0c8f5c56..ec97cdd912ea 100644 --- a/tests/monotouch-test/ObjCRuntime/NativeHandleTest.cs +++ b/tests/monotouch-test/ObjCRuntime/NativeHandleTest.cs @@ -8,10 +8,10 @@ public unsafe void Operators () { IntPtr value = new IntPtr (0xdadf00d); - Assert.AreEqual (value, ((NativeHandle) value).Handle, "IntPtr -> NativeHandle"); - Assert.AreEqual (value, (IntPtr) new NativeHandle (value), "NativeHandle -> IntPtr"); - Assert.AreEqual (value, ((NativeHandle) ((void*) value)).Handle, "void* -> NativeHandle"); - Assert.AreEqual (value, (IntPtr) (void*) new NativeHandle (value), "NativeHandle -> void*"); + Assert.That (((NativeHandle) value).Handle, Is.EqualTo (value), "IntPtr -> NativeHandle"); + Assert.That ((IntPtr) new NativeHandle (value), Is.EqualTo (value), "NativeHandle -> IntPtr"); + Assert.That (((NativeHandle) ((void*) value)).Handle, Is.EqualTo (value), "void* -> NativeHandle"); + Assert.That ((IntPtr) (void*) new NativeHandle (value), Is.EqualTo (value), "NativeHandle -> void*"); } } } diff --git a/tests/monotouch-test/ObjCRuntime/ProtocolTest.cs b/tests/monotouch-test/ObjCRuntime/ProtocolTest.cs index fea96b3b3618..61f7dd23ddfc 100644 --- a/tests/monotouch-test/ObjCRuntime/ProtocolTest.cs +++ b/tests/monotouch-test/ObjCRuntime/ProtocolTest.cs @@ -24,12 +24,12 @@ public void Ctors () }; foreach (var d in data) { - Assert.AreNotEqual (IntPtr.Zero, new Protocol (d.Type).Handle, $"{d.Name} type"); - Assert.AreNotEqual (IntPtr.Zero, new Protocol (d.Name).Handle, $"{d.Name} string"); - Assert.AreEqual (d.Name, new Protocol (d.Name).Name, $"{d.Name} name"); - Assert.AreEqual (d.Name, new Protocol (d.Type).Name, $"{d.Name} type name"); - Assert.AreEqual (d.Name, new Protocol (new Protocol (d.Name).Handle).Name, $"{d.Name} IntPtr name"); - Assert.AreEqual (d.Name, new Protocol (Protocol.GetHandle (d.Name)).Name, $"{d.Name} GetHandle name"); + Assert.That (new Protocol (d.Type).Handle, Is.Not.EqualTo (IntPtr.Zero), $"{d.Name} type"); + Assert.That (new Protocol (d.Name).Handle, Is.Not.EqualTo (IntPtr.Zero), $"{d.Name} string"); + Assert.That (new Protocol (d.Name).Name, Is.EqualTo (d.Name), $"{d.Name} name"); + Assert.That (new Protocol (d.Type).Name, Is.EqualTo (d.Name), $"{d.Name} type name"); + Assert.That (new Protocol (new Protocol (d.Name).Handle).Name, Is.EqualTo (d.Name), $"{d.Name} IntPtr name"); + Assert.That (new Protocol (Protocol.GetHandle (d.Name)).Name, Is.EqualTo (d.Name), $"{d.Name} GetHandle name"); } } } diff --git a/tests/monotouch-test/ObjCRuntime/RegistrarTest.cs b/tests/monotouch-test/ObjCRuntime/RegistrarTest.cs index 758c6dd9f3ee..b1f2ef35a054 100644 --- a/tests/monotouch-test/ObjCRuntime/RegistrarTest.cs +++ b/tests/monotouch-test/ObjCRuntime/RegistrarTest.cs @@ -103,22 +103,22 @@ public void NSRangeOutParameter () var a = new _LongNSRange (-1, -2); var c = new _LongNSRange (-5, -6); Messaging.void_objc_msgSend_NSRange_out_NSRange_ref_NSRange (obj.Handle, Selector.GetHandle ("passRange:getRange:refRange:"), a, out var b, ref c); - Assert.AreEqual (a.Location, (long) (-1), "post a Location"); - Assert.AreEqual (a.Length, (long) (-2), "post a Length"); - Assert.AreEqual (b.Location, (long) 3, "post b Location"); - Assert.AreEqual (b.Length, (long) 4, "post b Length"); - Assert.AreEqual (c.Location, (long) 5, "post c Location"); - Assert.AreEqual (c.Length, (long) 6, "post c Length"); + Assert.That ((long) (-1), Is.EqualTo (a.Location), "post a Location"); + Assert.That ((long) (-2), Is.EqualTo (a.Length), "post a Length"); + Assert.That ((long) 3, Is.EqualTo (b.Location), "post b Location"); + Assert.That ((long) 4, Is.EqualTo (b.Length), "post b Length"); + Assert.That ((long) 5, Is.EqualTo (c.Location), "post c Location"); + Assert.That ((long) 6, Is.EqualTo (c.Length), "post c Length"); } class NSRangeOutParameterClass : NSObject { [Export ("passRange:getRange:refRange:")] public void DoIt (_LongNSRange a, out _LongNSRange b, ref _LongNSRange c) { - Assert.AreEqual (a.Location, (long) (-1), "a Location"); - Assert.AreEqual (a.Length, (long) (-2), "a Length"); - Assert.AreEqual (c.Location, (long) (-5), "c Location"); - Assert.AreEqual (c.Length, (long) (-6), "c Length"); + Assert.That ((long) (-1), Is.EqualTo (a.Location), "a Location"); + Assert.That ((long) (-2), Is.EqualTo (a.Length), "a Length"); + Assert.That ((long) (-5), Is.EqualTo (c.Location), "c Location"); + Assert.That ((long) (-6), Is.EqualTo (c.Length), "c Length"); a = new _LongNSRange (1, 2); b = new _LongNSRange (3, 4); @@ -139,8 +139,8 @@ public void RegistrarRemoval () #else var shouldBeRemoved = false; #endif - Assert.AreEqual (shouldBeRemoved, typeof (NSObject).Assembly.GetType ("Registrar.Registrar") is null, "Registrar removal"); - Assert.AreEqual (shouldBeRemoved, typeof (NSObject).Assembly.GetType ("Registrar.DynamicRegistrar") is null, "DynamicRegistrar removal"); + Assert.That (typeof (NSObject).Assembly.GetType ("Registrar.Registrar") is null, Is.EqualTo (shouldBeRemoved), "Registrar removal"); + Assert.That (typeof (NSObject).Assembly.GetType ("Registrar.DynamicRegistrar") is null, Is.EqualTo (shouldBeRemoved), "DynamicRegistrar removal"); } #if !MONOMAC @@ -239,8 +239,8 @@ public void TestINativeObject () if (!global::XamarinTests.ObjCRuntime.Registrar.IsStaticRegistrar) Assert.Ignore ("This test only passes with the static registrars."); - Assert.False (Messaging.bool_objc_msgSend_IntPtr (receiver, new Selector ("INativeObject1:").Handle, NativeHandle.Zero), "#a1"); - Assert.True (Messaging.bool_objc_msgSend_IntPtr (receiver, new Selector ("INativeObject1:").Handle, new CGPath ().Handle), "#a2"); + Assert.That (Messaging.bool_objc_msgSend_IntPtr (receiver, new Selector ("INativeObject1:").Handle, NativeHandle.Zero), Is.False, "#a1"); + Assert.That (Messaging.bool_objc_msgSend_IntPtr (receiver, new Selector ("INativeObject1:").Handle, new CGPath ().Handle), Is.True, "#a2"); Assert.That ((NativeHandle) Messaging.IntPtr_objc_msgSend_bool (receiver, new Selector ("INativeObject2:").Handle, false), Is.EqualTo (NativeHandle.Zero), "#b1"); ptr = Messaging.IntPtr_objc_msgSend_bool (receiver, new Selector ("INativeObject2:").Handle, true); @@ -254,11 +254,11 @@ public void TestINativeObject () path = null; ptr = NativeHandle.Zero; - Assert.False (bool_objc_msgSend_ref_intptr (receiver, new Selector ("INativeObject4:").Handle, ref ptr), "#d1"); + Assert.That (bool_objc_msgSend_ref_intptr (receiver, new Selector ("INativeObject4:").Handle, ref ptr), Is.False, "#d1"); Assert.That (ptr, Is.EqualTo (NativeHandle.Zero), "#d2"); path = new CGPath (); ptr = path.Handle; - Assert.True (bool_objc_msgSend_ref_intptr (receiver, new Selector ("INativeObject4:").Handle, ref ptr), "#d3"); + Assert.That (bool_objc_msgSend_ref_intptr (receiver, new Selector ("INativeObject4:").Handle, ref ptr), Is.True, "#d3"); Assert.That (ptr, Is.EqualTo (path.Handle), "#d4"); ptr = Messaging.IntPtr_objc_msgSend_bool (receiver, new Selector ("INativeObject5:").Handle, false); @@ -293,7 +293,7 @@ public void TestOutNSString () void_objc_msgSend_out_IntPtr (obj.Handle, sel.Handle, out var ptr); - Assert.AreEqual ("Santa is coming", NSString.FromHandle (ptr), "#santa"); + Assert.That (NSString.FromHandle (ptr), Is.EqualTo ("Santa is coming"), "#santa"); } [Test] @@ -303,9 +303,9 @@ public void TestInheritedStaticMethods () int rv; rv = Messaging.int_objc_msgSend (Class.GetHandle (typeof (StaticBaseClass)), Selector.GetHandle ("foo")); - Assert.AreEqual (rv, 314, "#base"); + Assert.That (rv, Is.EqualTo (314), "#base"); rv = Messaging.int_objc_msgSend (Class.GetHandle (typeof (StaticDerivedClass)), Selector.GetHandle ("foo")); - Assert.AreEqual (rv, 314, "#derived"); + Assert.That (rv, Is.EqualTo (314), "#derived"); } [Test] @@ -319,7 +319,7 @@ public void TestStructAndOut () void_objc_msgSend_SizeF_IntPtr_out_IntPtr (obj.Handle, sel.Handle, size, value.Handle, out ptr); - Assert.AreEqual (value.Handle, ptr, "#1"); + Assert.That (ptr, Is.EqualTo (value.Handle), "#1"); } #if !__TVOS__ && !MONOMAC @@ -400,19 +400,18 @@ public void TestThreadSafety () } // Wait for X "I'm ready" signals - Assert.IsTrue (start_counter.Wait (1000), "all threads didn't spin up in 1s"); + Assert.That (start_counter.Wait (1000), Is.True, "all threads didn't spin up in 1s"); wait.Set (); // let the threads go wild. - Assert.IsTrue (end_counter.Wait (5000), "all threads didn't finish testing in 5s"); + Assert.That (end_counter.Wait (5000), Is.True, "all threads didn't finish testing in 5s"); for (int i = 0; i < threads.Length; i++) { - Assert.IsTrue (threads [i].Join (1000), "join #" + i.ToString ()); + Assert.That (threads [i].Join (1000), Is.True, "join #" + i.ToString ()); } if (exceptions.Count > 0) { - Assert.Fail ("Expected no exceptions, but got:\n{0}", - new AggregateException (exceptions).ToString ()); + Assert.Fail ($"Expected no exceptions, but got:\n{new AggregateException (exceptions).ToString ()}"); } } @@ -431,32 +430,32 @@ public void TestRetainReturnValue () using (var pool = new NSAutoreleasePool ()) ptr = Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("testRetainArray")); using (var rv = Runtime.GetNSObject (ptr)) { - Assert.AreEqual ((nuint) 2, rv.RetainCount, "array"); - Assert.AreSame (typeof (NSArray), rv.GetType (), "array type"); + Assert.That (rv.RetainCount, Is.EqualTo ((nuint) 2), "array"); + Assert.That (rv.GetType (), Is.SameAs (typeof (NSArray)), "array type"); rv.DangerousRelease (); } using (var pool = new NSAutoreleasePool ()) ptr = Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("testReturnINativeObject")); using (var rv = Runtime.GetNSObject (ptr)) { - Assert.AreEqual ((nuint) 2, rv.RetainCount, "inativeobject"); - Assert.AreSame (typeof (NSObject), rv.GetType (), "inativeobject type"); + Assert.That (rv.RetainCount, Is.EqualTo ((nuint) 2), "inativeobject"); + Assert.That (rv.GetType (), Is.SameAs (typeof (NSObject)), "inativeobject type"); rv.DangerousRelease (); } using (var pool = new NSAutoreleasePool ()) ptr = Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("testRetainNSObject")); using (var rv = Runtime.GetNSObject (ptr)) { - Assert.AreEqual ((nuint) 2, rv.RetainCount, "nsobject"); - Assert.AreSame (typeof (NSObject), rv.GetType (), "nsobject type"); + Assert.That (rv.RetainCount, Is.EqualTo ((nuint) 2), "nsobject"); + Assert.That (rv.GetType (), Is.SameAs (typeof (NSObject)), "nsobject type"); rv.DangerousRelease (); } using (var pool = new NSAutoreleasePool ()) ptr = Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("testRetainString")); using (var rv = Runtime.GetNSObject (ptr)) { - Assert.AreEqual ((nuint) 2, rv.RetainCount, "string"); - Assert.IsTrue (rv is NSString, "string type"); + Assert.That (rv.RetainCount, Is.EqualTo ((nuint) 2), "string"); + Assert.That (rv is NSString, Is.True, "string type"); rv.DangerousRelease (); } } @@ -465,8 +464,8 @@ public void TestRetainReturnValue () using (var pool = new NSAutoreleasePool ()) ptr = Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("testOverriddenRetainNSObject")); using (var rv = Runtime.GetNSObject (ptr)) { - Assert.AreEqual ((nuint) 2, rv.RetainCount, "overridden nsobject"); - Assert.AreSame (typeof (NSObject), rv.GetType (), "overridden nsobject type"); + Assert.That (rv.RetainCount, Is.EqualTo ((nuint) 2), "overridden nsobject"); + Assert.That (rv.GetType (), Is.SameAs (typeof (NSObject)), "overridden nsobject type"); rv.DangerousRelease (); } @@ -485,7 +484,7 @@ public string MyProp { public void TestObjCProperties () { var class_handle = Class.GetHandle (typeof (Props)); - Assert.AreNotEqual (IntPtr.Zero, class_getProperty (class_handle, "myProp")); + Assert.That (class_getProperty (class_handle, "myProp"), Is.Not.EqualTo (IntPtr.Zero)); } [DllImport ("/usr/lib/libobjc.dylib")] @@ -501,7 +500,7 @@ public void TestObjCProperties () public void TestNonVirtualProperty () { using (var obj = new DerivedRegistrar1 ()) { - Assert.IsTrue (Messaging.bool_objc_msgSend (obj.Handle, Selector.GetHandle ("b1"))); + Assert.That (Messaging.bool_objc_msgSend (obj.Handle, Selector.GetHandle ("b1")), Is.True); } } @@ -519,10 +518,10 @@ public void TestGeneric () string t3 = NSString.FromHandle (Messaging.IntPtr_objc_msgSend (g3.Handle, sel)).ToString (); string t4 = NSString.FromHandle (Messaging.IntPtr_objc_msgSend (g4.Handle, sel)).ToString (); - Assert.AreEqual (g1.GetTypeFullName (), t1, "#t1"); - Assert.AreEqual (g2.GetTypeFullName (), t2, "#t2"); - Assert.AreEqual (g3.GetTypeFullName (), t3, "#t3"); - Assert.AreEqual (g4.GetTypeFullName (), t4, "#t4"); + Assert.That (t1, Is.EqualTo (g1.GetTypeFullName ()), "#t1"); + Assert.That (t2, Is.EqualTo (g2.GetTypeFullName ()), "#t2"); + Assert.That (t3, Is.EqualTo (g3.GetTypeFullName ()), "#t3"); + Assert.That (t4, Is.EqualTo (g4.GetTypeFullName ()), "#t4"); var openClass = Class.GetHandle ("Open_1"); var handle = Messaging.IntPtr_objc_msgSend (openClass, Selector.GetHandle ("alloc")); @@ -566,43 +565,43 @@ public void TestInstanceMethodOnOpenGenericType () var expectedU = typeof (NSSet); var expectedV = typeof (string); Messaging.void_objc_msgSend_IntPtr (foo.Handle, Selector.GetHandle ("bar:"), IntPtr.Zero); - Assert.IsNull (foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (foo.LastArg, Is.Null); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); Messaging.void_objc_msgSend_IntPtr (foo.Handle, Selector.GetHandle ("bar:"), view.Handle); - Assert.AreSame (view, foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (foo.LastArg, Is.SameAs (view)); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); var arr = NSArray.FromNSObjects (view); Messaging.void_objc_msgSend_IntPtr (foo.Handle, Selector.GetHandle ("zap:"), IntPtr.Zero); - Assert.IsNull (foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (foo.LastArg, Is.Null); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); Messaging.void_objc_msgSend_IntPtr (foo.Handle, Selector.GetHandle ("zap:"), arr.Handle); - Assert.AreSame (view, ((object []) foo.LastArg) [0]); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (((object []) foo.LastArg) [0], Is.SameAs (view)); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); - Assert.AreEqual (IntPtr.Zero, Messaging.IntPtr_objc_msgSend (foo.Handle, Selector.GetHandle ("xyz")), "xyz"); - Assert.IsNull (foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (Messaging.IntPtr_objc_msgSend (foo.Handle, Selector.GetHandle ("xyz")), Is.EqualTo (IntPtr.Zero), "xyz"); + Assert.That (foo.LastArg, Is.Null); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); - Assert.AreEqual (IntPtr.Zero, Messaging.IntPtr_objc_msgSend (foo.Handle, Selector.GetHandle ("barzap")), "barzap"); - Assert.IsNull (foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (Messaging.IntPtr_objc_msgSend (foo.Handle, Selector.GetHandle ("barzap")), Is.EqualTo (IntPtr.Zero), "barzap"); + Assert.That (foo.LastArg, Is.Null); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); Messaging.void_objc_msgSend_IntPtr (foo.Handle, Selector.GetHandle ("setBarzap:"), IntPtr.Zero); - Assert.IsNull (foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (foo.LastArg, Is.Null); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); Messaging.void_objc_msgSend_IntPtr (foo.Handle, Selector.GetHandle ("setBarzap:"), view.Handle); - Assert.AreSame (view, foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (foo.LastArg, Is.SameAs (view)); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); arr.Dispose (); view.Dispose (); @@ -616,43 +615,43 @@ public void TestInstanceMethodOnOpenGenericType () var expectedU = typeof (NSObject); var expectedV = typeof (int); Messaging.void_objc_msgSend_IntPtr (foo.Handle, Selector.GetHandle ("bar:"), IntPtr.Zero); - Assert.IsNull (foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (foo.LastArg, Is.Null); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); Messaging.void_objc_msgSend_IntPtr (foo.Handle, Selector.GetHandle ("bar:"), view.Handle); - Assert.AreSame (view, foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (foo.LastArg, Is.SameAs (view)); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); var arr = NSArray.FromNSObjects (view); Messaging.void_objc_msgSend_IntPtr (foo.Handle, Selector.GetHandle ("zap:"), IntPtr.Zero); - Assert.IsNull (foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (foo.LastArg, Is.Null); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); Messaging.void_objc_msgSend_IntPtr (foo.Handle, Selector.GetHandle ("zap:"), arr.Handle); - Assert.AreSame (view, ((object []) foo.LastArg) [0]); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (((object []) foo.LastArg) [0], Is.SameAs (view)); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); - Assert.AreEqual (IntPtr.Zero, Messaging.IntPtr_objc_msgSend (foo.Handle, Selector.GetHandle ("xyz")), "xyz"); - Assert.IsNull (foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (Messaging.IntPtr_objc_msgSend (foo.Handle, Selector.GetHandle ("xyz")), Is.EqualTo (IntPtr.Zero), "xyz"); + Assert.That (foo.LastArg, Is.Null); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); - Assert.AreEqual (IntPtr.Zero, Messaging.IntPtr_objc_msgSend (foo.Handle, Selector.GetHandle ("barzap")), "barzap"); - Assert.IsNull (foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (Messaging.IntPtr_objc_msgSend (foo.Handle, Selector.GetHandle ("barzap")), Is.EqualTo (IntPtr.Zero), "barzap"); + Assert.That (foo.LastArg, Is.Null); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); Messaging.void_objc_msgSend_IntPtr (foo.Handle, Selector.GetHandle ("setBarzap:"), IntPtr.Zero); - Assert.IsNull (foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (foo.LastArg, Is.Null); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); Messaging.void_objc_msgSend_IntPtr (foo.Handle, Selector.GetHandle ("setBarzap:"), view.Handle); - Assert.AreSame (view, foo.LastArg); - Assert.AreEqual (expectedU, foo.UType); - Assert.AreEqual (expectedV, foo.VType); + Assert.That (foo.LastArg, Is.SameAs (view)); + Assert.That (foo.UType, Is.EqualTo (expectedU)); + Assert.That (foo.VType, Is.EqualTo (expectedV)); arr.Dispose (); view.Dispose (); @@ -667,11 +666,11 @@ public void TestGenericUIView () using (var iview = new NullableIntView (new CGRect (0, 0, 100, 100))) { using (var strview = new StringView (new CGRect (0, 0, 100, 100))) { Messaging.void_objc_msgSend_CGRect (iview.Handle, Selector.GetHandle ("drawRect:"), CGRect.Empty); - Assert.AreEqual (typeof (int?), iview.TypeT, "int?"); - Assert.AreEqual ("NullableIntView", iview.TypeName, "int? typename"); + Assert.That (iview.TypeT, Is.EqualTo (typeof (int?)), "int?"); + Assert.That (iview.TypeName, Is.EqualTo ("NullableIntView"), "int? typename"); Messaging.void_objc_msgSend_CGRect (strview.Handle, Selector.GetHandle ("drawRect:"), CGRect.Empty); - Assert.AreEqual (typeof (string), strview.TypeT, "string"); - Assert.AreEqual ("StringView", strview.TypeName, "string typename"); + Assert.That (strview.TypeT, Is.EqualTo (typeof (string)), "string"); + Assert.That (strview.TypeName, Is.EqualTo ("StringView"), "string typename"); } } } @@ -697,10 +696,10 @@ public void TestNativeEnum () } if (IntPtr.Size == 4) { - Assert.AreEqual ((int) UIPopoverArrowDirection.Right, Messaging.int_objc_msgSend (obj.Handle, Selector.GetHandle ("testNativeEnum2")), "testNativeEnum2"); + Assert.That (Messaging.int_objc_msgSend (obj.Handle, Selector.GetHandle ("testNativeEnum2")), Is.EqualTo ((int) UIPopoverArrowDirection.Right), "testNativeEnum2"); Messaging.void_objc_msgSend_int (obj.Handle, Selector.GetHandle ("setTestNativeEnum2:"), (int) UIPopoverArrowDirection.Left); } else { - Assert.AreEqual ((long) UIPopoverArrowDirection.Right, Messaging.long_objc_msgSend (obj.Handle, Selector.GetHandle ("testNativeEnum2")), "testNativeEnum2"); + Assert.That (Messaging.long_objc_msgSend (obj.Handle, Selector.GetHandle ("testNativeEnum2")), Is.EqualTo ((long) UIPopoverArrowDirection.Right), "testNativeEnum2"); Messaging.void_objc_msgSend_long (obj.Handle, Selector.GetHandle ("setTestNativeEnum2:"), (long) UIPopoverArrowDirection.Left); } } @@ -728,8 +727,8 @@ public void TestCGPointParameter () var pnt1 = new CGPoint (123, 456); PointF pnt2 = new CGPoint (); void_objc_msgSend_CGPoint_ref_CGPoint (obj.Handle, Selector.GetHandle ("testCGPoint:out:"), pnt1, ref pnt2); - Assert.AreEqual ((nfloat) 123, pnt2.X, "X"); - Assert.AreEqual ((nfloat) 456, pnt2.Y, "Y"); + Assert.That (pnt2.X, Is.EqualTo ((nfloat) 123), "X"); + Assert.That (pnt2.Y, Is.EqualTo ((nfloat) 456), "Y"); } } @@ -738,25 +737,25 @@ public void ExportedGenericsTest () { using (var obj = new RegistrarTestClass ()) { var rv = Runtime.GetNSObject> (Messaging.IntPtr_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("fetchNSArrayOfNSString:"), IntPtr.Zero)); - Assert.IsNotNull (rv, "method"); + Assert.That (rv, Is.Not.Null, "method"); using (var number_array = NSArray.FromNSObjects ((NSNumber) 314)) { rv = Runtime.GetNSObject> (Messaging.IntPtr_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("fetchNSArrayOfNSString:"), number_array.Handle)); - Assert.IsNotNull (rv, "method param"); + Assert.That (rv, Is.Not.Null, "method param"); } rv = Runtime.GetNSObject> (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("nSArrayOfNSString"))); - Assert.IsNotNull (rv, "property"); + Assert.That (rv, Is.Not.Null, "property"); Messaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("setNSArrayOfNSString:"), IntPtr.Zero); Messaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("setNSArrayOfNSString:"), rv.Handle); var rv2 = Runtime.GetNSObject>> (Messaging.IntPtr_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("fetchComplexGenericType:"), IntPtr.Zero)); - Assert.IsNotNull (rv2, "complex"); + Assert.That (rv2, Is.Not.Null, "complex"); using (var complex = new NSArray>> ()) { Runtime.GetNSObject>> (Messaging.IntPtr_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("fetchComplexGenericType:"), complex.Handle)); - Assert.IsNotNull (rv2, "complex param"); + Assert.That (rv2, Is.Not.Null, "complex param"); } } } @@ -1028,7 +1027,7 @@ public virtual NSObject TestOverriddenRetainNSObject () [Export ("testNativeEnum1:")] public virtual void TestNativeEnum1 (NSWritingDirection twd) { - Assert.That (Enum.GetValues (), Contains.Item (twd), "TestNativeEnum1"); + Assert.That (Enum.GetValues ().Contains (twd), "TestNativeEnum1"); } public virtual UIPopoverArrowDirection TestNativeEnum2 { @@ -1038,7 +1037,7 @@ public virtual UIPopoverArrowDirection TestNativeEnum2 { } [Export ("setTestNativeEnum2:")] set { - Assert.AreEqual (UIPopoverArrowDirection.Left, value, "setTestNativeEnum2:"); + Assert.That (value, Is.EqualTo (UIPopoverArrowDirection.Left), "setTestNativeEnum2:"); } } @@ -1047,8 +1046,8 @@ public virtual UIPopoverArrowDirection TestNativeEnum2 { public virtual void TestNativeEnum1 (NSWritingDirection twd, int a, long b) { Assert.That (Enum.GetValues (), Contains.Item (twd), "TestNativeEnum3"); - Assert.AreEqual (31415, a, "TestNativeEnum3 a"); - Assert.AreEqual (3141592, b, "TestNativeEnum3 b"); + Assert.That (a, Is.EqualTo (31415), "TestNativeEnum3 a"); + Assert.That (b, Is.EqualTo (3141592), "TestNativeEnum3 b"); } #endif // !MONOMAC @@ -1288,12 +1287,12 @@ public override string GetTypeFullName () [Test] public void TestRegisteredName () { - Assert.AreEqual ("MonoTouchFixtures_ObjCRuntime_RegistrarTest_ConstrainedGenericType_1", new Class (typeof (ConstrainedGenericType<>)).Name); - Assert.AreEqual ("MonoTouchFixtures_ObjCRuntime_RegistrarTest_ConstrainedGenericType_1", new Class (typeof (ConstrainedGenericType)).Name); - Assert.AreEqual ("MonoTouchFixtures_ObjCRuntime_RegistrarTest_NestedParent_1_Nested", new Class (typeof (NestedParent.Nested)).Name); - Assert.AreEqual ("UnderlyingEnumValues", new Class (typeof (UnderlyingEnumValues)).Name); - Assert.AreEqual ("MonoTouchFixtures_ObjCRuntime_RegistrarTest_Nested1_Dummy", new Class (typeof (Nested1.Dummy)).Name); - Assert.AreEqual ("MonoTouchFixtures_ObjCRuntime_RegistrarTest_C", new Class (typeof (C)).Name); + Assert.That (new Class (typeof (ConstrainedGenericType<>)).Name, Is.EqualTo ("MonoTouchFixtures_ObjCRuntime_RegistrarTest_ConstrainedGenericType_1")); + Assert.That (new Class (typeof (ConstrainedGenericType)).Name, Is.EqualTo ("MonoTouchFixtures_ObjCRuntime_RegistrarTest_ConstrainedGenericType_1")); + Assert.That (new Class (typeof (NestedParent.Nested)).Name, Is.EqualTo ("MonoTouchFixtures_ObjCRuntime_RegistrarTest_NestedParent_1_Nested")); + Assert.That (new Class (typeof (UnderlyingEnumValues)).Name, Is.EqualTo ("UnderlyingEnumValues")); + Assert.That (new Class (typeof (Nested1.Dummy)).Name, Is.EqualTo ("MonoTouchFixtures_ObjCRuntime_RegistrarTest_Nested1_Dummy")); + Assert.That (new Class (typeof (C)).Name, Is.EqualTo ("MonoTouchFixtures_ObjCRuntime_RegistrarTest_C")); } void ThrowsICEIfDebug (TestDelegate code, string message, bool execute_release_mode = true) @@ -1352,24 +1351,24 @@ public void TestConstrainedGenericType () // m2 value = NativeHandle.Zero; void_objc_msgSend_out_IntPtr (obj.Handle, Selector.GetHandle ("m2:"), out value); - Assert.AreEqual (NativeHandle.Zero, value); + Assert.That (value, Is.EqualTo (NativeHandle.Zero)); value = view.Handle; void_objc_msgSend_out_IntPtr (obj.Handle, Selector.GetHandle ("m2:"), out value); - Assert.AreEqual (NativeHandle.Zero, value); + Assert.That (value, Is.EqualTo (NativeHandle.Zero)); value = (NativeHandle) new IntPtr ((unchecked((int) 0xdeadbeef))); void_objc_msgSend_out_IntPtr (obj.Handle, Selector.GetHandle ("m2:"), out value); - Assert.AreEqual (NativeHandle.Zero, value); + Assert.That (value, Is.EqualTo (NativeHandle.Zero)); // m3 value = NativeHandle.Zero; void_objc_msgSend_ref_IntPtr (obj.Handle, Selector.GetHandle ("m3:"), ref value); - Assert.AreEqual (NativeHandle.Zero, value); + Assert.That (value, Is.EqualTo (NativeHandle.Zero)); value = view.Handle; void_objc_msgSend_ref_IntPtr (obj.Handle, Selector.GetHandle ("m3:"), ref value); - Assert.AreEqual (view.Handle, value); + Assert.That (value, Is.EqualTo (view.Handle)); value = nsobj.Handle; ThrowsICEIfDebug (() => void_objc_msgSend_ref_IntPtr (obj.Handle, Selector.GetHandle ("m3:"), ref value), "m3 ICE"); @@ -1386,19 +1385,19 @@ public void TestConstrainedGenericType () } // r1 - Assert.AreEqual (NativeHandle.Zero, (NativeHandle) Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("r1"))); + Assert.That ((NativeHandle) Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("r1")), Is.EqualTo (NativeHandle.Zero)); // r2 - Assert.AreEqual (NativeHandle.Zero, (NativeHandle) Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("r2"))); + Assert.That ((NativeHandle) Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("r2")), Is.EqualTo (NativeHandle.Zero)); // p1 - Assert.AreEqual (NativeHandle.Zero, (NativeHandle) Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("p1"))); + Assert.That ((NativeHandle) Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("p1")), Is.EqualTo (NativeHandle.Zero)); Messaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("setP1:"), NativeHandle.Zero); Messaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("setP1:"), view.Handle); ThrowsICEIfDebug (() => Messaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("setP1:"), nsobj.Handle), "setP1: ICE"); // p2 - Assert.AreEqual (NativeHandle.Zero, (NativeHandle) Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("p2"))); + Assert.That ((NativeHandle) Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("p2")), Is.EqualTo (NativeHandle.Zero)); Messaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("setP2:"), NativeHandle.Zero); ThrowsICEIfDebug (() => Messaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("setP2:"), nsobj.Handle), "setP2: ICE", false); @@ -1420,8 +1419,8 @@ public void TestConstrainedGenericType () public void TestCopyWithZone () { using (var cc = new CopyClass ()) { - Assert.AreEqual (cc.Handle, (NativeHandle) Messaging.IntPtr_objc_msgSend_IntPtr (cc.Handle, Selector.GetHandle ("copyWithZone:"), NativeHandle.Zero), "a"); - Assert.IsFalse (cc.had_zone.Value, "had_zone"); + Assert.That ((NativeHandle) Messaging.IntPtr_objc_msgSend_IntPtr (cc.Handle, Selector.GetHandle ("copyWithZone:"), NativeHandle.Zero), Is.EqualTo (cc.Handle), "a"); + Assert.That (cc.had_zone.Value, Is.False, "had_zone"); } } @@ -1443,13 +1442,13 @@ public NSObject Copy (NSZone zone) public void TestProtocolRegistration () { var iProtocol = typeof (IProtocol).FullName.Replace (".", "_").Replace ("+", "_"); - Assert.AreNotEqual (IntPtr.Zero, Runtime.GetProtocol (iProtocol), "IProtocol"); - Assert.IsTrue (Messaging.bool_objc_msgSend_IntPtr (Class.GetHandle (typeof (MyProtocolImplementation)), Selector.GetHandle ("conformsToProtocol:"), Runtime.GetProtocol (iProtocol)), "Interface/IProtocol"); + Assert.That (Runtime.GetProtocol (iProtocol), Is.Not.EqualTo (IntPtr.Zero), "IProtocol"); + Assert.That (Messaging.bool_objc_msgSend_IntPtr (Class.GetHandle (typeof (MyProtocolImplementation)), Selector.GetHandle ("conformsToProtocol:"), Runtime.GetProtocol (iProtocol)), Is.True, "Interface/IProtocol"); #if !__TVOS__ && !MONOMAC - Assert.IsTrue (Messaging.bool_objc_msgSend_IntPtr (Class.GetHandle (typeof (Test24970)), Selector.GetHandle ("conformsToProtocol:"), Protocol.GetHandle ("UIApplicationDelegate")), "UIApplicationDelegate/17669"); + Assert.That (Messaging.bool_objc_msgSend_IntPtr (Class.GetHandle (typeof (Test24970)), Selector.GetHandle ("conformsToProtocol:"), Protocol.GetHandle ("UIApplicationDelegate")), Is.True, "UIApplicationDelegate/17669"); #endif // We don't support [Adopts] (yet at least). - // Assert.IsTrue (Messaging.bool_objc_msgSend_IntPtr (Class.GetHandle (typeof (ConformsToProtocolTestClass)), Selector.GetHandle ("conformsToProtocol:"), Runtime.GetProtocol ("NSCoding")), "Adopts/ConformsToProtocolTestClass"); + // Assert.That (Messaging.bool_objc_msgSend_IntPtr (Class.GetHandle (typeof (ConformsToProtocolTestClass)), Selector.GetHandle ("conformsToProtocol:"), Runtime.GetProtocol ("NSCoding")), Is.True, "Adopts/ConformsToProtocolTestClass"); } [Test] @@ -1465,14 +1464,14 @@ public void TestTypeEncodings () #endif var exp = new string [] { "@", ":", "^v", "C", "c", "s", "s", "S", "i", "I", "q", "Q", "f", "d", boolEncoding, "@", ":", "#" }; - Assert.AreEqual ((nuint) exp.Length, sig.NumberOfArguments, "NumberOfArguments"); + Assert.That (sig.NumberOfArguments, Is.EqualTo ((nuint) exp.Length), "NumberOfArguments"); // for (uint i = 0; i < exp.Length; i++) { // var p = Marshal.PtrToStringAuto (sig.GetArgumentType (i)); // Console.WriteLine ("{0}: {1}", i, p); // } for (uint i = 0; i < exp.Length; i++) { var p = Marshal.PtrToStringAuto (sig.GetArgumentType (i)); - Assert.AreEqual (exp [i], p, "#{0}", i); + Assert.That (p, Is.EqualTo (exp [i]), $"#{i}"); } } @@ -1495,9 +1494,9 @@ public void TestNativeObjectArray () using (var array = NSArray.FromObjects (i1, i2)) { using (var obj = new NativeObjectArrayType ()) { Messaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("addAnnotations:"), array.Handle); - Assert.AreEqual (2, obj.Annotations.Length, "length"); - Assert.AreSame (i1, obj.Annotations [0], "i1"); - Assert.AreSame (i2, obj.Annotations [1], "i2"); + Assert.That (obj.Annotations.Length, Is.EqualTo (2), "length"); + Assert.That (obj.Annotations [0], Is.SameAs (i1), "i1"); + Assert.That (obj.Annotations [1], Is.SameAs (i2), "i2"); } } } @@ -1513,9 +1512,9 @@ public void TestNativeObjectArray () using (var obj = new NativeObjectArrayType ()) { Messaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("addAnnotations:"), array.Handle); - Assert.AreEqual (2, obj.Annotations.Length, "length #2"); - Assert.IsNotNull (obj.Annotations [0], "i1 #2"); - Assert.IsNotNull (obj.Annotations [1], "i2 #2"); + Assert.That (obj.Annotations.Length, Is.EqualTo (2), "length #2"); + Assert.That (obj.Annotations [0], Is.Not.Null, "i1 #2"); + Assert.That (obj.Annotations [1], Is.Not.Null, "i2 #2"); } } } @@ -1642,8 +1641,8 @@ public void GenericVirtualTest () { using (var obj = new GenericConstrainedDerived ()) { Messaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("foo:"), obj.Handle); - Assert.AreEqual ("Derived", obj.FooType, "Derived"); - Assert.AreSame (obj, obj.FooT, "obj"); + Assert.That (obj.FooType, Is.EqualTo ("Derived"), "Derived"); + Assert.That (obj.FooT, Is.SameAs (obj), "obj"); } } @@ -1662,13 +1661,13 @@ public void ConformsToProtocolTest () public void ConformsToProtocolTest2 () { using (var obj = new ConformsToProtocolTestClass ()) { - Assert.IsTrue (Messaging.bool_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("conformsToProtocol:"), Runtime.GetProtocol ("NSCoding"))); - Assert.IsFalse (Messaging.bool_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("conformsToProtocol:"), Runtime.GetProtocol ("NSCopying"))); + Assert.That (Messaging.bool_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("conformsToProtocol:"), Runtime.GetProtocol ("NSCoding")), Is.True); + Assert.That (Messaging.bool_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("conformsToProtocol:"), Runtime.GetProtocol ("NSCopying")), Is.False); } using (var obj = new ConformsToProtocolTestClass ()) { - Assert.IsTrue (Messaging.bool_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("conformsToProtocol:"), Runtime.GetProtocol ("NSCoding"))); - Assert.IsFalse (Messaging.bool_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("conformsToProtocol:"), Runtime.GetProtocol ("NSCopying"))); + Assert.That (Messaging.bool_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("conformsToProtocol:"), Runtime.GetProtocol ("NSCoding")), Is.True); + Assert.That (Messaging.bool_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("conformsToProtocol:"), Runtime.GetProtocol ("NSCopying")), Is.False); } } @@ -1759,8 +1758,8 @@ public Action Block { public void IProtocolTest () { var o = new MyProtocolImplementation (); - Assert.AreEqual (31415, Messaging.int_objc_msgSend (o.Handle, Selector.GetHandle ("foo")), "#method"); - Assert.AreEqual (31415926, Messaging.int_objc_msgSend (o.Handle, Selector.GetHandle ("bar")), "#getter"); + Assert.That (Messaging.int_objc_msgSend (o.Handle, Selector.GetHandle ("foo")), Is.EqualTo (31415), "#method"); + Assert.That (Messaging.int_objc_msgSend (o.Handle, Selector.GetHandle ("bar")), Is.EqualTo (31415926), "#getter"); Assert.DoesNotThrow (() => { Messaging.void_objc_msgSend_int (o.Handle, Selector.GetHandle ("setBar:"), 2); }, "#setter"); } @@ -1776,7 +1775,7 @@ public void FakeTypeTest () var cls = Class.GetHandle ("FakeType2"); obj2_ptr = Messaging.IntPtr_objc_msgSend (Class.GetHandle ("FakeType2"), Selector.GetHandle ("alloc")); obj2_ptr = Messaging.IntPtr_objc_msgSend (obj2_ptr, Selector.GetHandle ("init")); - Assert.AreNotEqual (IntPtr.Zero, obj2_ptr, "not zero"); + Assert.That (obj2_ptr, Is.Not.EqualTo (IntPtr.Zero), "not zero"); Messaging.bool_objc_msgSend_IntPtr (obj1.Handle, Selector.GetHandle ("fakeTypeTest:"), obj2_ptr); } } finally { @@ -1799,7 +1798,7 @@ public FakeType1 () public bool FakeTypeTest (FakeType1 ft) { var cls = new Class (Messaging.IntPtr_objc_msgSend (ft.Handle, Selector.GetHandle ("class"))); - Assert.AreEqual ("FakeType2", cls.Name); + Assert.That (cls.Name, Is.EqualTo ("FakeType2")); return true; } } @@ -1812,11 +1811,11 @@ public bool FakeTypeTest (FakeType1 ft) public void Test_D () { using (var tc = new ObjCRegistrarTest ()) { - Assert.AreEqual (tc.Pd1, 0, "Pd1"); - Assert.AreEqual (0, tc.D (), "1"); + Assert.That (tc.Pd1, Is.EqualTo (0), "Pd1"); + Assert.That (tc.D (), Is.EqualTo (0), "1"); tc.Pd1 = 1.2; - Assert.AreEqual (1.2, tc.D (), "2"); - Assert.AreEqual (tc.Pd1, 1.2, "Pd1"); + Assert.That (tc.D (), Is.EqualTo (1.2), "2"); + Assert.That (1.2, Is.EqualTo (tc.Pd1), "Pd1"); } } @@ -1835,7 +1834,7 @@ public class IdAsIntPtrClass : ObjCProtocolTest { [Export ("idAsIntPtr:")] public new void IdAsIntPtr (IntPtr id) { - Assert.AreEqual (IntPtr.Zero, id, "Zero"); + Assert.That (id, Is.EqualTo (IntPtr.Zero), "Zero"); } } @@ -1849,7 +1848,7 @@ public void OutNSErrorOnStack1 () Marshal.WriteIntPtr (ptr, IntPtr.Zero); Console.WriteLine ("ptr: 0x{0} = 0x{1}", ptr.ToString ("x"), Marshal.ReadIntPtr (ptr)); Messaging.void_objc_msgSend_int_int_int_int_int_int_IntPtr (obj.Handle, Selector.GetHandle ("outNSErrorOnStack:i:i:i:i:i:err:"), 0, 0, 0, 0, 0, 0, ptr); - Assert.AreEqual (IntPtr.Zero, Marshal.ReadIntPtr (ptr), "#1"); + Assert.That (Marshal.ReadIntPtr (ptr), Is.EqualTo (IntPtr.Zero), "#1"); Marshal.FreeHGlobal (ptr); ptr = IntPtr.Zero; @@ -1857,7 +1856,7 @@ public void OutNSErrorOnStack1 () IntPtr* ptrFixed = &ptr; Console.WriteLine ("ptr: 0x{0}", ptr.ToString ("x")); Messaging.void_objc_msgSend_int_int_int_int_int_int_IntPtr (obj.Handle, Selector.GetHandle ("outNSErrorOnStack:i:i:i:i:i:err:"), 0, 0, 0, 0, 0, 0, (IntPtr) ptrFixed); - Assert.AreEqual (IntPtr.Zero, ptr, "#2"); + Assert.That (ptr, Is.EqualTo (IntPtr.Zero), "#2"); } } } @@ -1872,7 +1871,7 @@ public void OutNSErrorOnStack2 () Marshal.WriteIntPtr (ptr, IntPtr.Zero); Console.WriteLine ("ptr: 0x{0} = 0x{1}", ptr.ToString ("x"), Marshal.ReadIntPtr (ptr)); Messaging.void_objc_msgSend_IntPtr_IntPtr_IntPtr_long_int_IntPtr (obj.Handle, Selector.GetHandle ("outNSErrorOnStack:obj:obj:int64:i:err:"), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 1, 2, ptr); - Assert.AreEqual (IntPtr.Zero, Marshal.ReadIntPtr (ptr), "#1"); + Assert.That (Marshal.ReadIntPtr (ptr), Is.EqualTo (IntPtr.Zero), "#1"); Marshal.FreeHGlobal (ptr); ptr = IntPtr.Zero; @@ -1880,7 +1879,7 @@ public void OutNSErrorOnStack2 () IntPtr* ptrFixed = &ptr; Console.WriteLine ("ptr: 0x{0}", ptr.ToString ("x")); Messaging.void_objc_msgSend_IntPtr_IntPtr_IntPtr_long_int_IntPtr (obj.Handle, Selector.GetHandle ("outNSErrorOnStack:obj:obj:int64:i:err:"), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 1, 2, (IntPtr) ptrFixed); - Assert.AreEqual (IntPtr.Zero, ptr, "#2"); + Assert.That (ptr, Is.EqualTo (IntPtr.Zero), "#2"); } } } @@ -1893,8 +1892,8 @@ public override void OutNSErrorOnStack (int i1, int i2, int i3, int i4, int i5, public override void OutNSErrorOnStack (NSObject i1, NSObject i2, NSObject i3, long i4, int i5, out NSError error) { - Assert.AreEqual (i4, 1, "#long"); - Assert.AreEqual (i5, 2, "#int"); + Assert.That (i4, Is.EqualTo (1), "#long"); + Assert.That (i5, Is.EqualTo (2), "#int"); error = null; } } @@ -1929,7 +1928,7 @@ public void CustomAppDelegatePerformFetchTest () block.CleanupBlock (); - Assert.IsTrue (performed); + Assert.That (performed, Is.True); } } @@ -2007,11 +2006,11 @@ public void TestProtocolAndRegister () // Yet we've created these in btouch, so we need to define what they // actually do (nothing at all). - Assert.AreEqual (NativeHandle.Zero, Class.GetHandle ("TestProtocolRegister")); + Assert.That (Class.GetHandle ("TestProtocolRegister"), Is.EqualTo (NativeHandle.Zero)); // However deriving from those nonsensical classes must do something // (at the very least because anything else would be a breaking change). - Assert.AreNotEqual (NativeHandle.Zero, Class.GetHandle ("DerivedTestProtocolRegister")); + Assert.That (Class.GetHandle ("DerivedTestProtocolRegister"), Is.Not.EqualTo (NativeHandle.Zero)); } [Protocol] @@ -2129,7 +2128,7 @@ public void BlockCollection () GC.Collect (); GC.WaitForPendingFinalizers (); TestRuntime.RunAsync (TimeSpan.FromSeconds (30), () => { }, () => ObjCBlockTester.FreedBlockCount > initialFreedCount); - Assert.IsNull (ex, "No exceptions"); + Assert.That (ex, Is.Null, "No exceptions"); Assert.That (ObjCBlockTester.FreedBlockCount, Is.GreaterThan (initialFreedCount), "freed blocks"); } @@ -2143,9 +2142,9 @@ public void TestCtors () ptr = Messaging.IntPtr_objc_msgSend (Class.GetHandle (typeof (D2)), Selector.GetHandle ("alloc")); ptr = Messaging.IntPtr_objc_msgSend_int (ptr, Selector.GetHandle ("initWithFoo:"), 1); var obj = Runtime.GetNSObject (ptr); - Assert.AreEqual (3, obj.Value, "a"); - Assert.AreEqual ("foo", obj.ctor1, "a ctor1"); - Assert.AreEqual ("foo", obj.ctor2, "a ctor2"); + Assert.That (obj.Value, Is.EqualTo (3), "a"); + Assert.That (obj.ctor1, Is.EqualTo ("foo"), "a ctor1"); + Assert.That (obj.ctor2, Is.EqualTo ("foo"), "a ctor2"); } finally { Messaging.void_objc_msgSend (ptr, Selector.GetHandle ("release")); } @@ -2160,7 +2159,7 @@ public void TestCtors () var ex = Assert.Throws (() => Runtime.GetNSObject (ptr), "b ex"); Assert.That (ex.Message, Does.Contain ("Could not find an existing managed instance for this object, nor was it possible to create a new managed instance (because the type 'MonoTouchFixtures.ObjCRuntime.RegistrarTest+D2' does not have a constructor that takes one"), "Exception message"); var obj = Runtime.GetNSObject (ptr); - Assert.AreEqual ("bar", obj.ctor1, "b ctor1"); + Assert.That (obj.ctor1, Is.EqualTo ("bar"), "b ctor1"); } finally { Messaging.void_objc_msgSend (ptr, Selector.GetHandle ("release")); } @@ -2182,7 +2181,7 @@ public void TestCtors () ptr = Messaging.IntPtr_objc_msgSend (Class.GetHandle (typeof (E2)), Selector.GetHandle ("alloc")); ptr = Messaging.IntPtr_objc_msgSend (ptr, Selector.GetHandle ("init")); var obj = Runtime.GetNSObject (ptr); - Assert.AreEqual (3, obj.Value, "d"); + Assert.That (obj.Value, Is.EqualTo (3), "d"); } finally { Messaging.void_objc_msgSend (ptr, Selector.GetHandle ("release")); } @@ -2194,12 +2193,12 @@ public void TestCtors () // we first need it. ptr = Messaging.IntPtr_objc_msgSend (Class.GetHandle (typeof (E2)), Selector.GetHandle ("alloc")); ptr = Messaging.IntPtr_objc_msgSend (ptr, Selector.GetHandle ("init")); - Assert.IsNull (Runtime.TryGetNSObject (ptr), "e null"); + Assert.That (Runtime.TryGetNSObject (ptr), Is.Null, "e null"); int rv = Messaging.int_objc_msgSend_int (ptr, Selector.GetHandle ("M1:"), 31415); - Assert.IsNotNull (Runtime.TryGetNSObject (ptr), "e not null"); - Assert.AreEqual (31415, rv, "e1"); + Assert.That (Runtime.TryGetNSObject (ptr), Is.Not.Null, "e not null"); + Assert.That (rv, Is.EqualTo (31415), "e1"); var obj = Runtime.GetNSObject (ptr); - Assert.AreEqual (3, obj.Value, "e2"); + Assert.That (obj.Value, Is.EqualTo (3), "e2"); } finally { Messaging.void_objc_msgSend (ptr, Selector.GetHandle ("release")); } @@ -2213,12 +2212,12 @@ public void TestCtors () // in a subclass of a generic type. ptr = Messaging.IntPtr_objc_msgSend (Class.GetHandle (typeof (G2)), Selector.GetHandle ("alloc")); ptr = Messaging.IntPtr_objc_msgSend (ptr, Selector.GetHandle ("init")); - Assert.IsNull (Runtime.TryGetNSObject (ptr), "f null"); + Assert.That (Runtime.TryGetNSObject (ptr), Is.Null, "f null"); int rv = Messaging.int_objc_msgSend_int (ptr, Selector.GetHandle ("M1:"), 31415); - Assert.IsNotNull (Runtime.TryGetNSObject (ptr), "f not null"); - Assert.AreEqual (31415, rv, "f1"); + Assert.That (Runtime.TryGetNSObject (ptr), Is.Not.Null, "f not null"); + Assert.That (rv, Is.EqualTo (31415), "f1"); var obj = Runtime.GetNSObject (ptr); - Assert.AreEqual (3, obj.Value, "f2"); + Assert.That (obj.Value, Is.EqualTo (3), "f2"); } finally { Messaging.void_objc_msgSend (ptr, Selector.GetHandle ("release")); } @@ -2232,12 +2231,12 @@ public void TestCtors () // in a generic type. ptr = Messaging.IntPtr_objc_msgSend (Class.GetHandle (typeof (G2)), Selector.GetHandle ("alloc")); ptr = Messaging.IntPtr_objc_msgSend (ptr, Selector.GetHandle ("init")); - Assert.IsNull (Runtime.TryGetNSObject (ptr), "g null"); + Assert.That (Runtime.TryGetNSObject (ptr), Is.Null, "g null"); int rv = Messaging.int_objc_msgSend_int (ptr, Selector.GetHandle ("M2:"), 31415); - Assert.IsNotNull (Runtime.TryGetNSObject (ptr), "g not null"); - Assert.AreEqual (31415, rv, "g1"); + Assert.That (Runtime.TryGetNSObject (ptr), Is.Not.Null, "g not null"); + Assert.That (rv, Is.EqualTo (31415), "g1"); var obj = Runtime.GetNSObject (ptr); - Assert.AreEqual (3, obj.Value, "g2"); + Assert.That (obj.Value, Is.EqualTo (3), "g2"); } finally { Messaging.void_objc_msgSend (ptr, Selector.GetHandle ("release")); } @@ -2280,7 +2279,7 @@ public void CustomUserTypeWithDynamicallyLoadedAssembly () Name = "CustomUserTypeWithDynamicallyLoadedAssembly", }; thread.Start (); - Assert.IsTrue (thread.Join (TimeSpan.FromSeconds (30)), "Background thread done"); + Assert.That (thread.Join (TimeSpan.FromSeconds (30)), Is.True, "Background thread done"); // Run the main loop for a little while. var counter = size; @@ -2288,7 +2287,7 @@ public void CustomUserTypeWithDynamicallyLoadedAssembly () // Verify that none of the managed instances have been collected by the GC: for (var i = 0; i < size; i++) { - Assert.IsNotNull (handles [i].Target, $"Target #{i}"); + Assert.That (handles [i].Target, Is.Not.Null, $"Target #{i}"); ((NSObject) handles [i].Target).Dispose (); } @@ -2323,7 +2322,7 @@ public override nint RowsInSection (UITableView tableView, nint section) public void TestInheritedProtocols () { using (var obj = new Bug28757B ()) { - Assert.AreEqual ((nint) 2, Messaging.nint_objc_msgSend_IntPtr_nint (obj.Handle, Selector.GetHandle ("tableView:numberOfRowsInSection:"), IntPtr.Zero, 0), "#test"); + Assert.That (Messaging.nint_objc_msgSend_IntPtr_nint (obj.Handle, Selector.GetHandle ("tableView:numberOfRowsInSection:"), IntPtr.Zero, 0), Is.EqualTo ((nint) 2), "#test"); } } #endif // !MONOMAC @@ -2337,7 +2336,7 @@ public void InOutProtocolMethodArgument () var targetContentOffset = new CGPoint (3, 4); Messaging.void_objc_msgSend_IntPtr_CGPoint_ref_CGPoint (obj.Handle, Selector.GetHandle ("scrollViewWillEndDragging:withVelocity:targetContentOffset:"), IntPtr.Zero, velocity, ref targetContentOffset); Console.WriteLine (targetContentOffset); - Assert.AreEqual ("{123, 345}", targetContentOffset.ToString (), "ref output"); + Assert.That (targetContentOffset.ToString (), Is.EqualTo ("{123, 345}"), "ref output"); } } #endif // !MONOMAC @@ -2347,8 +2346,8 @@ class Scroller : NSObject, IUIScrollViewDelegate { [Export ("scrollViewWillEndDragging:withVelocity:targetContentOffset:")] public void WillEndDragging (UIScrollView scrollView, PointF velocity, ref PointF targetContentOffset) { - Assert.AreEqual ("{1, 2}", velocity.ToString (), "velocity"); - Assert.AreEqual ("{3, 4}", targetContentOffset.ToString (), "targetContentOffset"); + Assert.That (velocity.ToString (), Is.EqualTo ("{1, 2}"), "velocity"); + Assert.That (targetContentOffset.ToString (), Is.EqualTo ("{3, 4}"), "targetContentOffset"); targetContentOffset = new CGPoint (123, 345); } } @@ -2364,7 +2363,7 @@ public void VoidPtrToINativeObjectArgument () using (var obj = new ABPeoplePickerNavigationControllerDelegateImpl ()) { using (var person = new ABPerson ()) { Messaging.void_objc_msgSend_IntPtr_IntPtr (obj.Handle, Selector.GetHandle ("peoplePickerNavigationController:didSelectPerson:"), IntPtr.Zero, person.Handle); - Assert.AreEqual (person.Handle, obj.personHandle, "1"); + Assert.That (obj.personHandle, Is.EqualTo (person.Handle), "1"); } } } @@ -2392,21 +2391,21 @@ public void GenericAPI () var array = Messaging.IntPtr_objc_msgSend_IntPtr (Class.GetHandle (typeof (NSArray)), Selector.GetHandle ("arrayWithObject:"), handle); Messaging.void_objc_msgSend_IntPtr (contact.Handle, Selector.GetHandle ("setDates:"), array); - Assert.AreEqual ((nint) 1923, contact.Dates [0].Value.Year, "Dates"); + Assert.That (contact.Dates [0].Value.Year, Is.EqualTo ((nint) 1923), "Dates"); } using (var contact = new SubclassedContact ()) { var dates = Messaging.IntPtr_objc_msgSend (contact.Handle, Selector.GetHandle ("dates")); var obj = Runtime.GetNSObject (dates); - Assert.AreEqual (typeof (NSArray), obj.GetType (), "2 date type"); + Assert.That (obj.GetType (), Is.EqualTo (typeof (NSArray)), "2 date type"); var arr = (NSArray) obj; - Assert.AreEqual ((nuint) 1, arr.Count, "2 count"); + Assert.That (arr.Count, Is.EqualTo ((nuint) 1), "2 count"); } using (var contact = new SubclassedContact ()) { var dates = Messaging.IntPtr_objc_msgSend (contact.Handle, Selector.GetHandle ("dates")); var arr = NSArray.ArrayFromHandle> (dates); - Assert.AreEqual (1, arr.Length, "3 length"); + Assert.That (arr.Length, Is.EqualTo (1), "3 length"); } } @@ -2430,10 +2429,10 @@ public void Bug34224 () using (var obj = new Bug34224Class ()) { IntPtr ptr = new IntPtr (123); Messaging.void_objc_msgSend_ref_IntPtr (obj.Handle, Selector.GetHandle ("ref:"), ref ptr); - Assert.AreEqual (new IntPtr (456), ptr, "# ref"); + Assert.That (ptr, Is.EqualTo (new IntPtr (456)), "# ref"); Messaging.void_objc_msgSend_out_IntPtr (obj.Handle, Selector.GetHandle ("out:"), out ptr); - Assert.AreEqual (new IntPtr (567), ptr, "# out"); + Assert.That (ptr, Is.EqualTo (new IntPtr (567)), "# out"); } } @@ -2442,7 +2441,7 @@ class Bug34224Class : NSObject { [Export ("ref:")] public void Ref (ref IntPtr p1) { - Assert.AreEqual (new IntPtr (123), p1, "ref C"); + Assert.That (p1, Is.EqualTo (new IntPtr (123)), "ref C"); p1 = new IntPtr (456); } @@ -2472,9 +2471,9 @@ public void SelectorReturnValue () { using (var obj = new Bug34440Class ()) { var ptr = (IntPtr) Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("bug34440")); - Assert.AreEqual (Selector.GetHandle ("bug34440"), ptr, "selector"); + Assert.That (ptr, Is.EqualTo (Selector.GetHandle ("bug34440")), "selector"); ptr = Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("classReturn")); - Assert.AreEqual ((IntPtr) Class.GetHandle (typeof (Bug34440Class)), (IntPtr) ptr, "class"); + Assert.That ((IntPtr) ptr, Is.EqualTo ((IntPtr) Class.GetHandle (typeof (Bug34440Class))), "class"); } } @@ -2482,7 +2481,7 @@ public void SelectorReturnValue () public void BlockReturnTest () { using (var obj = new BlockReturnTestClass ()) { - Assert.IsTrue (obj.TestBlocks (), "TestBlocks"); + Assert.That (obj.TestBlocks (), Is.True, "TestBlocks"); } } @@ -2490,7 +2489,7 @@ class BlockReturnTestClass : ObjCRegistrarTest { public override RegistrarTestBlock MethodReturningBlock () { return v => { - Assert.AreEqual (0xdeadf00d, v, "input"); + Assert.That (v, Is.EqualTo (0xdeadf00d), "input"); return 0x1337b001; }; } @@ -2498,7 +2497,7 @@ public override RegistrarTestBlock MethodReturningBlock () public override RegistrarTestBlock PropertyReturningBlock { get { return v => { - Assert.AreEqual (0xdeadf11d, v, "input"); + Assert.That (v, Is.EqualTo (0xdeadf11d), "input"); return 0x7b001133; }; } @@ -2509,15 +2508,15 @@ public override RegistrarTestBlock PropertyReturningBlock { public void PropertySetters () { var cls = Class.GetHandle (typeof (PropertySetterTestClass)); - Assert.AreNotEqual (IntPtr.Zero, class_getInstanceMethod (cls, Selector.GetHandle ("setá:")), "a 1"); + Assert.That (class_getInstanceMethod (cls, Selector.GetHandle ("setá:")), Is.Not.EqualTo (IntPtr.Zero), "a 1"); using (var obj = new PropertySetterTestClass ()) { obj.SetValueForKey (new NSString ("AAA"), (NSString) "á"); - Assert.AreEqual ("AAA", (string) (NSString) obj.ValueForKey ((NSString) "á"), "A getvalue"); - Assert.AreEqual ("AAA", obj.A, "A setvalue"); + Assert.That ((string) (NSString) obj.ValueForKey ((NSString) "á"), Is.EqualTo ("AAA"), "A getvalue"); + Assert.That (obj.A, Is.EqualTo ("AAA"), "A setvalue"); obj.SetValueForKey (new NSString ("BBB"), (NSString) "b"); - Assert.AreEqual ("BBB", (string) (NSString) obj.ValueForKey ((NSString) "b"), "B getvalue"); - Assert.AreEqual ("BBB", obj.B, "B setvalue"); + Assert.That ((string) (NSString) obj.ValueForKey ((NSString) "b"), Is.EqualTo ("BBB"), "B getvalue"); + Assert.That (obj.B, Is.EqualTo ("BBB"), "B setvalue"); } } @@ -2533,8 +2532,8 @@ class PropertySetterTestClass : NSObject { public void ConstructorChaining () { using (var obj = new CtorChaining2 (2)) { - Assert.IsTrue (obj.InitCalled, "Init called"); - Assert.IsTrue (obj.InitCallsInitCalled, "InitCallsInit called"); + Assert.That (obj.InitCalled, Is.True, "Init called"); + Assert.That (obj.InitCallsInitCalled, Is.True, "InitCallsInit called"); } } @@ -2559,8 +2558,8 @@ public void OutOverriddenWithoutOutAttribute () using (var obj = new Registrar_OutExportDerivedClass ()) { IntPtr tmpH = tmp.Handle; var rv = Messaging.IntPtr_objc_msgSend_ref_IntPtr (obj.Handle, Selector.GetHandle ("func:"), ref tmpH); - Assert.AreEqual (IntPtr.Zero, tmpH, "input"); - Assert.AreEqual (IntPtr.Zero, rv, "output"); + Assert.That (tmpH, Is.EqualTo (IntPtr.Zero), "input"); + Assert.That (rv, Is.EqualTo (IntPtr.Zero), "output"); } } } @@ -2579,8 +2578,8 @@ public void ProtocolArgument () using (var obj = new ProtocolArgumentClass ()) { var nsobjProtocol = Protocol.GetHandle ("NSObject"); var ptr = Messaging.IntPtr_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle ("someMethod:"), nsobjProtocol); - Assert.AreEqual (nsobjProtocol, ptr, "result"); - Assert.AreNotEqual (IntPtr.Zero, ptr, "nsobject"); + Assert.That (ptr, Is.EqualTo (nsobjProtocol), "result"); + Assert.That (ptr, Is.Not.EqualTo (IntPtr.Zero), "nsobject"); } } @@ -2669,8 +2668,8 @@ class ByrefParameterTest : NSObject { [Export ("doSomething:")] public void DoSomething (ref NSString str) { - Assert.IsNotNull (str, "NonNull NSString&"); - Assert.AreEqual ("ByrefParameter", str.ToString ()); + Assert.That (str, Is.Not.Null, "NonNull NSString&"); + Assert.That (str.ToString (), Is.EqualTo ("ByrefParameter")); } } @@ -2762,7 +2761,7 @@ public void TestStringArray () obj.StringArrayProperty = array; Assert.That (obj.StringArrayProperty, Is.EqualTo (array), "1"); obj.SetStringArrayMethod (null); - Assert.IsNull (obj.StringArrayProperty, "2"); + Assert.That (obj.StringArrayProperty, Is.Null, "2"); obj.SetStringArrayMethod (array); Assert.That (obj.StringArrayProperty, Is.EqualTo (array), "3"); var rv = obj.GetStringArrayMethod (); @@ -2800,7 +2799,7 @@ public void TestNSObjectArray () obj.NSObjectArrayProperty = array; Assert.That (obj.NSObjectArrayProperty, Is.EqualTo (array), "1"); obj.SetNSObjectArrayMethod (null); - Assert.IsNull (obj.NSObjectArrayProperty, "2"); + Assert.That (obj.NSObjectArrayProperty, Is.Null, "2"); obj.SetNSObjectArrayMethod (array); Assert.That (obj.NSObjectArrayProperty, Is.EqualTo (array), "3"); var rv = obj.GetNSObjectArrayMethod (); @@ -2838,7 +2837,7 @@ public void TestINSCodingArray () obj.INSCodingArrayProperty = array; Assert.That (obj.INSCodingArrayProperty, Is.EqualTo (array), "1"); obj.SetINSCodingArrayMethod (null); - Assert.IsNull (obj.INSCodingArrayProperty, "2"); + Assert.That (obj.INSCodingArrayProperty, Is.Null, "2"); obj.SetINSCodingArrayMethod (array); Assert.That (obj.INSCodingArrayProperty, Is.EqualTo (array), "3"); var rv = obj.GetINSCodingArrayMethod (); @@ -2883,29 +2882,29 @@ public void RefOutTest_CFBundle () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestCFBundle (action << 0, ref refObj, out outObj); - Assert.IsNull (refObj, "CFBundle-1A-ref"); - Assert.IsNull (outObj, "CFBundle-1A-out"); + Assert.That (refObj, Is.Null, "CFBundle-1A-ref"); + Assert.That (outObj, Is.Null, "CFBundle-1A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestCFBundle (action << 8, ref refObj, out outObj); - Assert.IsNull (refObj, "CFBundle-1M-ref"); - Assert.IsNull (outObj, "CFBundle-1M-out"); + Assert.That (refObj, Is.Null, "CFBundle-1M-ref"); + Assert.That (outObj, Is.Null, "CFBundle-1M-out"); // direct native refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "CFBundle-1DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "CFBundle-1DA-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "CFBundle-1DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "CFBundle-1DA-out"); // direct managed refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "CFBundle-1DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "CFBundle-1DM-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "CFBundle-1DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "CFBundle-1DM-out"); /// 2: verify that refValue points to something action = 2; @@ -2914,31 +2913,31 @@ public void RefOutTest_CFBundle () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestCFBundle (action << 0, ref refObj, out outObj); - Assert.AreEqual (dummyObj.Handle, refObj.Handle, "CFBundle-2A-ref"); - Assert.AreSame (dummyObj, refObj, "CBundle-2A-ref-same"); - Assert.IsNull (outObj, "CFBundle-2A-out"); + Assert.That (refObj.Handle, Is.EqualTo (dummyObj.Handle), "CFBundle-2A-ref"); + Assert.That (refObj, Is.SameAs (dummyObj), "CBundle-2A-ref-same"); + Assert.That (outObj, Is.Null, "CFBundle-2A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestCFBundle (action << 8, ref refObj, out outObj); - Assert.AreEqual (dummyObj.Handle, refObj.Handle, "CFBundle-2M-ref"); - Assert.AreSame (dummyObj, refObj, "CBundle-2M-ref-same"); - Assert.IsNull (outObj, "CFBundle-2M-out"); + Assert.That (refObj.Handle, Is.EqualTo (dummyObj.Handle), "CFBundle-2M-ref"); + Assert.That (refObj, Is.SameAs (dummyObj), "CBundle-2M-ref-same"); + Assert.That (outObj, Is.Null, "CFBundle-2M-out"); // direct native refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (dummyObj.Handle, refValue, "CFBundle-2DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "CFBundle-2DA-out"); + Assert.That (refValue, Is.EqualTo (dummyObj.Handle), "CFBundle-2DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "CFBundle-2DA-out"); // direct managed refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (dummyObj.Handle, refValue, "CFBundle-2DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "CFBundle-2DM-out"); + Assert.That (refValue, Is.EqualTo (dummyObj.Handle), "CFBundle-2DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "CFBundle-2DM-out"); /// 3 set both parameteres to the same pointer of a CFBundle @@ -2948,33 +2947,33 @@ public void RefOutTest_CFBundle () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestCFBundle (action << 0, ref refObj, out outObj); - Assert.AreEqual (dummyObj.Handle, refObj.Handle, "CFBundle-3A-ref"); - Assert.AreSame (dummyObj, refObj, "CBundle-3A-ref-same"); - Assert.AreEqual (dummyObj.Handle, outObj.Handle, "CFBundle-3A-out"); - Assert.AreNotSame (dummyObj, outObj, "CBundle-3A-ref-out"); + Assert.That (refObj.Handle, Is.EqualTo (dummyObj.Handle), "CFBundle-3A-ref"); + Assert.That (refObj, Is.SameAs (dummyObj), "CBundle-3A-ref-same"); + Assert.That (outObj.Handle, Is.EqualTo (dummyObj.Handle), "CFBundle-3A-out"); + Assert.That (outObj, Is.Not.SameAs (dummyObj), "CBundle-3A-ref-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestCFBundle (action << 8, ref refObj, out outObj); - Assert.AreEqual (dummyObj.Handle, refObj.Handle, "CFBundle-3M-ref"); - Assert.AreNotSame (dummyObj, refObj, "CBundle-3M-ref-same"); - Assert.AreEqual (dummyObj.Handle, outObj.Handle, "CFBundle-3M-out"); - Assert.AreNotSame (dummyObj, outObj, "CBundle-3M-ref-out"); + Assert.That (refObj.Handle, Is.EqualTo (dummyObj.Handle), "CFBundle-3M-ref"); + Assert.That (refObj, Is.Not.SameAs (dummyObj), "CBundle-3M-ref-same"); + Assert.That (outObj.Handle, Is.EqualTo (dummyObj.Handle), "CFBundle-3M-out"); + Assert.That (outObj, Is.Not.SameAs (dummyObj), "CBundle-3M-ref-out"); // direct native refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (dummyObj.Handle, refValue, "CFBundle-3DA-ref"); - Assert.AreEqual (dummyObj.Handle, outValue, "CFBundle-3DA-out"); + Assert.That (refValue, Is.EqualTo (dummyObj.Handle), "CFBundle-3DA-ref"); + Assert.That (outValue, Is.EqualTo (dummyObj.Handle), "CFBundle-3DA-out"); // direct managed refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (dummyObj.Handle, refValue, "CFBundle-3DM-ref"); - Assert.AreEqual (dummyObj.Handle, outValue, "CFBundle-3DM-out"); + Assert.That (refValue, Is.EqualTo (dummyObj.Handle), "CFBundle-3DM-ref"); + Assert.That (outValue, Is.EqualTo (dummyObj.Handle), "CFBundle-3DM-out"); /// 4 set both parameteres to different pointers of a CFBundle @@ -2984,33 +2983,33 @@ public void RefOutTest_CFBundle () refObj = null; // set to null outObj = null; // set to null obj.TestCFBundle (action << 0, ref refObj, out outObj); - Assert.AreNotEqual (NativeHandle.Zero, refObj.Handle, "CFBundle-4A-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outObj.Handle, "CFBundle-4A-out"); - Assert.AreNotEqual (refObj.Handle, outObj.Handle, "CBundle-4A-ref-distinct"); + Assert.That (refObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "CFBundle-4A-ref"); + Assert.That (outObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "CFBundle-4A-out"); + Assert.That (outObj.Handle, Is.Not.EqualTo (refObj.Handle), "CBundle-4A-ref-distinct"); // managed refObj = null; // set to null outObj = null; // set to null obj.TestCFBundle (action << 8, ref refObj, out outObj); - Assert.AreNotEqual (NativeHandle.Zero, refObj.Handle, "CFBundle-4M-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outObj.Handle, "CFBundle-4M-out"); - Assert.AreNotEqual (refObj.Handle, outObj.Handle, "CBundle-4M-ref-distinct"); + Assert.That (refObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "CFBundle-4M-ref"); + Assert.That (outObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "CFBundle-4M-out"); + Assert.That (outObj.Handle, Is.Not.EqualTo (refObj.Handle), "CBundle-4M-ref-distinct"); // direct native refValue = NativeHandle.Zero; // set to null outValue = NativeHandle.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreNotEqual (NativeHandle.Zero, refValue, "CFBundle-4DA-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outValue, "CFBundle-4DA-out"); - Assert.AreNotEqual (refValue, outValue, "CBundle-4DA-ref-distinct"); + Assert.That (refValue, Is.Not.EqualTo (NativeHandle.Zero), "CFBundle-4DA-ref"); + Assert.That (outValue, Is.Not.EqualTo (NativeHandle.Zero), "CFBundle-4DA-out"); + Assert.That (outValue, Is.Not.EqualTo (refValue), "CBundle-4DA-ref-distinct"); // direct managed refValue = NativeHandle.Zero; // set to null outValue = NativeHandle.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreNotEqual (NativeHandle.Zero, refValue, "CFBundle-4DM-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outValue, "CFBundle-4DM-out"); - Assert.AreNotEqual (refValue, outValue, "CBundle-4DM-ref-distinct"); + Assert.That (refValue, Is.Not.EqualTo (NativeHandle.Zero), "CFBundle-4DM-ref"); + Assert.That (outValue, Is.Not.EqualTo (NativeHandle.Zero), "CFBundle-4DM-out"); + Assert.That (outValue, Is.Not.EqualTo (refValue), "CBundle-4DM-ref-distinct"); } } @@ -3034,29 +3033,29 @@ public void RefOutTest_INSCoding () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestINSCoding (action << 0, ref refObj, out outObj); - Assert.IsNull (refObj, "NSCoding-1A-ref"); - Assert.IsNull (outObj, "NSCoding-1A-out"); + Assert.That (refObj, Is.Null, "NSCoding-1A-ref"); + Assert.That (outObj, Is.Null, "NSCoding-1A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestINSCoding (action << 8, ref refObj, out outObj); - Assert.IsNull (refObj, "NSCoding-1M-ref"); - Assert.IsNull (outObj, "NSCoding-1M-out"); + Assert.That (refObj, Is.Null, "NSCoding-1M-ref"); + Assert.That (outObj, Is.Null, "NSCoding-1M-out"); // direct native refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "NSCoding-1DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSCoding-1DA-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "NSCoding-1DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSCoding-1DA-out"); // direct managed refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "NSCoding-1DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSCoding-1DM-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "NSCoding-1DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSCoding-1DM-out"); /// 2: verify that refValue points to something action = 2; @@ -3065,31 +3064,31 @@ public void RefOutTest_INSCoding () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestINSCoding (action << 0, ref refObj, out outObj); - Assert.AreEqual (dummyObj.Handle, refObj.Handle, "NSCoding-2A-ref"); - Assert.AreSame (dummyObj, refObj, "NSCoding-2A-ref-same"); - Assert.IsNull (outObj, "NSCoding-2A-out"); + Assert.That (refObj.Handle, Is.EqualTo (dummyObj.Handle), "NSCoding-2A-ref"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSCoding-2A-ref-same"); + Assert.That (outObj, Is.Null, "NSCoding-2A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestINSCoding (action << 8, ref refObj, out outObj); - Assert.AreEqual (dummyObj.Handle, refObj.Handle, "NSCoding-2M-ref"); - Assert.AreSame (dummyObj, refObj, "NSCoding-2M-ref-same"); - Assert.IsNull (outObj, "NSCoding-2M-out"); + Assert.That (refObj.Handle, Is.EqualTo (dummyObj.Handle), "NSCoding-2M-ref"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSCoding-2M-ref-same"); + Assert.That (outObj, Is.Null, "NSCoding-2M-out"); // direct native refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (dummyObj.Handle, refValue, "NSCoding-2DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSCoding-2DA-out"); + Assert.That (refValue, Is.EqualTo (dummyObj.Handle), "NSCoding-2DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSCoding-2DA-out"); // direct managed refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (dummyObj.Handle, refValue, "NSCoding-2DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSCoding-2DM-out"); + Assert.That (refValue, Is.EqualTo (dummyObj.Handle), "NSCoding-2DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSCoding-2DM-out"); /// 3 set both parameteres to the same pointer of a NSCoding @@ -3099,12 +3098,12 @@ public void RefOutTest_INSCoding () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestINSCoding (action << 0, ref refObj, out outObj); - Assert.AreNotEqual (dummyObj.Handle, refObj.Handle, "NSCoding-3A-ref"); - Assert.AreNotSame (dummyObj, refObj, "NSCoding-3A-ref-same"); - Assert.AreNotEqual (dummyObj.Handle, outObj.Handle, "NSCoding-3A-out"); - Assert.AreNotSame (dummyObj, outObj, "NSCoding-3A-ref-out"); - Assert.AreEqual (refObj.Handle, outObj.Handle, "NSCoding-3A-out-ref-eq"); - Assert.AreNotSame (refObj, outObj, "NSCoding-3A-ref-out-not-safe"); + Assert.That (refObj.Handle, Is.Not.EqualTo (dummyObj.Handle), "NSCoding-3A-ref"); + Assert.That (refObj, Is.Not.SameAs (dummyObj), "NSCoding-3A-ref-same"); + Assert.That (outObj.Handle, Is.Not.EqualTo (dummyObj.Handle), "NSCoding-3A-out"); + Assert.That (outObj, Is.Not.SameAs (dummyObj), "NSCoding-3A-ref-out"); + Assert.That (outObj.Handle, Is.EqualTo (refObj.Handle), "NSCoding-3A-out-ref-eq"); + Assert.That (outObj, Is.Not.SameAs (refObj), "NSCoding-3A-ref-out-not-safe"); Assert.That (refObj.GetType ().FullName, Does.Contain ("CodingWrapper"), "NSCoding-3A-ref-wrapper-type"); Assert.That (outObj.GetType ().FullName, Does.Contain ("CodingWrapper"), "NSCoding-3A-ref-wrapper-type"); @@ -3112,12 +3111,12 @@ public void RefOutTest_INSCoding () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestINSCoding (action << 8, ref refObj, out outObj); - Assert.AreNotEqual (dummyObj.Handle, refObj.Handle, "NSCoding-3M-ref"); - Assert.AreNotSame (dummyObj, refObj, "NSCoding-3M-ref-same"); - Assert.AreNotEqual (dummyObj.Handle, outObj.Handle, "NSCoding-3M-out"); - Assert.AreNotSame (dummyObj, outObj, "NSCoding-3M-ref-out"); - Assert.AreEqual (refObj.Handle, outObj.Handle, "NSCoding-3M-out-ref-eq"); - Assert.AreSame (refObj, outObj, "NSCoding-3M-ref-out-not-safe"); + Assert.That (refObj.Handle, Is.Not.EqualTo (dummyObj.Handle), "NSCoding-3M-ref"); + Assert.That (refObj, Is.Not.SameAs (dummyObj), "NSCoding-3M-ref-same"); + Assert.That (outObj.Handle, Is.Not.EqualTo (dummyObj.Handle), "NSCoding-3M-out"); + Assert.That (outObj, Is.Not.SameAs (dummyObj), "NSCoding-3M-ref-out"); + Assert.That (outObj.Handle, Is.EqualTo (refObj.Handle), "NSCoding-3M-out-ref-eq"); + Assert.That (outObj, Is.SameAs (refObj), "NSCoding-3M-ref-out-not-safe"); Assert.That (refObj, Is.TypeOf (), "NSCoding-3M-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSCoding-3M-ref-wrapper-type"); @@ -3125,9 +3124,9 @@ public void RefOutTest_INSCoding () refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreNotEqual (dummyObj.Handle, refValue, "NSCoding-3DA-ref"); - Assert.AreNotEqual (dummyObj.Handle, outValue, "NSCoding-3DA-out"); - Assert.AreSame (refObj, outObj, "NSCoding-3DA-out-ref-same"); + Assert.That (refValue, Is.Not.EqualTo (dummyObj.Handle), "NSCoding-3DA-ref"); + Assert.That (outValue, Is.Not.EqualTo (dummyObj.Handle), "NSCoding-3DA-out"); + Assert.That (outObj, Is.SameAs (refObj), "NSCoding-3DA-out-ref-same"); Assert.That (refObj, Is.TypeOf (), "NSCoding-3DA-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSCoding-3DA-ref-wrapper-type"); @@ -3135,9 +3134,9 @@ public void RefOutTest_INSCoding () refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreNotEqual (dummyObj.Handle, refValue, "NSCoding-3DM-ref"); - Assert.AreNotEqual (dummyObj.Handle, outValue, "NSCoding-3DM-out"); - Assert.AreSame (refObj, outObj, "NSCoding-3DM-out-ref-eq"); + Assert.That (refValue, Is.Not.EqualTo (dummyObj.Handle), "NSCoding-3DM-ref"); + Assert.That (outValue, Is.Not.EqualTo (dummyObj.Handle), "NSCoding-3DM-out"); + Assert.That (outObj, Is.SameAs (refObj), "NSCoding-3DM-out-ref-eq"); Assert.That (refObj, Is.TypeOf (), "NSCoding-3DM-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSCoding-3DM-ref-wrapper-type"); @@ -3149,9 +3148,9 @@ public void RefOutTest_INSCoding () refObj = null; // set to null outObj = null; // set to null obj.TestINSCoding (action << 0, ref refObj, out outObj); - Assert.AreNotEqual (NativeHandle.Zero, refObj.Handle, "NSCoding-4A-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outObj.Handle, "NSCoding-4A-out"); - Assert.AreNotEqual (refObj.Handle, outObj.Handle, "NSCoding-4A-ref-distinct"); + Assert.That (refObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "NSCoding-4A-ref"); + Assert.That (outObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "NSCoding-4A-out"); + Assert.That (outObj.Handle, Is.Not.EqualTo (refObj.Handle), "NSCoding-4A-ref-distinct"); Assert.That (refObj.GetType ().FullName, Does.Contain ("CodingWrapper"), "NSCoding-4A-ref-wrapper-type"); Assert.That (outObj.GetType ().FullName, Does.Contain ("CodingWrapper"), "NSCoding-4A-ref-wrapper-type"); @@ -3159,9 +3158,9 @@ public void RefOutTest_INSCoding () refObj = null; // set to null outObj = null; // set to null obj.TestINSCoding (action << 8, ref refObj, out outObj); - Assert.AreNotEqual (NativeHandle.Zero, refObj.Handle, "NSCoding-4M-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outObj.Handle, "NSCoding-4M-out"); - Assert.AreNotEqual (refObj.Handle, outObj.Handle, "NSCoding-4M-ref-distinct"); + Assert.That (refObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "NSCoding-4M-ref"); + Assert.That (outObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "NSCoding-4M-out"); + Assert.That (outObj.Handle, Is.Not.EqualTo (refObj.Handle), "NSCoding-4M-ref-distinct"); Assert.That (refObj, Is.TypeOf (), "NSCoding-4M-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSCoding-4M-ref-wrapper-type"); @@ -3169,9 +3168,9 @@ public void RefOutTest_INSCoding () refValue = NativeHandle.Zero; // set to null outValue = NativeHandle.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreNotEqual (NativeHandle.Zero, refValue, "NSCoding-4DA-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outValue, "NSCoding-4DA-out"); - Assert.AreNotEqual (refValue, outValue, "NSCoding-4DA-ref-distinct"); + Assert.That (refValue, Is.Not.EqualTo (NativeHandle.Zero), "NSCoding-4DA-ref"); + Assert.That (outValue, Is.Not.EqualTo (NativeHandle.Zero), "NSCoding-4DA-out"); + Assert.That (outValue, Is.Not.EqualTo (refValue), "NSCoding-4DA-ref-distinct"); Assert.That (refObj, Is.TypeOf (), "NSCoding-4DA-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSCoding-4DA-ref-wrapper-type"); @@ -3179,9 +3178,9 @@ public void RefOutTest_INSCoding () refValue = NativeHandle.Zero; // set to null outValue = NativeHandle.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreNotEqual (NativeHandle.Zero, refValue, "NSCoding-4DM-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outValue, "NSCoding-4DM-out"); - Assert.AreNotEqual (refValue, outValue, "NSCoding-4DM-ref-distinct"); + Assert.That (refValue, Is.Not.EqualTo (NativeHandle.Zero), "NSCoding-4DM-ref"); + Assert.That (outValue, Is.Not.EqualTo (NativeHandle.Zero), "NSCoding-4DM-out"); + Assert.That (outValue, Is.Not.EqualTo (refValue), "NSCoding-4DM-ref-distinct"); Assert.That (refObj, Is.TypeOf (), "NSCoding-4DM-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSCoding-4DM-ref-wrapper-type"); } @@ -3207,29 +3206,29 @@ public void RefOutTest_NSObject () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestNSObject (action << 0, ref refObj, out outObj); - Assert.IsNull (refObj, "NSObject-1A-ref"); - Assert.IsNull (outObj, "NSObject-1A-out"); + Assert.That (refObj, Is.Null, "NSObject-1A-ref"); + Assert.That (outObj, Is.Null, "NSObject-1A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestNSObject (action << 8, ref refObj, out outObj); - Assert.IsNull (refObj, "NSObject-1M-ref"); - Assert.IsNull (outObj, "NSObject-1M-out"); + Assert.That (refObj, Is.Null, "NSObject-1M-ref"); + Assert.That (outObj, Is.Null, "NSObject-1M-out"); // direct native refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "NSObject-1DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSObject-1DA-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "NSObject-1DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSObject-1DA-out"); // direct managed refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "NSObject-1DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSObject-1DM-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "NSObject-1DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSObject-1DM-out"); /// 2: verify that refValue points to something action = 2; @@ -3238,31 +3237,31 @@ public void RefOutTest_NSObject () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestNSObject (action << 0, ref refObj, out outObj); - Assert.AreEqual (dummyObj.Handle, refObj.Handle, "NSObject-2A-ref"); - Assert.AreSame (dummyObj, refObj, "NSObject-2A-ref-same"); - Assert.IsNull (outObj, "NSObject-2A-out"); + Assert.That (refObj.Handle, Is.EqualTo (dummyObj.Handle), "NSObject-2A-ref"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSObject-2A-ref-same"); + Assert.That (outObj, Is.Null, "NSObject-2A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestNSObject (action << 8, ref refObj, out outObj); - Assert.AreEqual (dummyObj.Handle, refObj.Handle, "NSObject-2M-ref"); - Assert.AreSame (dummyObj, refObj, "NSObject-2M-ref-same"); - Assert.IsNull (outObj, "NSObject-2M-out"); + Assert.That (refObj.Handle, Is.EqualTo (dummyObj.Handle), "NSObject-2M-ref"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSObject-2M-ref-same"); + Assert.That (outObj, Is.Null, "NSObject-2M-out"); // direct native refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (dummyObj.Handle, refValue, "NSObject-2DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSObject-2DA-out"); + Assert.That (refValue, Is.EqualTo (dummyObj.Handle), "NSObject-2DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSObject-2DA-out"); // direct managed refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (dummyObj.Handle, refValue, "NSObject-2DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSObject-2DM-out"); + Assert.That (refValue, Is.EqualTo (dummyObj.Handle), "NSObject-2DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSObject-2DM-out"); /// 3 set both parameteres to the same pointer of a NSObject @@ -3272,9 +3271,9 @@ public void RefOutTest_NSObject () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestNSObject (action << 0, ref refObj, out outObj); - Assert.AreNotEqual (dummyObj.Handle, refObj.Handle, "NSObject-3A-ref"); - Assert.AreNotEqual (dummyObj.Handle, outObj.Handle, "NSObject-3A-out"); - Assert.AreSame (refObj, outObj, "NSObject-3A-ref-out-not-safe"); + Assert.That (refObj.Handle, Is.Not.EqualTo (dummyObj.Handle), "NSObject-3A-ref"); + Assert.That (outObj.Handle, Is.Not.EqualTo (dummyObj.Handle), "NSObject-3A-out"); + Assert.That (outObj, Is.SameAs (refObj), "NSObject-3A-ref-out-not-safe"); Assert.That (refObj, Is.TypeOf (), "NSObject-3A-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSObject-3A-ref-wrapper-type"); @@ -3282,9 +3281,9 @@ public void RefOutTest_NSObject () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestNSObject (action << 8, ref refObj, out outObj); - Assert.AreNotEqual (dummyObj.Handle, refObj.Handle, "NSObject-3M-ref"); - Assert.AreNotEqual (dummyObj.Handle, outObj.Handle, "NSObject-3M-out"); - Assert.AreSame (refObj, outObj, "NSObject-3M-ref-out-not-safe"); + Assert.That (refObj.Handle, Is.Not.EqualTo (dummyObj.Handle), "NSObject-3M-ref"); + Assert.That (outObj.Handle, Is.Not.EqualTo (dummyObj.Handle), "NSObject-3M-out"); + Assert.That (outObj, Is.SameAs (refObj), "NSObject-3M-ref-out-not-safe"); Assert.That (refObj, Is.TypeOf (), "NSObject-3M-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSObject-3M-ref-wrapper-type"); @@ -3292,9 +3291,9 @@ public void RefOutTest_NSObject () refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreNotEqual (dummyObj.Handle, refValue, "NSObject-3DA-ref"); - Assert.AreNotEqual (dummyObj.Handle, outValue, "NSObject-3DA-out"); - Assert.AreEqual (refValue, outValue, "NSObject-3DA-out-ref-same"); + Assert.That (refValue, Is.Not.EqualTo (dummyObj.Handle), "NSObject-3DA-ref"); + Assert.That (outValue, Is.Not.EqualTo (dummyObj.Handle), "NSObject-3DA-out"); + Assert.That (outValue, Is.EqualTo (refValue), "NSObject-3DA-out-ref-same"); Assert.That (Runtime.GetNSObject (refValue), Is.TypeOf (), "NSObject-3DA-ref-wrapper-type"); Assert.That (Runtime.GetNSObject (outValue), Is.TypeOf (), "NSObject-3DA-ref-wrapper-type"); @@ -3302,9 +3301,9 @@ public void RefOutTest_NSObject () refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreNotEqual (dummyObj.Handle, refValue, "NSObject-3DM-ref"); - Assert.AreNotEqual (dummyObj.Handle, outValue, "NSObject-3DM-out"); - Assert.AreEqual (refValue, outValue, "NSObject-3DM-out-ref-eq"); + Assert.That (refValue, Is.Not.EqualTo (dummyObj.Handle), "NSObject-3DM-ref"); + Assert.That (outValue, Is.Not.EqualTo (dummyObj.Handle), "NSObject-3DM-out"); + Assert.That (outValue, Is.EqualTo (refValue), "NSObject-3DM-out-ref-eq"); Assert.That (Runtime.GetNSObject (refValue), Is.TypeOf (), "NSObject-3DM-ref-wrapper-type"); Assert.That (Runtime.GetNSObject (outValue), Is.TypeOf (), "NSObject-3DM-ref-wrapper-type"); @@ -3316,9 +3315,9 @@ public void RefOutTest_NSObject () refObj = null; // set to null outObj = null; // set to null obj.TestNSObject (action << 0, ref refObj, out outObj); - Assert.AreNotEqual (NativeHandle.Zero, refObj.Handle, "NSObject-4A-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outObj.Handle, "NSObject-4A-out"); - Assert.AreNotEqual (refObj.Handle, outObj.Handle, "NSObject-4A-ref-distinct"); + Assert.That (refObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "NSObject-4A-ref"); + Assert.That (outObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "NSObject-4A-out"); + Assert.That (outObj.Handle, Is.Not.EqualTo (refObj.Handle), "NSObject-4A-ref-distinct"); Assert.That (refObj, Is.TypeOf (), "NSObject-4A-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSObject-4A-ref-wrapper-type"); @@ -3326,9 +3325,9 @@ public void RefOutTest_NSObject () refObj = null; // set to null outObj = null; // set to null obj.TestNSObject (action << 8, ref refObj, out outObj); - Assert.AreNotEqual (NativeHandle.Zero, refObj.Handle, "NSObject-4M-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outObj.Handle, "NSObject-4M-out"); - Assert.AreNotEqual (refObj.Handle, outObj.Handle, "NSObject-4M-ref-distinct"); + Assert.That (refObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "NSObject-4M-ref"); + Assert.That (outObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "NSObject-4M-out"); + Assert.That (outObj.Handle, Is.Not.EqualTo (refObj.Handle), "NSObject-4M-ref-distinct"); Assert.That (refObj, Is.TypeOf (), "NSObject-4M-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSObject-4M-ref-wrapper-type"); @@ -3336,9 +3335,9 @@ public void RefOutTest_NSObject () refValue = NativeHandle.Zero; // set to null outValue = NativeHandle.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreNotEqual (NativeHandle.Zero, refValue, "NSObject-4DA-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outValue, "NSObject-4DA-out"); - Assert.AreNotEqual (refValue, outValue, "NSObject-4DA-ref-distinct"); + Assert.That (refValue, Is.Not.EqualTo (NativeHandle.Zero), "NSObject-4DA-ref"); + Assert.That (outValue, Is.Not.EqualTo (NativeHandle.Zero), "NSObject-4DA-out"); + Assert.That (outValue, Is.Not.EqualTo (refValue), "NSObject-4DA-ref-distinct"); Assert.That (Runtime.GetNSObject (refValue), Is.TypeOf (), "NSObject-4DA-ref-wrapper-type"); Assert.That (Runtime.GetNSObject (outValue), Is.TypeOf (), "NSObject-4DA-ref-wrapper-type"); @@ -3346,9 +3345,9 @@ public void RefOutTest_NSObject () refValue = NativeHandle.Zero; // set to null outValue = NativeHandle.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreNotEqual (NativeHandle.Zero, refValue, "NSObject-4DM-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outValue, "NSObject-4DM-out"); - Assert.AreNotEqual (refValue, outValue, "NSObject-4DM-ref-distinct"); + Assert.That (refValue, Is.Not.EqualTo (NativeHandle.Zero), "NSObject-4DM-ref"); + Assert.That (outValue, Is.Not.EqualTo (NativeHandle.Zero), "NSObject-4DM-out"); + Assert.That (outValue, Is.Not.EqualTo (refValue), "NSObject-4DM-ref-distinct"); Assert.That (Runtime.GetNSObject (refValue), Is.TypeOf (), "NSObject-4DM-ref-wrapper-type"); Assert.That (Runtime.GetNSObject (outValue), Is.TypeOf (), "NSObject-4DM-ref-wrapper-type"); } @@ -3374,29 +3373,29 @@ public void RefOutTest_NSValue () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestValue (action << 0, ref refObj, out outObj); - Assert.IsNull (refObj, "NSValue-1A-ref"); - Assert.IsNull (outObj, "NSValue-1A-out"); + Assert.That (refObj, Is.Null, "NSValue-1A-ref"); + Assert.That (outObj, Is.Null, "NSValue-1A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestValue (action << 8, ref refObj, out outObj); - Assert.IsNull (refObj, "NSValue-1M-ref"); - Assert.IsNull (outObj, "NSValue-1M-out"); + Assert.That (refObj, Is.Null, "NSValue-1M-ref"); + Assert.That (outObj, Is.Null, "NSValue-1M-out"); // direct native refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "NSValue-1DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSValue-1DA-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "NSValue-1DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSValue-1DA-out"); // direct managed refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "NSValue-1DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSValue-1DM-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "NSValue-1DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSValue-1DM-out"); /// 2: verify that refValue points to something action = 2; @@ -3405,31 +3404,31 @@ public void RefOutTest_NSValue () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestValue (action << 0, ref refObj, out outObj); - Assert.AreEqual (dummyObj.Handle, refObj.Handle, "NSValue-2A-ref"); - Assert.AreSame (dummyObj, refObj, "NSValue-2A-ref-same"); - Assert.IsNull (outObj, "NSValue-2A-out"); + Assert.That (refObj.Handle, Is.EqualTo (dummyObj.Handle), "NSValue-2A-ref"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSValue-2A-ref-same"); + Assert.That (outObj, Is.Null, "NSValue-2A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestValue (action << 8, ref refObj, out outObj); - Assert.AreEqual (dummyObj.Handle, refObj.Handle, "NSValue-2M-ref"); - Assert.AreSame (dummyObj, refObj, "NSValue-2M-ref-same"); - Assert.IsNull (outObj, "NSValue-2M-out"); + Assert.That (refObj.Handle, Is.EqualTo (dummyObj.Handle), "NSValue-2M-ref"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSValue-2M-ref-same"); + Assert.That (outObj, Is.Null, "NSValue-2M-out"); // direct native refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (dummyObj.Handle, refValue, "NSValue-2DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSValue-2DA-out"); + Assert.That (refValue, Is.EqualTo (dummyObj.Handle), "NSValue-2DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSValue-2DA-out"); // direct managed refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (dummyObj.Handle, refValue, "NSValue-2DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSValue-2DM-out"); + Assert.That (refValue, Is.EqualTo (dummyObj.Handle), "NSValue-2DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSValue-2DM-out"); /// 3 set both parameteres to the same pointer of a NSValue @@ -3439,9 +3438,9 @@ public void RefOutTest_NSValue () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestValue (action << 0, ref refObj, out outObj); - Assert.AreNotEqual (dummyObj.Handle, refObj.Handle, "NSValue-3A-ref"); - Assert.AreNotEqual (dummyObj.Handle, outObj.Handle, "NSValue-3A-out"); - Assert.AreSame (refObj, outObj, "NSValue-3A-ref-out-not-safe"); + Assert.That (refObj.Handle, Is.Not.EqualTo (dummyObj.Handle), "NSValue-3A-ref"); + Assert.That (outObj.Handle, Is.Not.EqualTo (dummyObj.Handle), "NSValue-3A-out"); + Assert.That (outObj, Is.SameAs (refObj), "NSValue-3A-ref-out-not-safe"); Assert.That (refObj, Is.TypeOf (), "NSValue-3A-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSValue-3A-ref-wrapper-type"); @@ -3449,9 +3448,9 @@ public void RefOutTest_NSValue () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestValue (action << 8, ref refObj, out outObj); - Assert.AreNotEqual (dummyObj.Handle, refObj.Handle, "NSValue-3M-ref"); - Assert.AreNotEqual (dummyObj.Handle, outObj.Handle, "NSValue-3M-out"); - Assert.AreSame (refObj, outObj, "NSValue-3M-ref-out-not-safe"); + Assert.That (refObj.Handle, Is.Not.EqualTo (dummyObj.Handle), "NSValue-3M-ref"); + Assert.That (outObj.Handle, Is.Not.EqualTo (dummyObj.Handle), "NSValue-3M-out"); + Assert.That (outObj, Is.SameAs (refObj), "NSValue-3M-ref-out-not-safe"); Assert.That (refObj, Is.TypeOf (), "NSValue-3M-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSValue-3M-ref-wrapper-type"); @@ -3459,9 +3458,9 @@ public void RefOutTest_NSValue () refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreNotEqual (dummyObj.Handle, refValue, "NSValue-3DA-ref"); - Assert.AreNotEqual (dummyObj.Handle, outValue, "NSValue-3DA-out"); - Assert.AreEqual (refValue, outValue, "NSValue-3DA-out-ref-same"); + Assert.That (refValue, Is.Not.EqualTo (dummyObj.Handle), "NSValue-3DA-ref"); + Assert.That (outValue, Is.Not.EqualTo (dummyObj.Handle), "NSValue-3DA-out"); + Assert.That (outValue, Is.EqualTo (refValue), "NSValue-3DA-out-ref-same"); Assert.That (Runtime.GetNSObject (refValue), Is.TypeOf (), "NSValue-3DA-ref-wrapper-type"); Assert.That (Runtime.GetNSObject (outValue), Is.TypeOf (), "NSValue-3DA-ref-wrapper-type"); @@ -3469,9 +3468,9 @@ public void RefOutTest_NSValue () refValue = dummyObj.Handle; // set to non-null outValue = dummyObj.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreNotEqual (dummyObj.Handle, refValue, "NSValue-3DM-ref"); - Assert.AreNotEqual (dummyObj.Handle, outValue, "NSValue-3DM-out"); - Assert.AreEqual (refValue, outValue, "NSValue-3DM-out-ref-eq"); + Assert.That (refValue, Is.Not.EqualTo (dummyObj.Handle), "NSValue-3DM-ref"); + Assert.That (outValue, Is.Not.EqualTo (dummyObj.Handle), "NSValue-3DM-out"); + Assert.That (outValue, Is.EqualTo (refValue), "NSValue-3DM-out-ref-eq"); Assert.That (Runtime.GetNSObject (refValue), Is.TypeOf (), "NSValue-3DM-ref-wrapper-type"); Assert.That (Runtime.GetNSObject (outValue), Is.TypeOf (), "NSValue-3DM-ref-wrapper-type"); @@ -3483,9 +3482,9 @@ public void RefOutTest_NSValue () refObj = null; // set to null outObj = null; // set to null obj.TestValue (action << 0, ref refObj, out outObj); - Assert.AreNotEqual (NativeHandle.Zero, refObj.Handle, "NSValue-4A-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outObj.Handle, "NSValue-4A-out"); - Assert.AreNotEqual (refObj.Handle, outObj.Handle, "NSValue-4A-ref-distinct"); + Assert.That (refObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "NSValue-4A-ref"); + Assert.That (outObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "NSValue-4A-out"); + Assert.That (outObj.Handle, Is.Not.EqualTo (refObj.Handle), "NSValue-4A-ref-distinct"); Assert.That (refObj, Is.TypeOf (), "NSValue-4A-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSValue-4A-ref-wrapper-type"); @@ -3493,9 +3492,9 @@ public void RefOutTest_NSValue () refObj = null; // set to null outObj = null; // set to null obj.TestValue (action << 8, ref refObj, out outObj); - Assert.AreNotEqual (NativeHandle.Zero, refObj.Handle, "NSValue-4M-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outObj.Handle, "NSValue-4M-out"); - Assert.AreNotEqual (refObj.Handle, outObj.Handle, "NSValue-4M-ref-distinct"); + Assert.That (refObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "NSValue-4M-ref"); + Assert.That (outObj.Handle, Is.Not.EqualTo (NativeHandle.Zero), "NSValue-4M-out"); + Assert.That (outObj.Handle, Is.Not.EqualTo (refObj.Handle), "NSValue-4M-ref-distinct"); Assert.That (refObj, Is.TypeOf (), "NSValue-4M-ref-wrapper-type"); Assert.That (outObj, Is.TypeOf (), "NSValue-4M-ref-wrapper-type"); @@ -3503,9 +3502,9 @@ public void RefOutTest_NSValue () refValue = NativeHandle.Zero; // set to null outValue = NativeHandle.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreNotEqual (NativeHandle.Zero, refValue, "NSValue-4DA-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outValue, "NSValue-4DA-out"); - Assert.AreNotEqual (refValue, outValue, "NSValue-4DA-ref-distinct"); + Assert.That (refValue, Is.Not.EqualTo (NativeHandle.Zero), "NSValue-4DA-ref"); + Assert.That (outValue, Is.Not.EqualTo (NativeHandle.Zero), "NSValue-4DA-out"); + Assert.That (outValue, Is.Not.EqualTo (refValue), "NSValue-4DA-ref-distinct"); Assert.That (Runtime.GetNSObject (refValue), Is.TypeOf (), "NSValue-4DA-ref-wrapper-type"); Assert.That (Runtime.GetNSObject (outValue), Is.TypeOf (), "NSValue-4DA-ref-wrapper-type"); @@ -3513,9 +3512,9 @@ public void RefOutTest_NSValue () refValue = NativeHandle.Zero; // set to null outValue = NativeHandle.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreNotEqual (NativeHandle.Zero, refValue, "NSValue-4DM-ref"); - Assert.AreNotEqual (NativeHandle.Zero, outValue, "NSValue-4DM-out"); - Assert.AreNotEqual (refValue, outValue, "NSValue-4DM-ref-distinct"); + Assert.That (refValue, Is.Not.EqualTo (NativeHandle.Zero), "NSValue-4DM-ref"); + Assert.That (outValue, Is.Not.EqualTo (NativeHandle.Zero), "NSValue-4DM-out"); + Assert.That (outValue, Is.Not.EqualTo (refValue), "NSValue-4DM-ref-distinct"); Assert.That (Runtime.GetNSObject (refValue), Is.TypeOf (), "NSValue-4DM-ref-wrapper-type"); Assert.That (Runtime.GetNSObject (outValue), Is.TypeOf (), "NSValue-4DM-ref-wrapper-type"); } @@ -3542,29 +3541,29 @@ public void RefOutTest_String () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestString (action << 0, ref refObj, out outObj); - Assert.IsNull (refObj, "String-1A-ref"); - Assert.IsNull (outObj, "String-1A-out"); + Assert.That (refObj, Is.Null, "String-1A-ref"); + Assert.That (outObj, Is.Null, "String-1A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestString (action << 8, ref refObj, out outObj); - Assert.IsNull (refObj, "String-1M-ref"); - Assert.IsNull (outObj, "String-1M-out"); + Assert.That (refObj, Is.Null, "String-1M-ref"); + Assert.That (outObj, Is.Null, "String-1M-out"); // direct native refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "String-1DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "String-1DA-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "String-1DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "String-1DA-out"); // direct managed refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "String-1DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "String-1DM-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "String-1DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "String-1DM-out"); /// 2: verify that refValue points to something action = 2; @@ -3573,29 +3572,29 @@ public void RefOutTest_String () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestString (action << 0, ref refObj, out outObj); - Assert.AreEqual (dummyObj, refObj, "String-2A-ref"); - Assert.IsNull (outObj, "String-2A-out"); + Assert.That (refObj, Is.EqualTo (dummyObj), "String-2A-ref"); + Assert.That (outObj, Is.Null, "String-2A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestString (action << 8, ref refObj, out outObj); - Assert.AreEqual (dummyObj, refObj, "String-2M-ref"); - Assert.IsNull (outObj, "String-2M-out"); + Assert.That (refObj, Is.EqualTo (dummyObj), "String-2M-ref"); + Assert.That (outObj, Is.Null, "String-2M-out"); // direct native refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (dummyObj, NSString.FromHandle (refValue), "String-2DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "String-2DA-out"); + Assert.That (NSString.FromHandle (refValue), Is.EqualTo (dummyObj), "String-2DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "String-2DA-out"); // direct managed refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (dummyObj, NSString.FromHandle (refValue), "String-2DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "String-2DM-out"); + Assert.That (NSString.FromHandle (refValue), Is.EqualTo (dummyObj), "String-2DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "String-2DM-out"); /// 3 set both parameteres to the same pointer of a String @@ -3605,31 +3604,31 @@ public void RefOutTest_String () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestString (action << 0, ref refObj, out outObj); - Assert.AreEqual ("A constant native string", refObj, "String-3A-ref"); - Assert.AreEqual ("A constant native string", outObj, "String-3A-out"); + Assert.That (refObj, Is.EqualTo ("A constant native string"), "String-3A-ref"); + Assert.That (outObj, Is.EqualTo ("A constant native string"), "String-3A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null obj.TestString (action << 8, ref refObj, out outObj); - Assert.AreEqual ("A constant managed string", refObj, "String-3M-ref"); - Assert.AreEqual ("A constant managed string", outObj, "String-3M-out"); + Assert.That (refObj, Is.EqualTo ("A constant managed string"), "String-3M-ref"); + Assert.That (outObj, Is.EqualTo ("A constant managed string"), "String-3M-out"); // direct native refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreNotEqual (refValue, outValue, "String-3DA-eq"); // The managed roundtrip means 'outValue' is re-created (because it's nulled out upon entering managed code) - Assert.AreEqual ("A constant native string", NSString.FromHandle (refValue), "String-3DA-ref"); - Assert.AreEqual ("A constant native string", NSString.FromHandle (outValue), "String-3DA-out"); + Assert.That (outValue, Is.Not.EqualTo (refValue), "String-3DA-eq"); // The managed roundtrip means 'outValue' is re-created (because it's nulled out upon entering managed code) + Assert.That (NSString.FromHandle (refValue), Is.EqualTo ("A constant native string"), "String-3DA-ref"); + Assert.That (NSString.FromHandle (outValue), Is.EqualTo ("A constant native string"), "String-3DA-out"); // direct managed refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreNotEqual (refValue, outValue, "String-3DM-eq"); // The managed roundtrip means 'outValue' is re-created (because it's nulled out upon entering managed code) - Assert.AreEqual ("A constant managed string", NSString.FromHandle (refValue), "String-3DM-ref"); - Assert.AreEqual ("A constant managed string", NSString.FromHandle (outValue), "String-3DM-out"); + Assert.That (outValue, Is.Not.EqualTo (refValue), "String-3DM-eq"); // The managed roundtrip means 'outValue' is re-created (because it's nulled out upon entering managed code) + Assert.That (NSString.FromHandle (refValue), Is.EqualTo ("A constant managed string"), "String-3DM-ref"); + Assert.That (NSString.FromHandle (outValue), Is.EqualTo ("A constant managed string"), "String-3DM-out"); /// 4 set both parameteres to different pointers of a String @@ -3639,29 +3638,29 @@ public void RefOutTest_String () refObj = null; // set to null outObj = null; // set to null obj.TestString (action << 0, ref refObj, out outObj); - Assert.AreEqual ("Hello Xamarin", refObj, "String-4A-ref-value"); - Assert.AreEqual ("Hello Microsoft", outObj, "String-4A-out-value"); + Assert.That (refObj, Is.EqualTo ("Hello Xamarin"), "String-4A-ref-value"); + Assert.That (outObj, Is.EqualTo ("Hello Microsoft"), "String-4A-out-value"); // managed refObj = null; // set to null outObj = null; // set to null obj.TestString (action << 8, ref refObj, out outObj); - Assert.AreEqual ("Hello Xamarin from managed", refObj, "String-4M-ref-value"); - Assert.AreEqual ("Hello Microsoft from managed", outObj, "String-4M-out-value"); + Assert.That (refObj, Is.EqualTo ("Hello Xamarin from managed"), "String-4M-ref-value"); + Assert.That (outObj, Is.EqualTo ("Hello Microsoft from managed"), "String-4M-out-value"); // direct native refValue = IntPtr.Zero; // set to null outValue = IntPtr.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual ("Hello Xamarin", NSString.FromHandle (refValue), "String-4DA-ref-value"); - Assert.AreEqual ("Hello Microsoft", NSString.FromHandle (outValue), "String-4DA-out-value"); + Assert.That (NSString.FromHandle (refValue), Is.EqualTo ("Hello Xamarin"), "String-4DA-ref-value"); + Assert.That (NSString.FromHandle (outValue), Is.EqualTo ("Hello Microsoft"), "String-4DA-out-value"); // direct managed refValue = IntPtr.Zero; // set to null outValue = IntPtr.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual ("Hello Xamarin from managed", NSString.FromHandle (refValue), "String-4DM-ref-value"); - Assert.AreEqual ("Hello Microsoft from managed", NSString.FromHandle (outValue), "String-4DM-out-value"); + Assert.That (NSString.FromHandle (refValue), Is.EqualTo ("Hello Xamarin from managed"), "String-4DM-ref-value"); + Assert.That (NSString.FromHandle (outValue), Is.EqualTo ("Hello Microsoft from managed"), "String-4DM-out-value"); } } @@ -3684,36 +3683,36 @@ public unsafe void RefOutTest_Int () outObj = dummyObj; // set to non-null ptrObj = dummyObj; // set to non-null obj.TestInt (action << 0, ref refObj, out outObj, &ptrObj); - Assert.AreEqual (0, refObj, "Int-1A-ref"); - Assert.AreEqual (0, outObj, "Int-1A-out"); - Assert.AreEqual (0, ptrObj, "Int-1A-ptr"); + Assert.That (refObj, Is.EqualTo (0), "Int-1A-ref"); + Assert.That (outObj, Is.EqualTo (0), "Int-1A-out"); + Assert.That (ptrObj, Is.EqualTo (0), "Int-1A-ptr"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null ptrObj = dummyObj; // set to non-null obj.TestInt (action << 8, ref refObj, out outObj, &ptrObj); - Assert.AreEqual (0, refObj, "Int-1M-ref"); - Assert.AreEqual (0, outObj, "Int-1M-out"); - Assert.AreEqual (0, ptrObj, "Int-1M-ptr"); + Assert.That (refObj, Is.EqualTo (0), "Int-1M-ref"); + Assert.That (outObj, Is.EqualTo (0), "Int-1M-out"); + Assert.That (ptrObj, Is.EqualTo (0), "Int-1M-ptr"); // direct native refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null ptrObj = dummyObj; // set to non-null Messaging.void_objc_msgSend_int_int_int_int (obj.Handle, sel, action << 0, ref refObj, out outObj, &ptrObj); - Assert.AreEqual (0, refObj, "Int-1DA-ref"); - Assert.AreEqual (0, outObj, "Int-1DA-out"); - Assert.AreEqual (0, ptrObj, "Int-1DA-ptr"); + Assert.That (refObj, Is.EqualTo (0), "Int-1DA-ref"); + Assert.That (outObj, Is.EqualTo (0), "Int-1DA-out"); + Assert.That (ptrObj, Is.EqualTo (0), "Int-1DA-ptr"); // direct managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null ptrObj = dummyObj; // set to non-null Messaging.void_objc_msgSend_int_int_int_int (obj.Handle, sel, action << 8, ref refObj, out outObj, &ptrObj); - Assert.AreEqual (0, refObj, "Int-1DM-ref"); - Assert.AreEqual (0, outObj, "Int-1DM-out"); - Assert.AreEqual (0, ptrObj, "Int-1DM-ptr"); + Assert.That (refObj, Is.EqualTo (0), "Int-1DM-ref"); + Assert.That (outObj, Is.EqualTo (0), "Int-1DM-out"); + Assert.That (ptrObj, Is.EqualTo (0), "Int-1DM-ptr"); /// 2: N/A for testInt @@ -3725,44 +3724,44 @@ public unsafe void RefOutTest_Int () outObj = dummyObj; // set to non-null ptrObj = dummyObj; // set to non-null obj.TestInt (action << 0, ref refObj, out outObj, &ptrObj); - Assert.AreNotEqual (dummyObj, refObj, "Int-3A-ref"); - Assert.AreNotEqual (dummyObj, outObj, "Int-3A-out"); - Assert.AreNotEqual (dummyObj, ptrObj, "Int-3A-ptr"); - Assert.AreEqual (refObj, outObj, "Int-3A-out-ref-eq"); - Assert.AreEqual (refObj, ptrObj, "Int-3A-out-ptr-eq"); + Assert.That (refObj, Is.Not.EqualTo (dummyObj), "Int-3A-ref"); + Assert.That (outObj, Is.Not.EqualTo (dummyObj), "Int-3A-out"); + Assert.That (ptrObj, Is.Not.EqualTo (dummyObj), "Int-3A-ptr"); + Assert.That (outObj, Is.EqualTo (refObj), "Int-3A-out-ref-eq"); + Assert.That (ptrObj, Is.EqualTo (refObj), "Int-3A-out-ptr-eq"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null ptrObj = dummyObj; // set to non-null obj.TestInt (action << 8, ref refObj, out outObj, &ptrObj); - Assert.AreNotEqual (dummyObj, refObj, "Int-3M-ref"); - Assert.AreNotEqual (dummyObj, outObj, "Int-3M-out"); - Assert.AreNotEqual (dummyObj, ptrObj, "Int-3M-ptr"); - Assert.AreEqual (refObj, outObj, "Int-3M-out-ref-eq"); - Assert.AreEqual (refObj, ptrObj, "Int-3M-out-ptr-eq"); + Assert.That (refObj, Is.Not.EqualTo (dummyObj), "Int-3M-ref"); + Assert.That (outObj, Is.Not.EqualTo (dummyObj), "Int-3M-out"); + Assert.That (ptrObj, Is.Not.EqualTo (dummyObj), "Int-3M-ptr"); + Assert.That (outObj, Is.EqualTo (refObj), "Int-3M-out-ref-eq"); + Assert.That (ptrObj, Is.EqualTo (refObj), "Int-3M-out-ptr-eq"); // direct native refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null ptrObj = dummyObj; // set to non-null Messaging.void_objc_msgSend_int_int_int_int (obj.Handle, sel, action << 0, ref refObj, out outObj, &ptrObj); - Assert.AreNotEqual (dummyObj, refObj, "Int-3DA-ref"); - Assert.AreNotEqual (dummyObj, outObj, "Int-3DA-out"); - Assert.AreNotEqual (dummyObj, ptrObj, "Int-3DA-ptr"); - Assert.AreEqual (refObj, outObj, "Int-3DA-out-ref-same"); - Assert.AreEqual (refObj, ptrObj, "Int-3DA-out-ptr-same"); + Assert.That (refObj, Is.Not.EqualTo (dummyObj), "Int-3DA-ref"); + Assert.That (outObj, Is.Not.EqualTo (dummyObj), "Int-3DA-out"); + Assert.That (ptrObj, Is.Not.EqualTo (dummyObj), "Int-3DA-ptr"); + Assert.That (outObj, Is.EqualTo (refObj), "Int-3DA-out-ref-same"); + Assert.That (ptrObj, Is.EqualTo (refObj), "Int-3DA-out-ptr-same"); // direct managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null ptrObj = dummyObj; // set to non-null Messaging.void_objc_msgSend_int_int_int_int (obj.Handle, sel, action << 8, ref refObj, out outObj, &ptrObj); - Assert.AreNotEqual (dummyObj, refObj, "Int-3DM-ref"); - Assert.AreNotEqual (dummyObj, outObj, "Int-3DM-out"); - Assert.AreNotEqual (dummyObj, ptrObj, "Int-3DM-ptr"); - Assert.AreEqual (refObj, outObj, "Int-3DM-out-ref-eq"); - Assert.AreEqual (refObj, ptrObj, "Int-3DM-out-ptr-eq"); + Assert.That (refObj, Is.Not.EqualTo (dummyObj), "Int-3DM-ref"); + Assert.That (outObj, Is.Not.EqualTo (dummyObj), "Int-3DM-out"); + Assert.That (ptrObj, Is.Not.EqualTo (dummyObj), "Int-3DM-ptr"); + Assert.That (outObj, Is.EqualTo (refObj), "Int-3DM-out-ref-eq"); + Assert.That (ptrObj, Is.EqualTo (refObj), "Int-3DM-out-ptr-eq"); /// 4 set both parameteres to different pointers of a Int @@ -3773,50 +3772,50 @@ public unsafe void RefOutTest_Int () outObj = 0; // set to 0 ptrObj = 0; // set to 0 obj.TestInt (action << 0, ref refObj, out outObj, &ptrObj); - Assert.AreNotEqual (0, refObj, "Int-4A-ref"); - Assert.AreNotEqual (0, outObj, "Int-4A-out"); - Assert.AreNotEqual (0, ptrObj, "Int-4A-ptr"); - Assert.AreNotEqual (refObj, outObj, "Int-4A-ref-distinct"); - Assert.AreNotEqual (refObj, ptrObj, "Int-4A-ptr-distinct"); + Assert.That (refObj, Is.Not.EqualTo (0), "Int-4A-ref"); + Assert.That (outObj, Is.Not.EqualTo (0), "Int-4A-out"); + Assert.That (ptrObj, Is.Not.EqualTo (0), "Int-4A-ptr"); + Assert.That (outObj, Is.Not.EqualTo (refObj), "Int-4A-ref-distinct"); + Assert.That (ptrObj, Is.Not.EqualTo (refObj), "Int-4A-ptr-distinct"); // managed refObj = 0; // set to 0 outObj = 0; // set to 0 ptrObj = 0; // set to 0 obj.TestInt (action << 8, ref refObj, out outObj, &ptrObj); - Assert.AreNotEqual (0, refObj, "Int-4M-ref"); - Assert.AreNotEqual (0, outObj, "Int-4M-out"); - Assert.AreNotEqual (0, ptrObj, "Int-4M-ptr"); - Assert.AreNotEqual (refObj, outObj, "Int-4M-ref-distinct"); - Assert.AreNotEqual (refObj, ptrObj, "Int-4M-ptr-distinct"); + Assert.That (refObj, Is.Not.EqualTo (0), "Int-4M-ref"); + Assert.That (outObj, Is.Not.EqualTo (0), "Int-4M-out"); + Assert.That (ptrObj, Is.Not.EqualTo (0), "Int-4M-ptr"); + Assert.That (outObj, Is.Not.EqualTo (refObj), "Int-4M-ref-distinct"); + Assert.That (ptrObj, Is.Not.EqualTo (refObj), "Int-4M-ptr-distinct"); // direct native refObj = 0; // set to 0 outObj = 0; // set to 0 ptrObj = 0; // set to 0 Messaging.void_objc_msgSend_int_int_int_int (obj.Handle, sel, action << 0, ref refObj, out outObj, &ptrObj); - Assert.AreNotEqual (0, refObj, "Int-4DA-ref"); - Assert.AreNotEqual (0, outObj, "Int-4DA-out"); - Assert.AreNotEqual (0, ptrObj, "Int-4DA-ptr"); - Assert.AreNotEqual (refObj, outObj, "Int-4DA-ref-distinct"); - Assert.AreNotEqual (refObj, ptrObj, "Int-4DA-ptr-distinct"); - Assert.AreEqual (3141592, refObj, "Int-4DA-ref-value"); - Assert.AreEqual (2718282, outObj, "Int-4DA-out-value"); - Assert.AreEqual (5772156, ptrObj, "Int-4DA-ptr-value"); + Assert.That (refObj, Is.Not.EqualTo (0), "Int-4DA-ref"); + Assert.That (outObj, Is.Not.EqualTo (0), "Int-4DA-out"); + Assert.That (ptrObj, Is.Not.EqualTo (0), "Int-4DA-ptr"); + Assert.That (outObj, Is.Not.EqualTo (refObj), "Int-4DA-ref-distinct"); + Assert.That (ptrObj, Is.Not.EqualTo (refObj), "Int-4DA-ptr-distinct"); + Assert.That (refObj, Is.EqualTo (3141592), "Int-4DA-ref-value"); + Assert.That (outObj, Is.EqualTo (2718282), "Int-4DA-out-value"); + Assert.That (ptrObj, Is.EqualTo (5772156), "Int-4DA-ptr-value"); // direct managed refObj = 0; // set to 0 outObj = 0; // set to 0 ptrObj = 0; // set to 0 Messaging.void_objc_msgSend_int_int_int_int (obj.Handle, sel, action << 8, ref refObj, out outObj, &ptrObj); - Assert.AreNotEqual (0, refObj, "Int-4DM-ref"); - Assert.AreNotEqual (0, outObj, "Int-4DM-out"); - Assert.AreNotEqual (0, ptrObj, "Int-4DM-ptr"); - Assert.AreNotEqual (refObj, outObj, "Int-4DM-ref-distinct"); - Assert.AreNotEqual (refObj, ptrObj, "Int-4DM-ptr-distinct"); - Assert.AreEqual (3141592, refObj, "Int-4DM-ref-value"); - Assert.AreEqual (2718282, outObj, "Int-4DM-out-value"); - Assert.AreEqual (5772156, ptrObj, "Int-4DM-ptr-value"); + Assert.That (refObj, Is.Not.EqualTo (0), "Int-4DM-ref"); + Assert.That (outObj, Is.Not.EqualTo (0), "Int-4DM-out"); + Assert.That (ptrObj, Is.Not.EqualTo (0), "Int-4DM-ptr"); + Assert.That (outObj, Is.Not.EqualTo (refObj), "Int-4DM-ref-distinct"); + Assert.That (ptrObj, Is.Not.EqualTo (refObj), "Int-4DM-ptr-distinct"); + Assert.That (refObj, Is.EqualTo (3141592), "Int-4DM-ref-value"); + Assert.That (outObj, Is.EqualTo (2718282), "Int-4DM-out-value"); + Assert.That (ptrObj, Is.EqualTo (5772156), "Int-4DM-ptr-value"); } } @@ -3842,15 +3841,15 @@ public void RefOutTest_Sel () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.IsNull (refObj, "Selector-1A-ref"); - Assert.IsNull (outObj, "Selector-1A-out"); + Assert.That (refObj, Is.Null, "Selector-1A-ref"); + Assert.That (outObj, Is.Null, "Selector-1A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.IsNull (refObj, "Selector-1M-ref"); - Assert.IsNull (outObj, "Selector-1M-out"); + Assert.That (refObj, Is.Null, "Selector-1M-ref"); + Assert.That (outObj, Is.Null, "Selector-1M-out"); // direct native refValue = dummyObjHandle; // set to non-null @@ -3860,15 +3859,15 @@ public void RefOutTest_Sel () //Marshal.WriteIntPtr (x, 8, (IntPtr) 0xbabebabe); //Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, x, x); Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (IntPtr.Zero, refValue, "Selector-1DA-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "Selector-1DA-out"); + Assert.That (refValue, Is.EqualTo (IntPtr.Zero), "Selector-1DA-ref"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "Selector-1DA-out"); // direct managed refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (IntPtr.Zero, refValue, "Selector-1DM-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "Selector-1DM-out"); + Assert.That (refValue, Is.EqualTo (IntPtr.Zero), "Selector-1DM-ref"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "Selector-1DM-out"); /// 2: verify that refValue points to something action = 2; @@ -3877,29 +3876,29 @@ public void RefOutTest_Sel () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.AreEqual (dummyObj, refObj, "Selector-2A-ref"); - Assert.IsNull (outObj, "Selector-2A-out"); + Assert.That (refObj, Is.EqualTo (dummyObj), "Selector-2A-ref"); + Assert.That (outObj, Is.Null, "Selector-2A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.AreEqual (dummyObj, refObj, "Selector-2M-ref"); - Assert.IsNull (outObj, "Selector-2M-out"); + Assert.That (refObj, Is.EqualTo (dummyObj), "Selector-2M-ref"); + Assert.That (outObj, Is.Null, "Selector-2M-out"); // direct native refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual ((IntPtr) dummyObj.Handle, refValue, "Selector-2DA-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "Selector-2DA-out"); + Assert.That (refValue, Is.EqualTo ((IntPtr) dummyObj.Handle), "Selector-2DA-ref"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "Selector-2DA-out"); // direct managed refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual ((IntPtr) dummyObj.Handle, refValue, "Selector-2DM-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "Selector-2DM-out"); + Assert.That (refValue, Is.EqualTo ((IntPtr) dummyObj.Handle), "Selector-2DM-ref"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "Selector-2DM-out"); /// 3 set both parameteres to the same selector @@ -3909,31 +3908,31 @@ public void RefOutTest_Sel () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.AreEqual (Selector.GetHandle ("testSelector"), (IntPtr) refObj.Handle, "Selector-3A-ref"); - Assert.AreEqual (Selector.GetHandle ("testSelector"), (IntPtr) outObj.Handle, "Selector-3A-out"); + Assert.That ((IntPtr) refObj.Handle, Is.EqualTo (Selector.GetHandle ("testSelector")), "Selector-3A-ref"); + Assert.That ((IntPtr) outObj.Handle, Is.EqualTo (Selector.GetHandle ("testSelector")), "Selector-3A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.AreEqual (Selector.GetHandle ("testManagedSelector"), (IntPtr) refObj.Handle, "Selector-3M-ref"); - Assert.AreEqual (Selector.GetHandle ("testManagedSelector"), (IntPtr) outObj.Handle, "Selector-3M-out"); + Assert.That ((IntPtr) refObj.Handle, Is.EqualTo (Selector.GetHandle ("testManagedSelector")), "Selector-3M-ref"); + Assert.That ((IntPtr) outObj.Handle, Is.EqualTo (Selector.GetHandle ("testManagedSelector")), "Selector-3M-out"); // direct native refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (refValue, outValue, "Selector-3DA-eq"); // The managed roundtrip means 'outValue' is re-created (because it's nulled out upon entering managed code), but because selectors are unique, we get back the same pointer. - Assert.AreEqual (Selector.GetHandle ("testSelector"), refValue, "Selector-3DA-ref"); - Assert.AreEqual (Selector.GetHandle ("testSelector"), outValue, "Selector-3DA-out"); + Assert.That (outValue, Is.EqualTo (refValue), "Selector-3DA-eq"); // The managed roundtrip means 'outValue' is re-created (because it's nulled out upon entering managed code), but because selectors are unique, we get back the same pointer. + Assert.That (refValue, Is.EqualTo (Selector.GetHandle ("testSelector")), "Selector-3DA-ref"); + Assert.That (outValue, Is.EqualTo (Selector.GetHandle ("testSelector")), "Selector-3DA-out"); // direct managed refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (refValue, outValue, "Selector-3DM-eq"); // The managed roundtrip means 'outValue' is re-created (because it's nulled out upon entering managed code), but because selectors are unique, we get back the same pointer. - Assert.AreEqual (Selector.GetHandle ("testManagedSelector"), refValue, "Selector-3DM-ref"); - Assert.AreEqual (Selector.GetHandle ("testManagedSelector"), outValue, "Selector-3DM-out"); + Assert.That (outValue, Is.EqualTo (refValue), "Selector-3DM-eq"); // The managed roundtrip means 'outValue' is re-created (because it's nulled out upon entering managed code), but because selectors are unique, we get back the same pointer. + Assert.That (refValue, Is.EqualTo (Selector.GetHandle ("testManagedSelector")), "Selector-3DM-ref"); + Assert.That (outValue, Is.EqualTo (Selector.GetHandle ("testManagedSelector")), "Selector-3DM-out"); /// 4 set both parameteres to different selectors @@ -3943,29 +3942,29 @@ public void RefOutTest_Sel () refObj = null; // set to null outObj = null; // set to null test (action << 0, ref refObj, out outObj); - Assert.AreEqual (Selector.GetHandle ("testSelector:a:"), (IntPtr) refObj.Handle, "Selector-4A-ref-value"); - Assert.AreEqual (Selector.GetHandle ("testSelector:b:"), (IntPtr) outObj.Handle, "Selector-4A-out-value"); + Assert.That ((IntPtr) refObj.Handle, Is.EqualTo (Selector.GetHandle ("testSelector:a:")), "Selector-4A-ref-value"); + Assert.That ((IntPtr) outObj.Handle, Is.EqualTo (Selector.GetHandle ("testSelector:b:")), "Selector-4A-out-value"); // managed refObj = null; // set to null outObj = null; // set to null test (action << 8, ref refObj, out outObj); - Assert.AreEqual (Selector.GetHandle ("testManagedSelectorA"), (IntPtr) refObj.Handle, "Selector-4M-ref-value"); - Assert.AreEqual (Selector.GetHandle ("testManagedSelectorB"), (IntPtr) outObj.Handle, "Selector-4M-out-value"); + Assert.That ((IntPtr) refObj.Handle, Is.EqualTo (Selector.GetHandle ("testManagedSelectorA")), "Selector-4M-ref-value"); + Assert.That ((IntPtr) outObj.Handle, Is.EqualTo (Selector.GetHandle ("testManagedSelectorB")), "Selector-4M-out-value"); // direct native refValue = IntPtr.Zero; // set to null outValue = IntPtr.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (Selector.GetHandle ("testSelector:a:"), refValue, "Selector-4DA-ref-value"); - Assert.AreEqual (Selector.GetHandle ("testSelector:b:"), outValue, "Selector-4DA-out-value"); + Assert.That (refValue, Is.EqualTo (Selector.GetHandle ("testSelector:a:")), "Selector-4DA-ref-value"); + Assert.That (outValue, Is.EqualTo (Selector.GetHandle ("testSelector:b:")), "Selector-4DA-out-value"); // direct managed refValue = IntPtr.Zero; // set to null outValue = IntPtr.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (Selector.GetHandle ("testManagedSelectorA"), refValue, "Selector-4DM-ref-value"); - Assert.AreEqual (Selector.GetHandle ("testManagedSelectorB"), outValue, "Selector-4DM-out-value"); + Assert.That (refValue, Is.EqualTo (Selector.GetHandle ("testManagedSelectorA")), "Selector-4DM-ref-value"); + Assert.That (outValue, Is.EqualTo (Selector.GetHandle ("testManagedSelectorB")), "Selector-4DM-out-value"); } } @@ -3991,29 +3990,29 @@ public void RefOutTest_Class () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.IsNull (refObj, "Class-1A-ref"); - Assert.IsNull (outObj, "Class-1A-out"); + Assert.That (refObj, Is.Null, "Class-1A-ref"); + Assert.That (outObj, Is.Null, "Class-1A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.IsNull (refObj, "Class-1M-ref"); - Assert.IsNull (outObj, "Class-1M-out"); + Assert.That (refObj, Is.Null, "Class-1M-ref"); + Assert.That (outObj, Is.Null, "Class-1M-out"); // direct native refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "Class-1DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "Class-1DA-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "Class-1DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "Class-1DA-out"); // direct managed refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "Class-1DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "Class-1DM-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "Class-1DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "Class-1DM-out"); /// 2: verify that refValue points to something action = 2; @@ -4022,29 +4021,29 @@ public void RefOutTest_Class () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.AreEqual (dummyObj, refObj, "Class-2A-ref"); - Assert.IsNull (outObj, "Class-2A-out"); + Assert.That (refObj, Is.EqualTo (dummyObj), "Class-2A-ref"); + Assert.That (outObj, Is.Null, "Class-2A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.AreEqual (dummyObj, refObj, "Class-2M-ref"); - Assert.IsNull (outObj, "Class-2M-out"); + Assert.That (refObj, Is.EqualTo (dummyObj), "Class-2M-ref"); + Assert.That (outObj, Is.Null, "Class-2M-out"); // direct native refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (dummyObj.Handle, refValue, "Class-2DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "Class-2DA-out"); + Assert.That (refValue, Is.EqualTo (dummyObj.Handle), "Class-2DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "Class-2DA-out"); // direct managed refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (dummyObj.Handle, refValue, "Class-2DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "Class-2DM-out"); + Assert.That (refValue, Is.EqualTo (dummyObj.Handle), "Class-2DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "Class-2DM-out"); /// 3 set both parameteres to the same Class @@ -4054,31 +4053,31 @@ public void RefOutTest_Class () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.AreEqual (Class.GetHandle ("NSString"), refObj.Handle, "Class-3A-ref"); - Assert.AreEqual (Class.GetHandle ("NSString"), outObj.Handle, "Class-3A-out"); + Assert.That (refObj.Handle, Is.EqualTo (Class.GetHandle ("NSString")), "Class-3A-ref"); + Assert.That (outObj.Handle, Is.EqualTo (Class.GetHandle ("NSString")), "Class-3A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.AreEqual (Class.GetHandle (typeof (SomeConsumer)), refObj.Handle, "Class-3M-ref"); - Assert.AreEqual (Class.GetHandle (typeof (SomeConsumer)), outObj.Handle, "Class-3M-out"); + Assert.That (refObj.Handle, Is.EqualTo (Class.GetHandle (typeof (SomeConsumer))), "Class-3M-ref"); + Assert.That (outObj.Handle, Is.EqualTo (Class.GetHandle (typeof (SomeConsumer))), "Class-3M-out"); // direct native refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (refValue, outValue, "String-3DA-eq"); // The managed roundtrip means 'outValue' is re-created (because it's nulled out upon entering managed code), but since Class instances are singletons, we get back the same value. - Assert.AreEqual (Class.GetHandle ("NSString"), refValue, "Class-3DA-ref"); - Assert.AreEqual (Class.GetHandle ("NSString"), outValue, "Class-3DA-out"); + Assert.That (outValue, Is.EqualTo (refValue), "String-3DA-eq"); // The managed roundtrip means 'outValue' is re-created (because it's nulled out upon entering managed code), but since Class instances are singletons, we get back the same value. + Assert.That (refValue, Is.EqualTo (Class.GetHandle ("NSString")), "Class-3DA-ref"); + Assert.That (outValue, Is.EqualTo (Class.GetHandle ("NSString")), "Class-3DA-out"); // direct managed refValue = dummyObjHandle; // set to non-null outValue = dummyObjHandle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (refValue, outValue, "Class-3DM-eq"); // The managed roundtrip means 'outValue' is re-created (because it's nulled out upon entering managed code), but since Class instances are singletons, we get back the same value. - Assert.AreEqual (Class.GetHandle (typeof (SomeConsumer)), refValue, "Class-3DM-ref"); - Assert.AreEqual (Class.GetHandle (typeof (SomeConsumer)), outValue, "Class-3DM-out"); + Assert.That (outValue, Is.EqualTo (refValue), "Class-3DM-eq"); // The managed roundtrip means 'outValue' is re-created (because it's nulled out upon entering managed code), but since Class instances are singletons, we get back the same value. + Assert.That (refValue, Is.EqualTo (Class.GetHandle (typeof (SomeConsumer))), "Class-3DM-ref"); + Assert.That (outValue, Is.EqualTo (Class.GetHandle (typeof (SomeConsumer))), "Class-3DM-out"); /// 4 set both parameteres to different Classes @@ -4088,29 +4087,29 @@ public void RefOutTest_Class () refObj = null; // set to null outObj = null; // set to null test (action << 0, ref refObj, out outObj); - Assert.AreEqual (Class.GetHandle ("NSBundle"), refObj.Handle, "Class-4A-ref-value"); - Assert.AreEqual (Class.GetHandle ("NSDate"), outObj.Handle, "Class-4A-out-value"); + Assert.That (refObj.Handle, Is.EqualTo (Class.GetHandle ("NSBundle")), "Class-4A-ref-value"); + Assert.That (outObj.Handle, Is.EqualTo (Class.GetHandle ("NSDate")), "Class-4A-out-value"); // managed refObj = null; // set to null outObj = null; // set to null test (action << 8, ref refObj, out outObj); - Assert.AreEqual (Class.GetHandle (typeof (RefOutParametersSubclass)), refObj.Handle, "Class-4M-ref-value"); - Assert.AreEqual (Class.GetHandle ("RefOutParameters"), outObj.Handle, "Class-4M-out-value"); + Assert.That (refObj.Handle, Is.EqualTo (Class.GetHandle (typeof (RefOutParametersSubclass))), "Class-4M-ref-value"); + Assert.That (outObj.Handle, Is.EqualTo (Class.GetHandle ("RefOutParameters")), "Class-4M-out-value"); // direct native refValue = IntPtr.Zero; // set to null outValue = IntPtr.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (Class.GetHandle ("NSBundle"), refValue, "Class-4DA-ref-value"); - Assert.AreEqual (Class.GetHandle ("NSDate"), outValue, "Class-4DA-out-value"); + Assert.That (refValue, Is.EqualTo (Class.GetHandle ("NSBundle")), "Class-4DA-ref-value"); + Assert.That (outValue, Is.EqualTo (Class.GetHandle ("NSDate")), "Class-4DA-out-value"); // direct managed refValue = IntPtr.Zero; // set to null outValue = IntPtr.Zero; // set to null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (Class.GetHandle (typeof (RefOutParametersSubclass)), refValue, "Class-4DM-ref-value"); - Assert.AreEqual (Class.GetHandle ("RefOutParameters"), outValue, "Class-4DM-out-value"); + Assert.That (refValue, Is.EqualTo (Class.GetHandle (typeof (RefOutParametersSubclass))), "Class-4DM-ref-value"); + Assert.That (outValue, Is.EqualTo (Class.GetHandle ("RefOutParameters")), "Class-4DM-out-value"); } } @@ -4119,10 +4118,10 @@ void AssertAreEqual (INativeObject [] expected, INativeObject [] actual, string if (expected is null && actual is null) return; if (expected is null ^ actual is null) - Assert.Fail ("One is null and the other is not. Expected: {0} Actual: {1}. " + msg, expected, actual); - Assert.AreEqual (expected.Length, actual.Length, "Length." + msg); + Assert.Fail ($"One is null and the other is not. Expected: {expected} Actual: {actual}. " + msg); + Assert.That (actual.Length, Is.EqualTo (expected.Length), "Length." + msg); for (int i = 0; i < expected.Length; i++) { - Assert.AreEqual (expected [i].Handle, actual [i].Handle, $"Index #{i}: {msg}"); + Assert.That (actual [i].Handle, Is.EqualTo (expected [i].Handle), $"Index #{i}: {msg}"); } } @@ -4163,29 +4162,29 @@ public unsafe void RefOutTest_INSCodingArray () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.IsNull (refObj, "NSCodingArray-1A-ref"); - Assert.IsNull (outObj, "NSCodingArray-1A-out"); + Assert.That (refObj, Is.Null, "NSCodingArray-1A-ref"); + Assert.That (outObj, Is.Null, "NSCodingArray-1A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.IsNull (refObj, "NSCodingArray-1M-ref"); - Assert.IsNull (outObj, "NSCodingArray-1M-out"); + Assert.That (refObj, Is.Null, "NSCodingArray-1M-ref"); + Assert.That (outObj, Is.Null, "NSCodingArray-1M-out"); // direct native refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (IntPtr.Zero, refValue, "NSCodingArray-1DA-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "NSCodingArray-1DA-out"); + Assert.That (refValue, Is.EqualTo (IntPtr.Zero), "NSCodingArray-1DA-ref"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "NSCodingArray-1DA-out"); // direct managed refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (IntPtr.Zero, refValue, "NSCodingArray-1DM-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "NSCodingArray-1DM-out"); + Assert.That (refValue, Is.EqualTo (IntPtr.Zero), "NSCodingArray-1DM-ref"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "NSCodingArray-1DM-out"); /// 2: verify that refValue points to something action = 2; @@ -4195,30 +4194,30 @@ public unsafe void RefOutTest_INSCodingArray () outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); AssertAreEqual (dummyObj, refObj, "NSCodingArray-2A-ref"); - Assert.AreSame (dummyObj, refObj, "NSCodingArray-2A-ref-same"); - Assert.IsNull (outObj, "NSCodingArray-2A-out"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSCodingArray-2A-ref-same"); + Assert.That (outObj, Is.Null, "NSCodingArray-2A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); AssertAreEqual (dummyObj, refObj, "NSCodingArray-2M-ref"); - Assert.AreSame (dummyObj, refObj, "NSCodingArray-2M-ref-same"); - Assert.IsNull (outObj, "NSCodingArray-2M-out"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSCodingArray-2M-ref-same"); + Assert.That (outObj, Is.Null, "NSCodingArray-2M-out"); // direct native refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); AssertAreEqual (dummyObj, NSArray.ArrayFromHandle (refValue), "NSCodingArray-2DA-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "NSCodingArray-2DA-out"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "NSCodingArray-2DA-out"); // direct managed refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); AssertAreEqual (dummyObj, NSArray.ArrayFromHandle (refValue), "NSCodingArray-2DM-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "NSCodingArray-2DM-out"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "NSCodingArray-2DM-out"); /// 3 set both parameters to the same pointer of an NSCodingArray array @@ -4228,10 +4227,10 @@ public unsafe void RefOutTest_INSCodingArray () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.AreNotSame (dummyObj, refObj, "NSCodingArray-3A-ref-same"); - Assert.AreNotSame (dummyObj, outObj, "NSCodingArray-3A-ref-out"); + Assert.That (refObj, Is.Not.SameAs (dummyObj), "NSCodingArray-3A-ref-same"); + Assert.That (outObj, Is.Not.SameAs (dummyObj), "NSCodingArray-3A-ref-out"); AssertAreEqual (refObj, outObj, "NSCodingArray-3A-out-ref-eq"); - Assert.AreNotSame (refObj, outObj, "NSCodingArray-3A-ref-out-not-safe"); + Assert.That (outObj, Is.Not.SameAs (refObj), "NSCodingArray-3A-ref-out-not-safe"); Assert.That (refObj [0].GetType ().FullName, Does.Contain ("CodingWrapper"), "NSCodingArray-3A-ref-wrapper-type"); Assert.That (outObj [0].GetType ().FullName, Does.Contain ("CodingWrapper"), "NSCodingArray-3A-ref-wrapper-type"); @@ -4239,8 +4238,8 @@ public unsafe void RefOutTest_INSCodingArray () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.AreNotSame (dummyObj, refObj, "NSCodingArray-3M-ref-same"); - Assert.AreNotSame (dummyObj, outObj, "NSCodingArray-3M-ref-out"); + Assert.That (refObj, Is.Not.SameAs (dummyObj), "NSCodingArray-3M-ref-same"); + Assert.That (outObj, Is.Not.SameAs (dummyObj), "NSCodingArray-3M-ref-out"); AssertAreEqual (refObj, outObj, "NSCodingArray-3M-ref-out-not-safe"); Assert.That (refObj [0], Is.TypeOf (), "NSCodingArray-3M-ref-wrapper-type"); Assert.That (outObj [0], Is.TypeOf (), "NSCodingArray-3M-ref-wrapper-type"); @@ -4249,7 +4248,7 @@ public unsafe void RefOutTest_INSCodingArray () refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreNotSame (refValue, outValue, "NSCodingArray-3DA-out-ref-not-same"); + Assert.That (outValue, Is.Not.SameAs (refValue), "NSCodingArray-3DA-out-ref-not-same"); AssertAreEqual (refObj, outObj, "NSCodingArray-3DA-out-ref-equal"); Assert.That (refObj [0], Is.TypeOf (), "NSCodingArray-3DA-ref-wrapper-type"); Assert.That (outObj [0], Is.TypeOf (), "NSCodingArray-3DA-ref-wrapper-type"); @@ -4258,7 +4257,7 @@ public unsafe void RefOutTest_INSCodingArray () refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreNotSame (refValue, outValue, "NSCodingArray-3DM-out-ref-not-same"); + Assert.That (outValue, Is.Not.SameAs (refValue), "NSCodingArray-3DM-out-ref-not-same"); AssertAreEqual (refObj, outObj, "NSCodingArray-3DM-out-ref-equal"); Assert.That (refObj [0], Is.TypeOf (), "NSCodingArray-3DM-ref-wrapper-type"); Assert.That (outObj [0], Is.TypeOf (), "NSCodingArray-3DM-ref-wrapper-type"); @@ -4271,8 +4270,8 @@ public unsafe void RefOutTest_INSCodingArray () refObj = null; // set to null outObj = null; // set to null test (action << 0, ref refObj, out outObj); - Assert.IsNotNull (refObj, "NSCodingArray-4A-ref"); - Assert.IsNotNull (outObj, "NSCodingArray-4A-out"); + Assert.That (refObj, Is.Not.Null, "NSCodingArray-4A-ref"); + Assert.That (outObj, Is.Not.Null, "NSCodingArray-4A-out"); AssertAreNotEqual (refObj, outObj, "NSCodingArray-4A-ref-distinct"); Assert.That (refObj [0].GetType ().FullName, Does.Contain ("NSNumber").Or.Contain ("CodingWrapper"), "NSCodingArray-4A-ref-wrapper-type"); Assert.That (outObj [0].GetType ().FullName, Does.Contain ("NSNumber").Or.Contain ("CodingWrapper"), "NSCodingArray-4A-ref-wrapper-type"); @@ -4327,29 +4326,29 @@ public unsafe void RefOutTest_NSObjectArray () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.IsNull (refObj, "NSObjectArray-1A-ref"); - Assert.IsNull (outObj, "NSObjectArray-1A-out"); + Assert.That (refObj, Is.Null, "NSObjectArray-1A-ref"); + Assert.That (outObj, Is.Null, "NSObjectArray-1A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.IsNull (refObj, "NSObjectArray-1M-ref"); - Assert.IsNull (outObj, "NSObjectArray-1M-out"); + Assert.That (refObj, Is.Null, "NSObjectArray-1M-ref"); + Assert.That (outObj, Is.Null, "NSObjectArray-1M-out"); // direct native refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (IntPtr.Zero, refValue, "NSObjectArray-1DA-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "NSObjectArray-1DA-out"); + Assert.That (refValue, Is.EqualTo (IntPtr.Zero), "NSObjectArray-1DA-ref"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "NSObjectArray-1DA-out"); // direct managed refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (IntPtr.Zero, refValue, "NSObjectArray-1DM-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "NSObjectArray-1DM-out"); + Assert.That (refValue, Is.EqualTo (IntPtr.Zero), "NSObjectArray-1DM-ref"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "NSObjectArray-1DM-out"); /// 2: verify that refValue points to something action = 2; @@ -4359,30 +4358,30 @@ public unsafe void RefOutTest_NSObjectArray () outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); AssertAreEqual (dummyObj, refObj, "NSObjectArray-2A-ref"); - Assert.AreSame (dummyObj, refObj, "NSObjectArray-2A-ref-same"); - Assert.IsNull (outObj, "NSObjectArray-2A-out"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSObjectArray-2A-ref-same"); + Assert.That (outObj, Is.Null, "NSObjectArray-2A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); AssertAreEqual (dummyObj, refObj, "NSObjectArray-2M-ref"); - Assert.AreSame (dummyObj, refObj, "NSObjectArray-2M-ref-same"); - Assert.IsNull (outObj, "NSObjectArray-2M-out"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSObjectArray-2M-ref-same"); + Assert.That (outObj, Is.Null, "NSObjectArray-2M-out"); // direct native refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); AssertAreEqual (dummyObj, NSArray.ArrayFromHandle (refValue), "NSObjectArray-2DA-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "NSObjectArray-2DA-out"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "NSObjectArray-2DA-out"); // direct managed refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); AssertAreEqual (dummyObj, NSArray.ArrayFromHandle (refValue), "NSObjectArray-2DM-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "NSObjectArray-2DM-out"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "NSObjectArray-2DM-out"); /// 3 set both parameters to the same pointer of an NSObjectArray array @@ -4392,10 +4391,10 @@ public unsafe void RefOutTest_NSObjectArray () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.AreNotSame (dummyObj, refObj, "NSObjectArray-3A-ref-same"); - Assert.AreNotSame (dummyObj, outObj, "NSObjectArray-3A-ref-out"); + Assert.That (refObj, Is.Not.SameAs (dummyObj), "NSObjectArray-3A-ref-same"); + Assert.That (outObj, Is.Not.SameAs (dummyObj), "NSObjectArray-3A-ref-out"); AssertAreEqual (refObj, outObj, "NSObjectArray-3A-out-ref-eq"); - Assert.AreNotSame (refObj, outObj, "NSObjectArray-3A-ref-out-not-safe"); + Assert.That (outObj, Is.Not.SameAs (refObj), "NSObjectArray-3A-ref-out-not-safe"); Assert.That (refObj, Is.EquivalentTo (new NSObject [] { (NSString) "Hello", (NSString) "World" }), "NSObjectArray-3A-ref-equiv"); Assert.That (outObj, Is.EquivalentTo (new NSObject [] { (NSString) "Hello", (NSString) "World" }), "NSObjectArray-3A-obj-equiv"); @@ -4403,8 +4402,8 @@ public unsafe void RefOutTest_NSObjectArray () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.AreNotSame (dummyObj, refObj, "NSObjectArray-3M-ref-same"); - Assert.AreNotSame (dummyObj, outObj, "NSObjectArray-3M-ref-out"); + Assert.That (refObj, Is.Not.SameAs (dummyObj), "NSObjectArray-3M-ref-same"); + Assert.That (outObj, Is.Not.SameAs (dummyObj), "NSObjectArray-3M-ref-out"); AssertAreEqual (refObj, outObj, "NSObjectArray-3M-ref-out-not-safe"); Assert.That (refObj, Is.EquivalentTo (new NSObject [] { (NSString) "Hello", (NSString) "World", (NSString) "from", (NSString) "managed" }), "NSObjectArray-3M-ref-equiv"); Assert.That (outObj, Is.EquivalentTo (new NSObject [] { (NSString) "Hello", (NSString) "World", (NSString) "from", (NSString) "managed" }), "NSObjectArray-3M-obj-equiv"); @@ -4413,7 +4412,7 @@ public unsafe void RefOutTest_NSObjectArray () refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreNotEqual (refValue, outValue, "NSObjectArray-3DA-out-ref-not-same"); + Assert.That (outValue, Is.Not.EqualTo (refValue), "NSObjectArray-3DA-out-ref-not-same"); refObj = NSArray.ArrayFromHandle (refValue); outObj = NSArray.ArrayFromHandle (outValue); Assert.That (refObj, Is.EquivalentTo (new NSObject [] { (NSString) "Hello", (NSString) "World" }), "NSObjectArray-3DA-ref-equiv"); @@ -4423,7 +4422,7 @@ public unsafe void RefOutTest_NSObjectArray () refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreNotEqual (refValue, outValue, "NSObjectArray-3DM-out-ref-not-same"); + Assert.That (outValue, Is.Not.EqualTo (refValue), "NSObjectArray-3DM-out-ref-not-same"); refObj = NSArray.ArrayFromHandle (refValue); outObj = NSArray.ArrayFromHandle (outValue); Assert.That (refObj, Is.EquivalentTo (new NSObject [] { (NSString) "Hello", (NSString) "World", (NSString) "from", (NSString) "managed" }), "NSObjectArray-3DM-ref-equiv"); @@ -4490,29 +4489,29 @@ public unsafe void RefOutTest_NSValueArray () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.IsNull (refObj, "NSValueArray-1A-ref"); - Assert.IsNull (outObj, "NSValueArray-1A-out"); + Assert.That (refObj, Is.Null, "NSValueArray-1A-ref"); + Assert.That (outObj, Is.Null, "NSValueArray-1A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.IsNull (refObj, "NSValueArray-1M-ref"); - Assert.IsNull (outObj, "NSValueArray-1M-out"); + Assert.That (refObj, Is.Null, "NSValueArray-1M-ref"); + Assert.That (outObj, Is.Null, "NSValueArray-1M-out"); // direct native refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (IntPtr.Zero, refValue, "NSValueArray-1DA-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "NSValueArray-1DA-out"); + Assert.That (refValue, Is.EqualTo (IntPtr.Zero), "NSValueArray-1DA-ref"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "NSValueArray-1DA-out"); // direct managed refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (IntPtr.Zero, refValue, "NSValueArray-1DM-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "NSValueArray-1DM-out"); + Assert.That (refValue, Is.EqualTo (IntPtr.Zero), "NSValueArray-1DM-ref"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "NSValueArray-1DM-out"); /// 2: verify that refValue points to something action = 2; @@ -4522,30 +4521,30 @@ public unsafe void RefOutTest_NSValueArray () outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); AssertAreEqual (dummyObj, refObj, "NSValueArray-2A-ref"); - Assert.AreSame (dummyObj, refObj, "NSValueArray-2A-ref-same"); - Assert.IsNull (outObj, "NSValueArray-2A-out"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSValueArray-2A-ref-same"); + Assert.That (outObj, Is.Null, "NSValueArray-2A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); AssertAreEqual (dummyObj, refObj, "NSValueArray-2M-ref"); - Assert.AreSame (dummyObj, refObj, "NSValueArray-2M-ref-same"); - Assert.IsNull (outObj, "NSValueArray-2M-out"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSValueArray-2M-ref-same"); + Assert.That (outObj, Is.Null, "NSValueArray-2M-out"); // direct native refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); AssertAreEqual (dummyObj, NSArray.ArrayFromHandle (refValue), "NSValueArray-2DA-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "NSValueArray-2DA-out"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "NSValueArray-2DA-out"); // direct managed refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); AssertAreEqual (dummyObj, NSArray.ArrayFromHandle (refValue), "NSValueArray-2DM-ref"); - Assert.AreEqual (IntPtr.Zero, outValue, "NSValueArray-2DM-out"); + Assert.That (outValue, Is.EqualTo (IntPtr.Zero), "NSValueArray-2DM-out"); /// 3 set both parameters to the same pointer of an NSValueArray array @@ -4555,10 +4554,10 @@ public unsafe void RefOutTest_NSValueArray () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.AreNotSame (dummyObj, refObj, "NSValueArray-3A-ref-same"); - Assert.AreNotSame (dummyObj, outObj, "NSValueArray-3A-ref-out"); + Assert.That (refObj, Is.Not.SameAs (dummyObj), "NSValueArray-3A-ref-same"); + Assert.That (outObj, Is.Not.SameAs (dummyObj), "NSValueArray-3A-ref-out"); AssertAreEqual (refObj, outObj, "NSValueArray-3A-out-ref-eq"); - Assert.AreNotSame (refObj, outObj, "NSValueArray-3A-ref-out-not-safe"); + Assert.That (outObj, Is.Not.SameAs (refObj), "NSValueArray-3A-ref-out-not-safe"); Assert.That (refObj [0], Is.TypeOf (), "NSValueArray-3A-ref-wrapper-type"); Assert.That (outObj [0], Is.TypeOf (), "NSValueArray-3A-ref-wrapper-type"); @@ -4566,8 +4565,8 @@ public unsafe void RefOutTest_NSValueArray () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.AreNotSame (dummyObj, refObj, "NSValueArray-3M-ref-same"); - Assert.AreNotSame (dummyObj, outObj, "NSValueArray-3M-ref-out"); + Assert.That (refObj, Is.Not.SameAs (dummyObj), "NSValueArray-3M-ref-same"); + Assert.That (outObj, Is.Not.SameAs (dummyObj), "NSValueArray-3M-ref-out"); AssertAreEqual (refObj, outObj, "NSValueArray-3M-ref-out-not-safe"); Assert.That (refObj [0], Is.TypeOf (), "NSValueArray-3M-ref-wrapper-type"); Assert.That (outObj [0], Is.TypeOf (), "NSValueArray-3M-ref-wrapper-type"); @@ -4576,7 +4575,7 @@ public unsafe void RefOutTest_NSValueArray () refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreNotSame (refValue, outValue, "NSValueArray-3DA-out-ref-not-same"); + Assert.That (outValue, Is.Not.SameAs (refValue), "NSValueArray-3DA-out-ref-not-same"); AssertAreEqual (refObj, outObj, "NSValueArray-3DA-out-ref-equal"); Assert.That (refObj [0], Is.TypeOf (), "NSValueArray-3DA-ref-wrapper-type"); Assert.That (outObj [0], Is.TypeOf (), "NSValueArray-3DA-ref-wrapper-type"); @@ -4585,7 +4584,7 @@ public unsafe void RefOutTest_NSValueArray () refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreNotSame (refValue, outValue, "NSValueArray-3DM-out-ref-not-same"); + Assert.That (outValue, Is.Not.SameAs (refValue), "NSValueArray-3DM-out-ref-not-same"); AssertAreEqual (refObj, outObj, "NSValueArray-3DM-out-ref-equal"); Assert.That (refObj [0], Is.TypeOf (), "NSValueArray-3DM-ref-wrapper-type"); Assert.That (outObj [0], Is.TypeOf (), "NSValueArray-3DM-ref-wrapper-type"); @@ -4598,8 +4597,8 @@ public unsafe void RefOutTest_NSValueArray () refObj = null; // set to null outObj = null; // set to null test (action << 0, ref refObj, out outObj); - Assert.IsNotNull (refObj, "NSValueArray-4A-ref"); - Assert.IsNotNull (outObj, "NSValueArray-4A-out"); + Assert.That (refObj, Is.Not.Null, "NSValueArray-4A-ref"); + Assert.That (outObj, Is.Not.Null, "NSValueArray-4A-out"); AssertAreNotEqual (refObj, outObj, "NSValueArray-4A-ref-distinct"); Assert.That (refObj [0], Is.TypeOf (), "NSValueArray-4A-ref-wrapper-type"); Assert.That (outObj [0], Is.TypeOf (), "NSValueArray-4A-ref-wrapper-type"); @@ -4652,29 +4651,29 @@ public unsafe void RefOutTest_StringArray () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.IsNull (refObj, "NSStringArray-1A-ref"); - Assert.IsNull (outObj, "NSStringArray-1A-out"); + Assert.That (refObj, Is.Null, "NSStringArray-1A-ref"); + Assert.That (outObj, Is.Null, "NSStringArray-1A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.IsNull (refObj, "NSStringArray-1M-ref"); - Assert.IsNull (outObj, "NSStringArray-1M-out"); + Assert.That (refObj, Is.Null, "NSStringArray-1M-ref"); + Assert.That (outObj, Is.Null, "NSStringArray-1M-out"); // direct native refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "NSStringArray-1DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSStringArray-1DA-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "NSStringArray-1DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSStringArray-1DA-out"); // direct managed refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "NSStringArray-1DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSStringArray-1DM-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "NSStringArray-1DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSStringArray-1DM-out"); /// 2: verify that refValue points to something action = 2; @@ -4684,32 +4683,32 @@ public unsafe void RefOutTest_StringArray () outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); Assert.That (dummyObj, Is.EquivalentTo (refObj), "NSStringArray-2A-ref"); - Assert.AreSame (dummyObj, refObj, "NSStringArray-2A-ref-same"); - Assert.IsNull (outObj, "NSStringArray-2A-out"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSStringArray-2A-ref-same"); + Assert.That (outObj, Is.Null, "NSStringArray-2A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); Assert.That (dummyObj, Is.EquivalentTo (refObj), "NSStringArray-2M-ref"); - Assert.AreSame (dummyObj, refObj, "NSStringArray-2M-ref-same"); - Assert.IsNull (outObj, "NSStringArray-2M-out"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSStringArray-2M-ref-same"); + Assert.That (outObj, Is.Null, "NSStringArray-2M-out"); // direct native refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); Assert.That (dummyObj, Is.EquivalentTo (NSArray.StringArrayFromHandle (refValue)), "NSStringArray-2DA-ref"); - Assert.AreEqual (dummyArray.Handle, refValue, "NSStringArray-2DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSStringArray-2DA-out"); + Assert.That (refValue, Is.EqualTo (dummyArray.Handle), "NSStringArray-2DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSStringArray-2DA-out"); // direct managed refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); Assert.That (dummyObj, Is.EquivalentTo (NSArray.StringArrayFromHandle (refValue)), "NSStringArray-2DM-ref"); - Assert.AreEqual (dummyArray.Handle, refValue, "NSStringArray-2DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSStringArray-2DM-out"); + Assert.That (refValue, Is.EqualTo (dummyArray.Handle), "NSStringArray-2DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSStringArray-2DM-out"); /// 3 set both parameters to the same pointer of an NSStringArray array @@ -4755,8 +4754,8 @@ public unsafe void RefOutTest_StringArray () refObj = null; // set to null outObj = null; // set to null test (action << 0, ref refObj, out outObj); - Assert.IsNotNull (refObj, "NSStringArray-4A-ref"); - Assert.IsNotNull (outObj, "NSStringArray-4A-out"); + Assert.That (refObj, Is.Not.Null, "NSStringArray-4A-ref"); + Assert.That (outObj, Is.Not.Null, "NSStringArray-4A-out"); Assert.That (refObj, Is.EquivalentTo (new string [] { "Hello", "Microsoft" }), "NSStringArray-4A-ref-equiv"); Assert.That (outObj, Is.EquivalentTo (new string [] { "Hello", "Xamarin" }), "NSStringArray-4A-obj-equiv"); @@ -4837,29 +4836,29 @@ public unsafe void RefOutTest_ClassArray () refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); - Assert.IsNull (refObj, "NSClassArray-1A-ref"); - Assert.IsNull (outObj, "NSClassArray-1A-out"); + Assert.That (refObj, Is.Null, "NSClassArray-1A-ref"); + Assert.That (outObj, Is.Null, "NSClassArray-1A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); - Assert.IsNull (refObj, "NSClassArray-1M-ref"); - Assert.IsNull (outObj, "NSClassArray-1M-out"); + Assert.That (refObj, Is.Null, "NSClassArray-1M-ref"); + Assert.That (outObj, Is.Null, "NSClassArray-1M-out"); // direct native refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "NSClassArray-1DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSClassArray-1DA-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "NSClassArray-1DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSClassArray-1DA-out"); // direct managed refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); - Assert.AreEqual (NativeHandle.Zero, refValue, "NSClassArray-1DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSClassArray-1DM-out"); + Assert.That (refValue, Is.EqualTo (NativeHandle.Zero), "NSClassArray-1DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSClassArray-1DM-out"); /// 2: verify that refValue points to something action = 2; @@ -4869,32 +4868,32 @@ public unsafe void RefOutTest_ClassArray () outObj = dummyObj; // set to non-null test (action << 0, ref refObj, out outObj); Assert.That (dummyObj, Is.EquivalentTo (refObj), "NSClassArray-2A-ref"); - Assert.AreSame (dummyObj, refObj, "NSClassArray-2A-ref-same"); - Assert.IsNull (outObj, "NSClassArray-2A-out"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSClassArray-2A-ref-same"); + Assert.That (outObj, Is.Null, "NSClassArray-2A-out"); // managed refObj = dummyObj; // set to non-null outObj = dummyObj; // set to non-null test (action << 8, ref refObj, out outObj); Assert.That (dummyObj, Is.EquivalentTo (refObj), "NSClassArray-2M-ref"); - Assert.AreSame (dummyObj, refObj, "NSClassArray-2M-ref-same"); - Assert.IsNull (outObj, "NSClassArray-2M-out"); + Assert.That (refObj, Is.SameAs (dummyObj), "NSClassArray-2M-ref-same"); + Assert.That (outObj, Is.Null, "NSClassArray-2M-out"); // direct native refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 0, ref refValue, out outValue); Assert.That (dummyObj, Is.EquivalentTo (NSArray.ArrayFromHandle (refValue)), "NSClassArray-2DA-ref"); - Assert.AreEqual (dummyArray.Handle, refValue, "NSClassArray-2DA-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSClassArray-2DA-out"); + Assert.That (refValue, Is.EqualTo (dummyArray.Handle), "NSClassArray-2DA-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSClassArray-2DA-out"); // direct managed refValue = dummyArray.Handle; // set to non-null outValue = dummyArray.Handle; // set to non-null Messaging.void_objc_msgSend_int_IntPtr_IntPtr (obj.Handle, sel, action << 8, ref refValue, out outValue); Assert.That (dummyObj, Is.EquivalentTo (NSArray.ArrayFromHandle (refValue)), "NSClassArray-2DM-ref"); - Assert.AreEqual (dummyArray.Handle, refValue, "NSClassArray-2DM-ref"); - Assert.AreEqual (NativeHandle.Zero, outValue, "NSClassArray-2DM-out"); + Assert.That (refValue, Is.EqualTo (dummyArray.Handle), "NSClassArray-2DM-ref"); + Assert.That (outValue, Is.EqualTo (NativeHandle.Zero), "NSClassArray-2DM-out"); /// 3 set both parameters to the same pointer of an Class array @@ -4940,8 +4939,8 @@ public unsafe void RefOutTest_ClassArray () refObj = null; // set to null outObj = null; // set to null test (action << 0, ref refObj, out outObj); - Assert.IsNotNull (refObj, "NSClassArray-4A-ref"); - Assert.IsNotNull (outObj, "NSClassArray-4A-out"); + Assert.That (refObj, Is.Not.Null, "NSClassArray-4A-ref"); + Assert.That (outObj, Is.Not.Null, "NSClassArray-4A-out"); Assert.That (refObj, Is.EquivalentTo (new Class [] { new Class (typeof (NSString)), new Class (typeof (NSValue)) }), "NSClassArray-4A-ref-equiv"); Assert.That (outObj, Is.EquivalentTo (new Class [] { new Class (typeof (NSData)), new Class (typeof (NSDate)) }), "NSClassArray-4A-obj-equiv"); @@ -5010,13 +5009,13 @@ public void MethodEncodings () NSObject o5 = Runtime.GetNSObject (obj5); NSObject o6 = Runtime.GetNSObject (obj6); NSObject o7 = Runtime.GetNSObject (obj7); - Assert.IsNotNull (o1, "O1"); - Assert.IsNotNull (o2, "O2"); - Assert.IsNotNull (o3, "O3"); - Assert.IsNotNull (o4, "O4"); - Assert.IsNotNull (o5, "O5"); - Assert.IsNotNull (o6, "O6"); - Assert.IsNotNull (o7, "O7"); + Assert.That (o1, Is.Not.Null, "O1"); + Assert.That (o2, Is.Not.Null, "O2"); + Assert.That (o3, Is.Not.Null, "O3"); + Assert.That (o4, Is.Not.Null, "O4"); + Assert.That (o5, Is.Not.Null, "O5"); + Assert.That (o6, Is.Not.Null, "O6"); + Assert.That (o7, Is.Not.Null, "O7"); } } @@ -5031,7 +5030,7 @@ public void MethodEncodings2 () CGRect obj5 = new CGRect (1, 2, 3, 4); nint obj6 = 6; Messaging.void_objc_msgSend_IntPtr_IntPtr_IntPtr_IntPtr_CGRect_IntPtr (met.Handle, Selector.GetHandle ("setPtrPropertyCGRect:p2:p3:p4:p5:p6:"), obj1, obj2, obj3, obj4, ref obj5, obj6); - Assert.AreEqual (new CGRect (5, 6, 7, 8), obj5, "rv"); + Assert.That (obj5, Is.EqualTo (new CGRect (5, 6, 7, 8)), "rv"); } } @@ -5039,13 +5038,13 @@ class MethodEncodingsTests : NSObject, IObjCProtocolTest { [Export ("methodEncodings:obj2:obj3:obj4:obj5:obj6:obj7:")] public void GetMethodEncodings (ref NSObject obj1, ref NSObject obj2, ref NSObject obj3, ref NSObject obj4, ref NSObject obj5, ref NSObject obj6, ref NSObject obj7) { - Assert.IsNull (obj1, "obj1"); - Assert.IsNull (obj2, "obj2"); - Assert.IsNull (obj3, "obj3"); - Assert.IsNull (obj4, "obj4"); - Assert.IsNull (obj5, "obj5"); - Assert.IsNull (obj6, "obj6"); - Assert.IsNull (obj7, "obj7"); + Assert.That (obj1, Is.Null, "obj1"); + Assert.That (obj2, Is.Null, "obj2"); + Assert.That (obj3, Is.Null, "obj3"); + Assert.That (obj4, Is.Null, "obj4"); + Assert.That (obj5, Is.Null, "obj5"); + Assert.That (obj6, Is.Null, "obj6"); + Assert.That (obj7, Is.Null, "obj7"); obj1 = new NSObject (); obj2 = new NSObject (); obj3 = new NSObject (); @@ -5058,12 +5057,12 @@ public void GetMethodEncodings (ref NSObject obj1, ref NSObject obj2, ref NSObje [Export ("setPtrPropertyCGRect:p2:p3:p4:p5:p6:")] void SetPtrPropertyCGRect (nint p1, nint p2, nint p3, nint p4, ref global::CoreGraphics.CGRect p5, nint p6) { - Assert.AreEqual ((nint) 1, p1, "1"); - Assert.AreEqual ((nint) 2, p2, "2"); - Assert.AreEqual ((nint) 3, p3, "3"); - Assert.AreEqual ((nint) 4, p4, "4"); - Assert.AreEqual (new CGRect (1, 2, 3, 4), p5, "5a"); - Assert.AreEqual ((nint) 6, p6, "6"); + Assert.That (p1, Is.EqualTo ((nint) 1), "1"); + Assert.That (p2, Is.EqualTo ((nint) 2), "2"); + Assert.That (p3, Is.EqualTo ((nint) 3), "3"); + Assert.That (p4, Is.EqualTo ((nint) 4), "4"); + Assert.That (p5, Is.EqualTo (new CGRect (1, 2, 3, 4)), "5a"); + Assert.That (p6, Is.EqualTo ((nint) 6), "6"); p5 = new CGRect (5, 6, 7, 8); } @@ -5082,7 +5081,7 @@ public override void TestCFBundle (int action, ref CFBundle refValue, out CFBund outValue = null; break; case 2: // verify that refValue points to something - Assert.IsNotNull (refValue, "2"); + Assert.That (refValue, Is.Not.Null, "2"); outValue = null; // compiler-enforced break; case 3: // set both parameteres to the same pointer of a CFBundle @@ -5111,7 +5110,7 @@ public override void TestINSCoding (int action, ref INSCoding refValue, out INSC outValue = null; break; case 2: // verify that refValue points to something - Assert.IsNotNull (refValue, "2"); + Assert.That (refValue, Is.Not.Null, "2"); outValue = null; // compiler-enforced break; case 3: // set both parameteres to the same pointer of an NSString @@ -5140,7 +5139,7 @@ public override void TestNSObject (int action, ref NSObject refValue, out NSObje outValue = null; break; case 2: // verify that refValue points to something - Assert.IsNotNull (refValue, "2"); + Assert.That (refValue, Is.Not.Null, "2"); outValue = null; // compiler-enforced break; case 3: // set both parameteres to the same pointer of an NSObject @@ -5169,7 +5168,7 @@ public override void TestValue (int action, ref NSValue refValue, out NSValue ou outValue = null; break; case 2: // verify that refValue points to something - Assert.IsNotNull (refValue, "2"); + Assert.That (refValue, Is.Not.Null, "2"); outValue = null; // compiler-enforced break; case 3: // set both parameteres to the same pointer of an NSObject @@ -5198,7 +5197,7 @@ public override void TestString (int action, ref string refValue, out string out outValue = null; break; case 2: // verify that refValue points to something - Assert.IsNotNull (refValue, "2"); + Assert.That (refValue, Is.Not.Null, "2"); outValue = null; // compiler-enforced break; case 3: // set both parameteres to the same pointer of an NSObject @@ -5254,7 +5253,7 @@ public override void TestSelector (int action, ref Selector refValue, out Select outValue = null; break; case 2: // verify that refValue points to something - Assert.IsNotNull (refValue, "TestSelector: 2"); + Assert.That (refValue, Is.Not.Null, "TestSelector: 2"); outValue = null; break; case 3: // set both parameteres to the same value @@ -5283,7 +5282,7 @@ public override void TestClass (int action, ref Class refValue, out Class outVal outValue = null; break; case 2: // verify that refValue points to something - Assert.IsNotNull (refValue); + Assert.That (refValue, Is.Not.Null); outValue = null; break; case 3: // set both parameteres to the same value @@ -5312,7 +5311,7 @@ public override void TestINSCodingArray (int action, ref INSCoding [] refValue, outValue = null; break; case 2: // verify that refValue points to something - Assert.IsNotNull (refValue, "2"); + Assert.That (refValue, Is.Not.Null, "2"); outValue = null; // compiler-enforced break; case 3: // set both parameteres to the same pointer of an NSObject @@ -5341,7 +5340,7 @@ public override void TestNSObjectArray (int action, ref NSObject [] refValue, ou outValue = null; break; case 2: // verify that refValue points to something - Assert.IsNotNull (refValue, "2"); + Assert.That (refValue, Is.Not.Null, "2"); outValue = null; // compiler-enforced break; case 3: // set both parameteres to the same pointer of an NSObject @@ -5370,7 +5369,7 @@ public override void TestNSValueArray (int action, ref NSValue [] refValue, out outValue = null; break; case 2: // verify that refValue points to something - Assert.IsNotNull (refValue, "2"); + Assert.That (refValue, Is.Not.Null, "2"); outValue = null; // compiler-enforced break; case 3: // set both parameteres to the same pointer of an NSObject @@ -5399,7 +5398,7 @@ public override void TestStringArray (int action, ref string [] refValue, out st outValue = null; break; case 2: // verify that refValue points to something - Assert.IsNotNull (refValue, "2"); + Assert.That (refValue, Is.Not.Null, "2"); outValue = null; // compiler-enforced break; case 3: // set both parameteres to the same pointer of an NSObject @@ -5432,7 +5431,7 @@ public override void TestClassArray (int action, ref Class [] refValue, out Clas outValue = null; break; case 2: // verify that refValue points to something - Assert.IsNotNull (refValue, "2"); + Assert.That (refValue, Is.Not.Null, "2"); outValue = null; // compiler-enforced break; case 3: // set both parameteres to the same pointer of an NSObject @@ -5470,7 +5469,7 @@ public void GenericClassWithUnrelatedGenericDelegate () block.SetupBlock (tramp, handler); Messaging.void_objc_msgSend_IntPtr_IntPtr_BlockLiteral (obj.Handle, Selector.GetHandle ("webView:decidePolicyForNavigationAction:decisionHandler:"), IntPtr.Zero, IntPtr.Zero, ref block); block.CleanupBlock (); - Assert.IsTrue (handler_called, "Handler called"); + Assert.That (handler_called, Is.True, "Handler called"); } else { Assert.Throws (() => block.SetupBlock (tramp, handler)); } @@ -5507,25 +5506,25 @@ public void RefEnumValues () using (var obj = new UnderlyingEnumValues ()) { b = 0; sb = 0; s = 0; us = 0; i = 0; ui = 0; l = 0; ul = 0; Messaging.void_objc_msgSend_ref_byte_ref_sbyte_ref_short_ref_ushort_ref_int_ref_uint_ref_long_ref_ulong (obj.Handle, Selector.GetHandle ("ByRef:a:b:c:d:e:f:g:"), ref b, ref sb, ref s, ref us, ref i, ref ui, ref l, ref ul); - Assert.AreEqual (EnumB.b, b, "ref: B"); - Assert.AreEqual (EnumSB.b, sb, "ref: SB"); - Assert.AreEqual (EnumS.b, s, "ref: S"); - Assert.AreEqual (EnumUS.b, us, "ref: US"); - Assert.AreEqual (EnumI.b, i, "ref: I"); - Assert.AreEqual (EnumUI.b, ui, "ref: UI"); - Assert.AreEqual (EnumL.b, l, "ref: L"); - Assert.AreEqual (EnumUL.b, ul, "ref: UL"); + Assert.That (b, Is.EqualTo (EnumB.b), "ref: B"); + Assert.That (sb, Is.EqualTo (EnumSB.b), "ref: SB"); + Assert.That (s, Is.EqualTo (EnumS.b), "ref: S"); + Assert.That (us, Is.EqualTo (EnumUS.b), "ref: US"); + Assert.That (i, Is.EqualTo (EnumI.b), "ref: I"); + Assert.That (ui, Is.EqualTo (EnumUI.b), "ref: UI"); + Assert.That (l, Is.EqualTo (EnumL.b), "ref: L"); + Assert.That (ul, Is.EqualTo (EnumUL.b), "ref: UL"); b = 0; sb = 0; s = 0; us = 0; i = 0; ui = 0; l = 0; ul = 0; Messaging.void_objc_msgSend_out_byte_out_sbyte_out_short_out_ushort_out_int_out_uint_out_long_out_ulong (obj.Handle, Selector.GetHandle ("Out:a:b:c:d:e:f:g:"), out b, out sb, out s, out us, out i, out ui, out l, out ul); - Assert.AreEqual (EnumB.b, b, "out: B"); - Assert.AreEqual (EnumSB.b, sb, "out: SB"); - Assert.AreEqual (EnumS.b, s, "out: S"); - Assert.AreEqual (EnumUS.b, us, "out: US"); - Assert.AreEqual (EnumI.b, i, "out: I"); - Assert.AreEqual (EnumUI.b, ui, "out: UI"); - Assert.AreEqual (EnumL.b, l, "out: L"); - Assert.AreEqual (EnumUL.b, ul, "out: UL"); + Assert.That (b, Is.EqualTo (EnumB.b), "out: B"); + Assert.That (sb, Is.EqualTo (EnumSB.b), "out: SB"); + Assert.That (s, Is.EqualTo (EnumS.b), "out: S"); + Assert.That (us, Is.EqualTo (EnumUS.b), "out: US"); + Assert.That (i, Is.EqualTo (EnumI.b), "out: I"); + Assert.That (ui, Is.EqualTo (EnumUI.b), "out: UI"); + Assert.That (l, Is.EqualTo (EnumL.b), "out: L"); + Assert.That (ul, Is.EqualTo (EnumUL.b), "out: UL"); } } @@ -5551,9 +5550,9 @@ void AssertMemberCount (Type type) var expectNoMembers = false; #endif if (expectNoMembers) { - Assert.AreEqual (0, members.Length, $"All members should be trimmed away in {type.FullName}:\n\t{string.Join ("\n\t", members.Select (v => v.ToString ()))}"); + Assert.That (members.Length, Is.EqualTo (0), $"All members should be trimmed away in {type.FullName}:\n\t{string.Join ("\n\t", members.Select (v => v.ToString ()))}"); } else { - Assert.AreNotEqual (0, members.Length, $"All members should not be trimmed away in {type.FullName}"); + Assert.That (members.Length, Is.Not.EqualTo (0), $"All members should not be trimmed away in {type.FullName}"); } } @@ -5646,7 +5645,7 @@ public void WithoutUserDelegateTypeAttribute () Action del = (v) => { }; if (Runtime.DynamicRegistrationSupported) { block.SetupBlock (tramp, del); - Assert.AreEqual ("v@:^v^v", GetBlockSignature (block), "a"); + Assert.That (GetBlockSignature (block), Is.EqualTo ("v@:^v^v"), "a"); block.CleanupBlock (); } else { Assert.Throws (() => block.SetupBlock (tramp, del)); @@ -5661,7 +5660,7 @@ public void WithUserDelegateTypeAttribute () Action del = (v) => { }; if (Runtime.DynamicRegistrationSupported) { block.SetupBlock (tramp, del); - Assert.AreEqual ("v@?@", GetBlockSignature (block), "a"); + Assert.That (GetBlockSignature (block), Is.EqualTo ("v@?@"), "a"); block.CleanupBlock (); } else { // The linker is able to rewrite calls to BlockLiteral.SetupBlock to BlockLiteral.SetupBlockImpl (which works without the dynamic registrar), diff --git a/tests/monotouch-test/ObjCRuntime/ResourcesTest.cs b/tests/monotouch-test/ObjCRuntime/ResourcesTest.cs index 1899894d3ae2..c45ec4a0108e 100644 --- a/tests/monotouch-test/ObjCRuntime/ResourcesTest.cs +++ b/tests/monotouch-test/ObjCRuntime/ResourcesTest.cs @@ -24,13 +24,13 @@ public void Embedded () { var manager = new ResourceManager ("monotouchtest.Welcome", typeof (ResourcesTest).Assembly); - Assert.AreEqual ("Welcome!", manager.GetString ("String1", new CultureInfo ("en")), "en"); - Assert.AreEqual ("G'day!", manager.GetString ("String1", new CultureInfo ("en-AU")), "en-AU"); - Assert.AreEqual ("Willkommen!", manager.GetString ("String1", new CultureInfo ("de")), "de"); - Assert.AreEqual ("Willkommen!", manager.GetString ("String1", new CultureInfo ("de-DE")), "de-DE"); - Assert.AreEqual ("Bienvenido!", manager.GetString ("String1", new CultureInfo ("es")), "es"); - Assert.AreEqual ("Bienvenido!", manager.GetString ("String1", new CultureInfo ("es-AR")), "es-AR"); - Assert.AreEqual ("Bienvenido!", manager.GetString ("String1", new CultureInfo ("es-ES")), "es-ES"); + Assert.That (manager.GetString ("String1", new CultureInfo ("en")), Is.EqualTo ("Welcome!"), "en"); + Assert.That (manager.GetString ("String1", new CultureInfo ("en-AU")), Is.EqualTo ("G'day!"), "en-AU"); + Assert.That (manager.GetString ("String1", new CultureInfo ("de")), Is.EqualTo ("Willkommen!"), "de"); + Assert.That (manager.GetString ("String1", new CultureInfo ("de-DE")), Is.EqualTo ("Willkommen!"), "de-DE"); + Assert.That (manager.GetString ("String1", new CultureInfo ("es")), Is.EqualTo ("Bienvenido!"), "es"); + Assert.That (manager.GetString ("String1", new CultureInfo ("es-AR")), Is.EqualTo ("Bienvenido!"), "es-AR"); + Assert.That (manager.GetString ("String1", new CultureInfo ("es-ES")), Is.EqualTo ("Bienvenido!"), "es-ES"); } } } diff --git a/tests/monotouch-test/ObjCRuntime/RuntimeTest.cs b/tests/monotouch-test/ObjCRuntime/RuntimeTest.cs index 2d7cbb3889c0..0fc4318e3168 100644 --- a/tests/monotouch-test/ObjCRuntime/RuntimeTest.cs +++ b/tests/monotouch-test/ObjCRuntime/RuntimeTest.cs @@ -66,7 +66,7 @@ public void Method () { } [Test] public void GetNSObject_IntPtrZero () { - Assert.Null (Runtime.GetNSObject (IntPtr.Zero)); + Assert.That (Runtime.GetNSObject (IntPtr.Zero), Is.Null); } [Test] @@ -217,13 +217,13 @@ public bool UsableUntilDeadImpl () // Send a message to the collected object. Messaging.void_objc_msgSend (notifierHandle, Selector.GetHandle ("notify")); - Assert.IsTrue (isNotified, "notified"); + Assert.That (isNotified, Is.True, "notified"); // We're done. Cleanup. NSRunLoop.Main.RunUntil (NSDate.Now.AddSeconds (0.1)); // Don't verify cleanup, it's not consistent. // And in any case it's not what this test is about. - // Assert.IsTrue (isDeallocated, "released"); + // Assert.That (isDeallocated, Is.True, "released"); return true; } @@ -338,7 +338,7 @@ public void FinalizationRaceCondition () while (!thread.Join (1)) NSRunLoop.Main.RunUntil (NSDate.Now.AddSeconds (0.1)); - Assert.AreEqual (0, broken, string.Format ("broken after {0} iterations", count)); + Assert.That (broken, Is.EqualTo (0), string.Format ("broken after {0} iterations", count)); } [Test] @@ -390,7 +390,7 @@ public void ConnectMethod2 () Runtime.ConnectMethod (typeof (A), typeof (RuntimeTest).GetMethod ("Test2"), new Selector ("test2")); Messaging.void_objc_msgSend (Class.GetHandle (typeof (A)), Selector.GetHandle ("test2")); - Assert.IsTrue (calledTest2); + Assert.That (calledTest2, Is.True); } static bool calledTest2; @@ -414,7 +414,7 @@ public void ConnectMethod3 () Runtime.ConnectMethod (typeof (NSString), typeof (RuntimeTest).GetMethod ("Test3"), new Selector ("test3")); Messaging.void_objc_msgSend (Class.GetHandle (typeof (NSString)), Selector.GetHandle ("test3")); - Assert.IsTrue (calledTest3); + Assert.That (calledTest3, Is.True); } static bool calledTest3; @@ -445,15 +445,15 @@ public void GetINativeObjectTest () valueptr = Messaging.IntPtr_objc_msgSend_IntPtr (Class.GetHandle (typeof (NSString)), Selector.GetHandle ("stringWithUTF8String:"), strptr); obj = Runtime.GetINativeObject (valueptr, false) as NSString; - Assert.AreEqual ("value", (string) obj, "NSObject"); + Assert.That ((string) obj, Is.EqualTo ("value"), "NSObject"); valueptr = Messaging.IntPtr_objc_msgSend_IntPtr (Class.GetHandle (typeof (NSString)), Selector.GetHandle ("stringWithUTF8String:"), strptr); obj = Runtime.GetINativeObject (valueptr, false) as NSString; - Assert.AreEqual ("value", (string) obj, "NSString"); + Assert.That ((string) obj, Is.EqualTo ("value"), "NSString"); valueptr = Messaging.IntPtr_objc_msgSend_IntPtr (Class.GetHandle (typeof (NSString)), Selector.GetHandle ("stringWithUTF8String:"), strptr); var nscopying = Runtime.GetINativeObject (valueptr, false); - Assert.NotNull (nscopying, "INSCopying"); + Assert.That (nscopying, Is.Not.Null, "INSCopying"); } finally { Marshal.FreeHGlobal (strptr); } @@ -473,7 +473,7 @@ public void NSAutoreleasePoolInThreadPool () }); } - Assert.IsTrue (counter.Wait (TimeSpan.FromSeconds (5)), "timed out"); + Assert.That (counter.Wait (TimeSpan.FromSeconds (5)), Is.True, "timed out"); // there is a race condition here: we don't necessarily know when the // threadpool's autorelease pools are freed (in theory we can have X // threadpool threads stopped just after the 'counter.Signal' line, @@ -508,7 +508,7 @@ public void NSAutoreleasePoolInThread () } for (var i = 0; i < count; i++) { - Assert.IsTrue (threads [i].Join (TimeSpan.FromSeconds (1)), $"Thread #{i}"); + Assert.That (threads [i].Join (TimeSpan.FromSeconds (1)), Is.True, $"Thread #{i}"); } // Strangely enough there seems to be a race condition here, not all threads will necessarily @@ -597,7 +597,7 @@ public void ResurrectedObjectsDisposedTest (Type type) for (int i = 0; i < objects.Length; i++) Messaging.void_objc_msgSend (objects [i], Selector.GetHandle ("release")); - Assert.AreEqual (0, brokenCount, "broken count"); + Assert.That (brokenCount, Is.EqualTo (0), "broken count"); } [Test] @@ -643,7 +643,7 @@ public void MX8029_b () Assert.Fail ("An exception should have been thrown"); } } catch (RuntimeException re) { - Assert.AreEqual (8029, re.Code, "Code"); + Assert.That (re.Code, Is.EqualTo (8029), "Code"); string expectedExceptionMessage; if (TestRuntime.IsCoreCLR) { expectedExceptionMessage = @"Unable to marshal the array parameter #1 whose managed type is 'System.Int32[]' to managed. @@ -658,10 +658,10 @@ public void MX8029_b () Method: MonoTouchFixtures.ObjCRuntime.RuntimeTest/Dummy:SetIntArray (int[]) "; } - Assert.AreEqual (expectedExceptionMessage, re.Message, "Message"); + Assert.That (re.Message, Is.EqualTo (expectedExceptionMessage), "Message"); var inner = (RuntimeException)re.InnerException; - Assert.AreEqual (8031, inner.Code, "Inner Code"); - Assert.AreEqual ("Unable to convert from an NSArray to a managed array of System.Int32.", inner.Message, "Inner Message"); + Assert.That (inner.Code, Is.EqualTo (8031), "Inner Code"); + Assert.That (inner.Message, Is.EqualTo ("Unable to convert from an NSArray to a managed array of System.Int32."), "Inner Message"); } } @@ -672,7 +672,7 @@ public void MX8033 () Messaging.IntPtr_objc_msgSend (Class.GetHandle (typeof (Dummy)), Selector.GetHandle ("intArray")); Assert.Fail ("An exception should have been thrown"); } catch (RuntimeException re) { - Assert.AreEqual (8033, re.Code, "Code"); + Assert.That (re.Code, Is.EqualTo (8033), "Code"); string expectedExceptionMessage; if (TestRuntime.IsCoreCLR) { expectedExceptionMessage = @"Unable to marshal the return value of type 'System.Int32[]' to Objective-C. @@ -687,10 +687,10 @@ public void MX8033 () Method: MonoTouchFixtures.ObjCRuntime.RuntimeTest/Dummy:GetIntArray () "; } - Assert.AreEqual (expectedExceptionMessage, re.Message, "Message"); + Assert.That (re.Message, Is.EqualTo (expectedExceptionMessage), "Message"); var inner = (RuntimeException) re.InnerException; - Assert.AreEqual (8032, inner.Code, "Inner Code"); - Assert.AreEqual ("Unable to convert from a managed array of System.Int32 to an NSArray.", inner.Message, "Inner Message"); + Assert.That (inner.Code, Is.EqualTo (8032), "Inner Code"); + Assert.That (inner.Message, Is.EqualTo ("Unable to convert from a managed array of System.Int32 to an NSArray."), "Inner Message"); } } #endif @@ -742,7 +742,7 @@ public void GetINativeObject_ForcedType () // This is a big hack, but hopefully it works well enough for this particular test case. // Just don't inspect the date variable in a debugger (it will most likely crash the app). date = Runtime.GetINativeObject (str.Handle, true, false); - Assert.AreEqual (date.Handle, str.Handle, "Same native pointer"); + Assert.That (str.Handle, Is.EqualTo (date.Handle), "Same native pointer"); date.Dispose (); date = null; } @@ -771,7 +771,7 @@ public void ToggleRef_NonToggledObjectsShouldBeCollected () Name = "ToggleRef_NonToggledObjectsShouldBeCollected", }; t.Start (); - Assert.IsTrue (t.Join (TimeSpan.FromSeconds (10)), "Background thread completion"); + Assert.That (t.Join (TimeSpan.FromSeconds (10)), Is.True, "Background thread completion"); var checkForCollectedManagedObjects = new Func (() => { GC.Collect (); @@ -786,11 +786,11 @@ public void ToggleRef_NonToggledObjectsShouldBeCollected () // Iterate over the runloop in case something has to happen on the main thread for the objects to be collected. TestRuntime.RunAsync (TimeSpan.FromSeconds (5), checkForCollectedManagedObjects); - Assert.IsTrue (checkForCollectedManagedObjects (), "Any collected objects"); + Assert.That (checkForCollectedManagedObjects (), Is.True, "Any collected objects"); for (var i = 0; i < counter; i++) { var obj = Runtime.GetNSObject (pointers [i]); - Assert.IsNotNull (obj, $"Object #{i} couldn't be resurrected"); + Assert.That (obj, Is.Not.Null, $"Object #{i} couldn't be resurrected"); obj.DangerousRelease (); // release the native reference obj.Dispose (); handles [i].Free (); @@ -820,7 +820,7 @@ public void ToggleRef_ToggledObjectsShouldNotBeCollected () Name = "ToggleRef_ToggledObjectsShouldNotBeCollected", }; t.Start (); - Assert.IsTrue (t.Join (TimeSpan.FromSeconds (10)), "Background thread completion"); + Assert.That (t.Join (TimeSpan.FromSeconds (10)), Is.True, "Background thread completion"); TestRuntime.RunAsync (TimeSpan.FromSeconds (2), () => { // Iterate over the runloop a bit to make sure we're just not collecting because objects are queued on for things to happen on the main thread @@ -831,7 +831,7 @@ public void ToggleRef_ToggledObjectsShouldNotBeCollected () for (var i = 0; i < counter; i++) { var obj = (NSFileManager) handles [i].Target; - Assert.IsNotNull (obj, $"Object #{i} was unexpectedly collected."); + Assert.That (obj, Is.Not.Null, $"Object #{i} was unexpectedly collected."); obj.DangerousRelease (); // release the native reference obj.Dispose (); handles [i].Free (); @@ -844,7 +844,7 @@ public void CurrentDirectory () var expectedDirectory = (string) ((NSString) Environment.CurrentDirectory).ResolveSymlinksInPath (); var actualDirectory = (string) ((NSString) NSBundle.MainBundle.BundlePath).ResolveSymlinksInPath (); - Assert.AreEqual (expectedDirectory, actualDirectory, "Current directory at launch"); + Assert.That (actualDirectory, Is.EqualTo (expectedDirectory), "Current directory at launch"); } [Test] @@ -863,27 +863,27 @@ public void OriginalWorkingDirectoryTest () public void IntPtrCtor_1 () { using var obj = Runtime.GetNSObject (IntPtrConstructor.New ()); - Assert.IsNotNull (obj, "NotNull"); + Assert.That (obj, Is.Not.Null, "NotNull"); Assert.That (obj, Is.TypeOf (), "Type"); - Assert.AreNotEqual (IntPtr.Zero, obj.Handle, "Handle"); + Assert.That (obj.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); } [Test] public void IntPtrCtor_2 () { using var obj = Runtime.GetNSObject (IntPtrConstructor.New ()); - Assert.IsNotNull (obj, "NotNull"); + Assert.That (obj, Is.Not.Null, "NotNull"); Assert.That (obj, Is.TypeOf (), "Type"); - Assert.AreNotEqual (IntPtr.Zero, obj.Handle, "Handle"); + Assert.That (obj.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); } [Test] public void IntPtrCtor_3 () { using var obj = Runtime.GetINativeObject (IntPtrConstructor.New (), false); - Assert.IsNotNull (obj, "NotNull"); + Assert.That (obj, Is.Not.Null, "NotNull"); Assert.That (obj, Is.TypeOf (), "Type"); - Assert.AreNotEqual (IntPtr.Zero, obj.Handle, "Handle"); + Assert.That (obj.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); } class IntPtrConstructor : NSObject { @@ -902,9 +902,9 @@ internal static IntPtr New () public void IntPtrBoolCtor_1 () { using var obj = Runtime.GetINativeObject ((IntPtr) 1234, false); - Assert.IsNotNull (obj, "NotNull"); + Assert.That (obj, Is.Not.Null, "NotNull"); Assert.That (obj, Is.TypeOf (), "Type"); - Assert.AreNotEqual (IntPtr.Zero, obj.Handle, "Handle"); + Assert.That (obj.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); } class IntPtrBoolConstructor : DisposableObject { @@ -944,80 +944,80 @@ public class RuntimeTest_GetINativeObjectTest { public void GetINativeObjectTest_NSObject_Owns () { var handle = CreateNativeNSObject (); - Assert.AreEqual (1, GetRetainCount (handle), "A 1"); + Assert.That (GetRetainCount (handle), Is.EqualTo (1), "A 1"); using var obj = Runtime.GetINativeObject (handle, false, true); - Assert.AreEqual (1, GetRetainCount (handle), "A 2"); + Assert.That (GetRetainCount (handle), Is.EqualTo (1), "A 2"); obj.DangerousRetain (); - Assert.AreEqual (2, GetRetainCount (handle), "A 3"); + Assert.That (GetRetainCount (handle), Is.EqualTo (2), "A 3"); using var obj2 = Runtime.GetINativeObject (handle, false, true); - Assert.AreEqual (1, GetRetainCount (handle), "A 4"); + Assert.That (GetRetainCount (handle), Is.EqualTo (1), "A 4"); using var obj3 = Runtime.GetINativeObject (handle, false, false); - Assert.AreEqual (1, GetRetainCount (handle), "A 5"); - Assert.AreSame (obj, obj2, "A 6"); - Assert.AreSame (obj, obj3, "A 7"); + Assert.That (GetRetainCount (handle), Is.EqualTo (1), "A 5"); + Assert.That (obj2, Is.SameAs (obj), "A 6"); + Assert.That (obj3, Is.SameAs (obj), "A 7"); } [Test] public void GetINativeObjectTest_NSObject_Unowned () { var handle = CreateNativeNSObject (); - Assert.AreEqual (1, GetRetainCount (handle), "A 1"); + Assert.That (GetRetainCount (handle), Is.EqualTo (1), "A 1"); using var obj = Runtime.GetINativeObject (handle, false, false); - Assert.AreEqual (2, GetRetainCount (handle), "A 2"); + Assert.That (GetRetainCount (handle), Is.EqualTo (2), "A 2"); obj.DangerousRelease (); - Assert.AreEqual (1, GetRetainCount (handle), "A 3"); + Assert.That (GetRetainCount (handle), Is.EqualTo (1), "A 3"); obj.DangerousRetain (); - Assert.AreEqual (2, GetRetainCount (handle), "A 4"); + Assert.That (GetRetainCount (handle), Is.EqualTo (2), "A 4"); using var obj2 = Runtime.GetINativeObject (handle, false, true); - Assert.AreEqual (1, GetRetainCount (handle), "A 5"); + Assert.That (GetRetainCount (handle), Is.EqualTo (1), "A 5"); using var obj3 = Runtime.GetINativeObject (handle, false, false); - Assert.AreEqual (1, GetRetainCount (handle), "A 6"); - Assert.AreSame (obj, obj2, "A 7"); - Assert.AreSame (obj, obj3, "A 8"); + Assert.That (GetRetainCount (handle), Is.EqualTo (1), "A 6"); + Assert.That (obj2, Is.SameAs (obj), "A 7"); + Assert.That (obj3, Is.SameAs (obj), "A 8"); } [Test] public void GetINativeObjectTest_INativeObject_Owns () { var handle = CreateNativeBitmapContext (); - Assert.AreEqual (1, CFGetRetainCount (handle), "A 1"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (1), "A 1"); using var obj = Runtime.GetINativeObject (handle, false, true); - Assert.AreEqual (1, CFGetRetainCount (handle), "A 2"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (1), "A 2"); CGContextRetain (obj.Handle); - Assert.AreEqual (2, CFGetRetainCount (handle), "A 3"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (2), "A 3"); using var obj2 = Runtime.GetINativeObject (handle, false, true); // does not decrease refcount because we return a new instance - Assert.AreEqual (2, CFGetRetainCount (handle), "A 4"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (2), "A 4"); using var obj3 = Runtime.GetINativeObject (handle, false, false); - Assert.AreEqual (3, CFGetRetainCount (handle), "A 5"); - Assert.AreNotSame (obj, obj2, "A 6"); - Assert.AreNotSame (obj, obj3, "A 7"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (3), "A 5"); + Assert.That (obj2, Is.Not.SameAs (obj), "A 6"); + Assert.That (obj3, Is.Not.SameAs (obj), "A 7"); obj3.Dispose (); - Assert.AreEqual (2, CFGetRetainCount (handle), "A 8"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (2), "A 8"); obj2.Dispose (); - Assert.AreEqual (1, CFGetRetainCount (handle), "A 9"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (1), "A 9"); } [Test] public void GetINativeObjectTest_INativeObject_Unowned () { var handle = CreateNativeBitmapContext (); - Assert.AreEqual (1, CFGetRetainCount (handle), "A 1"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (1), "A 1"); using var obj = Runtime.GetINativeObject (handle, false, false); - Assert.AreEqual (2, CFGetRetainCount (handle), "A 2"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (2), "A 2"); CGContextRelease (obj.Handle); - Assert.AreEqual (1, CFGetRetainCount (handle), "A 3"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (1), "A 3"); CGContextRetain (obj.Handle); - Assert.AreEqual (2, CFGetRetainCount (handle), "A 4"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (2), "A 4"); using var obj2 = Runtime.GetINativeObject (handle, false, true); // does not decrease refcount because we return a new instance - Assert.AreEqual (2, CFGetRetainCount (handle), "A 5"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (2), "A 5"); using var obj3 = Runtime.GetINativeObject (handle, false, false); - Assert.AreEqual (3, CFGetRetainCount (handle), "A 6"); - Assert.AreNotSame (obj, obj2, "A 7"); - Assert.AreNotSame (obj, obj3, "A 8"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (3), "A 6"); + Assert.That (obj2, Is.Not.SameAs (obj), "A 7"); + Assert.That (obj3, Is.Not.SameAs (obj), "A 8"); obj3.Dispose (); - Assert.AreEqual (2, CFGetRetainCount (handle), "A 9"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (2), "A 9"); obj2.Dispose (); - Assert.AreEqual (1, CFGetRetainCount (handle), "A 10"); + Assert.That (CFGetRetainCount (handle), Is.EqualTo (1), "A 10"); } static IntPtr CreateNativeNSObject () diff --git a/tests/monotouch-test/ObjCRuntime/SimpleRegistrarTest.cs b/tests/monotouch-test/ObjCRuntime/SimpleRegistrarTest.cs index e89d1016efc4..fd725633dc96 100644 --- a/tests/monotouch-test/ObjCRuntime/SimpleRegistrarTest.cs +++ b/tests/monotouch-test/ObjCRuntime/SimpleRegistrarTest.cs @@ -35,9 +35,9 @@ public void SimpleRegistrarSmokeTest () RegistrarTestDerivedClass derivedObj = new RegistrarTestDerivedClass (); IntPtr derivedReceiver = derivedObj.Handle; - Assert.AreEqual (Runtime.GetNSObject (IntPtr_objc_msgSend (receiver, Selector.GetHandle ("value"))), (NSString) "RegistrarTestClass"); + Assert.That ((NSString) "RegistrarTestClass", Is.EqualTo (Runtime.GetNSObject (IntPtr_objc_msgSend (receiver, Selector.GetHandle ("value"))))); - Assert.AreEqual (Runtime.GetNSObject (IntPtr_objc_msgSend (derivedReceiver, Selector.GetHandle ("value"))), (NSString) "RegistrarTestDerivedClass"); + Assert.That ((NSString) "RegistrarTestDerivedClass", Is.EqualTo (Runtime.GetNSObject (IntPtr_objc_msgSend (derivedReceiver, Selector.GetHandle ("value"))))); } [Test] diff --git a/tests/monotouch-test/ObjCRuntime/StrongEnumTests.cs b/tests/monotouch-test/ObjCRuntime/StrongEnumTests.cs index c5b7aefee9df..1c6cfe4d205f 100644 --- a/tests/monotouch-test/ObjCRuntime/StrongEnumTests.cs +++ b/tests/monotouch-test/ObjCRuntime/StrongEnumTests.cs @@ -41,7 +41,7 @@ public void GetConstant () if (obj is not null) { var rtrip = getValue.Invoke (null, new object [] { obj }); - Assert.AreEqual (Enum.ToObject (type, enumValue), rtrip, $"{type.FullName}.{enumValue}: Round trip failed: {enumValue}.GetConstant () -> {obj} but GetValue ({obj}) -> {rtrip}"); + Assert.That (rtrip, Is.EqualTo (Enum.ToObject (type, enumValue)), $"{type.FullName}.{enumValue}: Round trip failed: {enumValue}.GetConstant () -> {obj} but GetValue ({obj}) -> {rtrip}"); } } } @@ -79,9 +79,9 @@ public void GetConstant () }; #if __TVOS__ && !XAMCORE_5_0 - if (Runtime.Arch == Arch.SIMULATOR) { - rv.AddRange (Enum.GetValues ().Select (v => (typeof (global::BrowserEngineKit.BEAccessibilityTrait), (object) (int) v))); // BrowserEngineKit isn't available in the simulator - rv.AddRange (Enum.GetValues ().Select (v => (typeof (global::BrowserEngineKit.BEAccessibilityNotification), (object) (int) v))); // BrowserEngineKit isn't available in the simulator + if (Runtime.Arch == Arch.SIMULATOR && Runtime.IsARM64CallingConvention) { + rv.AddRange (Enum.GetValues ().Select (v => (typeof (global::BrowserEngineKit.BEAccessibilityTrait), (object) (long) v))); // BrowserEngineKit isn't available in the simulator + rv.AddRange (Enum.GetValues ().Select (v => (typeof (global::BrowserEngineKit.BEAccessibilityNotification), (object) (long) v))); // BrowserEngineKit isn't available in the simulator } #endif // __TVOS__ && !XAMCORE_5_0 diff --git a/tests/monotouch-test/ObjCRuntime/TrampolineTest.cs b/tests/monotouch-test/ObjCRuntime/TrampolineTest.cs index bf804cc7224e..a884c9c44ecf 100644 --- a/tests/monotouch-test/ObjCRuntime/TrampolineTest.cs +++ b/tests/monotouch-test/ObjCRuntime/TrampolineTest.cs @@ -57,10 +57,10 @@ public void StretTrampolineTest () CMTimeRange_objc_msgSend (out tr, obj.Handle, Selector.GetHandle ("myTimeRange")); } } - Assert.AreEqual (12, tr.Duration.Value); - Assert.AreEqual (1, tr.Duration.TimeScale); - Assert.AreEqual (1, tr.Start.Value); - Assert.AreEqual (1, tr.Start.TimeScale); + Assert.That (tr.Duration.Value, Is.EqualTo (12)); + Assert.That (tr.Duration.TimeScale, Is.EqualTo (1)); + Assert.That (tr.Start.Value, Is.EqualTo (1)); + Assert.That (tr.Start.TimeScale, Is.EqualTo (1)); } [Test] @@ -157,11 +157,11 @@ public void LoooongTest () void AreAlmostEqual (CGRect left, CGRect right, string message) { - var delta = 0.000001f; - Assert.AreEqual (left.X, right.X, delta, message); - Assert.AreEqual (left.Y, right.Y, delta, message); - Assert.AreEqual (left.Width, right.Width, delta, message); - Assert.AreEqual (left.Height, right.Height, delta, message); + var delta = 0.000001; + Assert.That ((double) right.X, Is.EqualTo ((double) left.X).Within (delta), message); + Assert.That ((double) right.Y, Is.EqualTo ((double) left.Y).Within (delta), message); + Assert.That ((double) right.Width, Is.EqualTo ((double) left.Width).Within (delta), message); + Assert.That ((double) right.Height, Is.EqualTo ((double) left.Height).Within (delta), message); } [Test] @@ -342,10 +342,10 @@ public void ArrayTest () Assert.That (arr [0] == "def", "#b2"); arr = NSArray.StringArrayFromHandle (Messaging.IntPtr_objc_msgSend (obj.Handle, new Selector ("Test_StringArrayNullReturn").Handle)); - Assert.IsNull (arr, "#c1"); + Assert.That (arr, Is.Null, "#c1"); c = Messaging.int_objc_msgSend_IntPtr (obj.Handle, new Selector ("Test_StringArray:").Handle, IntPtr.Zero); - Assert.AreEqual (-1, c, "#d1"); + Assert.That (c, Is.EqualTo (-1), "#d1"); } [Test] @@ -375,12 +375,12 @@ public class MiscTrampolines : NSObject { [Export ("x64argumentoverflow:::::")] void X64ArgumentOverflow (nint a, nint b, nint c, NSRange overflow, nint d) { - Assert.AreEqual ((nint) 1, a, "1"); - Assert.AreEqual ((nint) 2, b, "2"); - Assert.AreEqual ((nint) 3, c, "3"); - Assert.AreEqual ((nint) 4, overflow.Location, "length"); - Assert.AreEqual ((nint) 5, overflow.Length, "location"); - Assert.AreEqual ((nint) 6, d, "4"); + Assert.That (a, Is.EqualTo ((nint) 1), "1"); + Assert.That (b, Is.EqualTo ((nint) 2), "2"); + Assert.That (c, Is.EqualTo ((nint) 3), "3"); + Assert.That (overflow.Location, Is.EqualTo ((nint) 4), "length"); + Assert.That (overflow.Length, Is.EqualTo ((nint) 5), "location"); + Assert.That (d, Is.EqualTo ((nint) 6), "4"); } } diff --git a/tests/monotouch-test/PassKit/AddPassesViewControllerTest.cs b/tests/monotouch-test/PassKit/AddPassesViewControllerTest.cs index edde0fe70faf..61b47a9dbbd9 100644 --- a/tests/monotouch-test/PassKit/AddPassesViewControllerTest.cs +++ b/tests/monotouch-test/PassKit/AddPassesViewControllerTest.cs @@ -29,8 +29,8 @@ public void BoardingPass () using (var ctrl = new PKAddPassesViewController (pass)) { ctrl.Finished += delegate { }; // not available on iPad... - Assert.True ((ctrl.Delegate is not null) == PKPassLibrary.IsAvailable, "Delegate"); - Assert.True ((ctrl.WeakDelegate is not null) == PKPassLibrary.IsAvailable, "WeakDelegate"); + Assert.That ((ctrl.Delegate is not null) == PKPassLibrary.IsAvailable, Is.True, "Delegate"); + Assert.That ((ctrl.WeakDelegate is not null) == PKPassLibrary.IsAvailable, Is.True, "WeakDelegate"); } } @@ -44,11 +44,11 @@ public void InitWithNibNameTest () Assert.Inconclusive ("PassKit does not work on iPads"); PKAddPassesViewController ctrl = new PKAddPassesViewController (null, null); - Assert.NotNull (ctrl, "PKAddPassesViewController ctor(String, NSBundle)"); + Assert.That (ctrl, Is.Not.Null, "PKAddPassesViewController ctor(String, NSBundle)"); ctrl.Finished += delegate { }; - Assert.True ((ctrl.Delegate is not null) == PKPassLibrary.IsAvailable, "Delegate"); - Assert.True ((ctrl.WeakDelegate is not null) == PKPassLibrary.IsAvailable, "WeakDelegate"); + Assert.That ((ctrl.Delegate is not null) == PKPassLibrary.IsAvailable, Is.True, "Delegate"); + Assert.That ((ctrl.WeakDelegate is not null) == PKPassLibrary.IsAvailable, Is.True, "WeakDelegate"); } } } diff --git a/tests/monotouch-test/PassKit/PKJapanIndividualNumberCardMetadataTest.cs b/tests/monotouch-test/PassKit/PKJapanIndividualNumberCardMetadataTest.cs index 1aa6a8e0e9be..eefcc38ccf2d 100644 --- a/tests/monotouch-test/PassKit/PKJapanIndividualNumberCardMetadataTest.cs +++ b/tests/monotouch-test/PassKit/PKJapanIndividualNumberCardMetadataTest.cs @@ -24,8 +24,8 @@ public void Ctor_CardTemplateIdentifier () using var img = new CGImage (0.0f, (int) frame.Width, (int) frame.Height, 8, 32, 4 * (int) frame.Width, colorSpace, CGBitmapFlags.ByteOrderDefault | CGBitmapFlags.Last, provider, null, false, CGColorRenderingIntent.Default); using var preview = new PKAddPassMetadataPreview (img, "description"); using var obj = new PKJapanIndividualNumberCardMetadata ("credentialIdentifier", "sharingInstanceIdentifier", "cardTemplateIdentifier", preview, PKJapanIndividualNumberCardMetadataConstructorOption.CardTemplateIdentifier); - Assert.IsNull (obj.AuthenticationPassword, "AuthenticationPassword"); - Assert.IsNull (obj.SigningPassword, "SigningPassword"); + Assert.That (obj.AuthenticationPassword, Is.Null, "AuthenticationPassword"); + Assert.That (obj.SigningPassword, Is.Null, "SigningPassword"); // There doesn't seem to be an easy way to verify that the ctor actually worked } @@ -39,8 +39,8 @@ public void Ctor_CardConfigurationIdentifier () using var img = new CGImage (0.0f, (int) frame.Width, (int) frame.Height, 8, 32, 4 * (int) frame.Width, colorSpace, CGBitmapFlags.ByteOrderDefault | CGBitmapFlags.Last, provider, null, false, CGColorRenderingIntent.Default); using var preview = new PKAddPassMetadataPreview (img, "description"); using var obj = new PKJapanIndividualNumberCardMetadata ("credentialIdentifier", "sharingInstanceIdentifier", "cardConfigurationIdentifier", preview, PKJapanIndividualNumberCardMetadataConstructorOption.CardConfigurationIdentifier); - Assert.IsNull (obj.AuthenticationPassword, "AuthenticationPassword"); - Assert.IsNull (obj.SigningPassword, "SigningPassword"); + Assert.That (obj.AuthenticationPassword, Is.Null, "AuthenticationPassword"); + Assert.That (obj.SigningPassword, Is.Null, "SigningPassword"); // There doesn't seem to be an easy way to verify that the ctor actually worked } } diff --git a/tests/monotouch-test/PassKit/PKPassTest.cs b/tests/monotouch-test/PassKit/PKPassTest.cs index 3aed15e05355..b96ccfacbd3a 100644 --- a/tests/monotouch-test/PassKit/PKPassTest.cs +++ b/tests/monotouch-test/PassKit/PKPassTest.cs @@ -13,7 +13,7 @@ public class PKPassTest { public void GetLocalizedValueNull () { using var pass = new PKPass (); - Assert.IsNull (pass.GetLocalizedValue (new NSString ()), "'PKPass.GetLocalizedValue' is not returning a null value"); + Assert.That (pass.GetLocalizedValue (new NSString ()), Is.Null, "'PKPass.GetLocalizedValue' is not returning a null value"); } } } diff --git a/tests/monotouch-test/PassKit/PKPaymentRequestTest.cs b/tests/monotouch-test/PassKit/PKPaymentRequestTest.cs index 38e9422ff6fa..e3f9de0e0f7c 100644 --- a/tests/monotouch-test/PassKit/PKPaymentRequestTest.cs +++ b/tests/monotouch-test/PassKit/PKPaymentRequestTest.cs @@ -66,11 +66,11 @@ public void WeakRequiredBillingContactFields () public void CheckDefaultNulls () { using var pr = new PKPaymentRequest (); - Assert.IsNull (pr.CountryCode, "'PKPaymentRequest.CountryCode' is not returning null by default."); - Assert.IsNull (pr.CurrencyCode, "'PKPaymentRequest.CurrencyCode' is not returning null by default."); - Assert.IsNull (pr.MerchantIdentifier, "'PKPaymentRequest.MerchantIdentifier' is not returning null by default."); - Assert.IsNull (pr.PaymentSummaryItems, "'PKPaymentRequest.PaymentSummaryItems' is not returning null by default."); - Assert.IsNull (pr.SupportedNetworks, "'PKPaymentRequest.SupportedNetworks' is not returning null by default."); + Assert.That (pr.CountryCode, Is.Null, "'PKPaymentRequest.CountryCode' is not returning null by default."); + Assert.That (pr.CurrencyCode, Is.Null, "'PKPaymentRequest.CurrencyCode' is not returning null by default."); + Assert.That (pr.MerchantIdentifier, Is.Null, "'PKPaymentRequest.MerchantIdentifier' is not returning null by default."); + Assert.That (pr.PaymentSummaryItems, Is.Null, "'PKPaymentRequest.PaymentSummaryItems' is not returning null by default."); + Assert.That (pr.SupportedNetworks, Is.Null, "'PKPaymentRequest.SupportedNetworks' is not returning null by default."); Assert.DoesNotThrow (delegate { pr.CountryCode = null; }, "'PKPaymentRequest.CountryCode' cannot be set to null."); diff --git a/tests/monotouch-test/PassKit/PKPaymentSummaryItemTest.cs b/tests/monotouch-test/PassKit/PKPaymentSummaryItemTest.cs index a0c60ff93dd0..4ea35a14c9d3 100644 --- a/tests/monotouch-test/PassKit/PKPaymentSummaryItemTest.cs +++ b/tests/monotouch-test/PassKit/PKPaymentSummaryItemTest.cs @@ -13,8 +13,8 @@ public class PKPaymentSummaryItemTest { public void CheckDefaultNulls () { using var ps = new PKPaymentSummaryItem (); - Assert.IsNull (ps.Amount, "'PKPaymentSummaryItem.Amount' is not returning null by default."); - Assert.IsNull (ps.Label, "'PKPaymentSummaryItem.Label' is not returning null by default."); + Assert.That (ps.Amount, Is.Null, "'PKPaymentSummaryItem.Amount' is not returning null by default."); + Assert.That (ps.Label, Is.Null, "'PKPaymentSummaryItem.Label' is not returning null by default."); Assert.DoesNotThrow (delegate { ps.Amount = null; }, "'PKPaymentSummaryItem.Amount' cannot be set to null."); diff --git a/tests/monotouch-test/PassKit/PassLibraryTest.cs b/tests/monotouch-test/PassKit/PassLibraryTest.cs index af602c5e1d20..ab504b70461f 100644 --- a/tests/monotouch-test/PassKit/PassLibraryTest.cs +++ b/tests/monotouch-test/PassKit/PassLibraryTest.cs @@ -38,18 +38,18 @@ public void Defaults () if (passes is null) TestRuntime.IgnoreInCI ("GetPasses () seems to randomly return null on our bots."); // If the following assert fails for you locally, please investigate! See https://github.com/xamarin/maccore/issues/2598. - Assert.NotNull (passes, "GetPasses - if this assert fails for you locally, please investigate! See https://github.com/xamarin/maccore/issues/2598."); + Assert.That (passes, Is.Not.Null, "GetPasses - if this assert fails for you locally, please investigate! See https://github.com/xamarin/maccore/issues/2598."); using (var url = PassTest.GetBoardingPassUrl ()) { // we can just open the url Assert.That (UIApplication.SharedApplication.OpenUrl (url), Is.EqualTo (true).Or.EqualTo (false), "OpenUrl"); } - Assert.Null (library.GetPass (String.Empty, String.Empty), "GetPass"); + Assert.That (library.GetPass (String.Empty, String.Empty), Is.Null, "GetPass"); using (var pass = PassTest.GetBoardingPass ()) { - Assert.False (library.Contains (pass), "Contains"); - Assert.False (library.Replace (pass), "Replace"); + Assert.That (library.Contains (pass), Is.False, "Contains"); + Assert.That (library.Replace (pass), Is.False, "Replace"); library.Remove (pass); } } diff --git a/tests/monotouch-test/PassKit/PassTest.cs b/tests/monotouch-test/PassKit/PassTest.cs index 3ffe4d1713cb..8cbf3d45e220 100644 --- a/tests/monotouch-test/PassKit/PassTest.cs +++ b/tests/monotouch-test/PassKit/PassTest.cs @@ -30,18 +30,18 @@ public void Defaults () TestRuntime.AssertXcodeVersion (4, 5); using (PKPass pass = new PKPass ()) { - Assert.Null (pass.AuthenticationToken, "AuthenticationToken"); + Assert.That (pass.AuthenticationToken, Is.Null, "AuthenticationToken"); #if !__MACCATALYST__ // PKPass.Icon doesn't work: https://github.com/xamarin/maccore/issues/2347 - Assert.NotNull (pass.Icon, "Icon"); + Assert.That (pass.Icon, Is.Not.Null, "Icon"); #endif - Assert.Null (pass.LocalizedDescription, "LocalizedDescription"); + Assert.That (pass.LocalizedDescription, Is.Null, "LocalizedDescription"); Assert.That (string.IsNullOrEmpty (pass.LocalizedName), Is.False, "LocalizedName"); - Assert.Null (pass.OrganizationName, "OrganizationName"); - Assert.Null (pass.PassTypeIdentifier, "PassTypeIdentifier"); - Assert.Null (pass.PassUrl, "PassUrl"); - Assert.Null (pass.RelevantDate, "RelevantDate"); - Assert.Null (pass.SerialNumber, "SerialNumber"); - Assert.Null (pass.WebServiceUrl, "WebServiceUrl"); + Assert.That (pass.OrganizationName, Is.Null, "OrganizationName"); + Assert.That (pass.PassTypeIdentifier, Is.Null, "PassTypeIdentifier"); + Assert.That (pass.PassUrl, Is.Null, "PassUrl"); + Assert.That (pass.RelevantDate, Is.Null, "RelevantDate"); + Assert.That (pass.SerialNumber, Is.Null, "SerialNumber"); + Assert.That (pass.WebServiceUrl, Is.Null, "WebServiceUrl"); } } @@ -51,7 +51,7 @@ static public PKPass GetBoardingPass () using (NSData data = NSData.FromUrl (url)) { NSError error; PKPass pass = new PKPass (data, out error); - Assert.Null (error, "error"); + Assert.That (error, Is.Null, "error"); return pass; } } @@ -64,7 +64,7 @@ public void BoardingPass () using (var pass = GetBoardingPass ()) { Assert.That (pass.AuthenticationToken, Is.EqualTo ("vxwxd7J8AlNNFPS8k0a0FfUFtq0ewzFdc"), "AuthenticationToken"); #if !__MACCATALYST__ // PKPass.Icon doesn't work: https://github.com/xamarin/maccore/issues/2347 - Assert.NotNull (pass.Icon, "Icon"); + Assert.That (pass.Icon, Is.Not.Null, "Icon"); #endif Assert.That (pass.LocalizedDescription, Is.Not.Null, "LocalizedDescription is not null"); @@ -76,7 +76,7 @@ public void BoardingPass () if (TestRuntime.CheckXcodeVersion (5, 0)) Assert.That (pass.PassUrl.AbsoluteString, Is.EqualTo ("shoebox://card/1UuiGnfwxHgd0G0bIuPYPNpeRX8="), "PassUrl"); else - Assert.Null (pass.PassUrl, "PassUrl"); + Assert.That (pass.PassUrl, Is.Null, "PassUrl"); Assert.That (pass.RelevantDate.SecondsSinceReferenceDate, Is.EqualTo (364688700), "RelevantDate"); Assert.That (pass.SerialNumber, Is.EqualTo ("gT6zrHkaW"), "SerialNumber"); Assert.That (pass.WebServiceUrl.AbsoluteString, Is.EqualTo ("https://example.com/passes/"), "WebServiceUrl"); diff --git a/tests/monotouch-test/PdfKit/PdfAnnotationTest.cs b/tests/monotouch-test/PdfKit/PdfAnnotationTest.cs index e0251c50e46f..dcedd396269d 100644 --- a/tests/monotouch-test/PdfKit/PdfAnnotationTest.cs +++ b/tests/monotouch-test/PdfKit/PdfAnnotationTest.cs @@ -29,8 +29,8 @@ public void Setup () public void QuadrilateralPoints () { using (var obj = new PdfAnnotation ()) { - Assert.IsNotNull (obj.QuadrilateralPoints, "Q1"); - Assert.AreEqual (0, obj.QuadrilateralPoints.Length, "Q1b"); + Assert.That (obj.QuadrilateralPoints, Is.Not.Null, "Q1"); + Assert.That (obj.QuadrilateralPoints.Length, Is.EqualTo (0), "Q1b"); var points = new CGPoint [] { @@ -41,11 +41,11 @@ public void QuadrilateralPoints () }; obj.QuadrilateralPoints = points; - Assert.AreEqual (points, obj.QuadrilateralPoints, "Q2"); + Assert.That (obj.QuadrilateralPoints, Is.EqualTo (points), "Q2"); obj.QuadrilateralPoints = null; - Assert.IsNotNull (obj.QuadrilateralPoints, "Q3"); - Assert.AreEqual (0, obj.QuadrilateralPoints.Length, "Q3b"); + Assert.That (obj.QuadrilateralPoints, Is.Not.Null, "Q3"); + Assert.That (obj.QuadrilateralPoints.Length, Is.EqualTo (0), "Q3b"); } } diff --git a/tests/monotouch-test/Phase/PhaseAmbientMixerDefinitionTest.cs b/tests/monotouch-test/Phase/PhaseAmbientMixerDefinitionTest.cs index 475c84aea78b..acd670cefc84 100644 --- a/tests/monotouch-test/Phase/PhaseAmbientMixerDefinitionTest.cs +++ b/tests/monotouch-test/Phase/PhaseAmbientMixerDefinitionTest.cs @@ -31,7 +31,7 @@ public void TestConstructor () var orientation = new Quaternion (1, 0, 0, 0); using var layout = new AVAudioChannelLayout (AudioChannelLayoutTag.MPEG_5_1_A); using (var mixer = new PhaseAmbientMixerDefinition (layout, orientation)) { - Assert.AreEqual (orientation, mixer.Orientation); + Assert.That (mixer.Orientation, Is.EqualTo (orientation)); } } } diff --git a/tests/monotouch-test/Phase/PhaseEnvelopeSegmentTest.cs b/tests/monotouch-test/Phase/PhaseEnvelopeSegmentTest.cs index 3eec98d83556..5011f32027cd 100644 --- a/tests/monotouch-test/Phase/PhaseEnvelopeSegmentTest.cs +++ b/tests/monotouch-test/Phase/PhaseEnvelopeSegmentTest.cs @@ -27,10 +27,10 @@ public void ConstructorTest () { var endPoint = new Vector2d (1, 2); using (var segment = new PhaseEnvelopeSegment (endPoint, PhaseCurveType.Cubed)) { - Assert.AreEqual (endPoint, segment.EndPoint); + Assert.That (segment.EndPoint, Is.EqualTo (endPoint)); var newEndPoint = new Vector2d (2, 1); segment.EndPoint = newEndPoint; - Assert.AreEqual (newEndPoint, segment.EndPoint); + Assert.That (segment.EndPoint, Is.EqualTo (newEndPoint)); } } diff --git a/tests/monotouch-test/Phase/PhaseEnvelopeTest.cs b/tests/monotouch-test/Phase/PhaseEnvelopeTest.cs index c4df7b2c0a0e..b0c1c1b9937e 100644 --- a/tests/monotouch-test/Phase/PhaseEnvelopeTest.cs +++ b/tests/monotouch-test/Phase/PhaseEnvelopeTest.cs @@ -28,7 +28,7 @@ public void ConstructorTest () var start = new Vector2d (1, 2); using (var envelope = new PhaseEnvelope (start, new PhaseEnvelopeSegment [] { })) { // assert we do get the start vector - Assert.AreEqual (start, envelope.StartPoint); + Assert.That (envelope.StartPoint, Is.EqualTo (start)); } } diff --git a/tests/monotouch-test/Phase/PhaseObjectTest.cs b/tests/monotouch-test/Phase/PhaseObjectTest.cs index b01e4f6b574c..631e21c1648b 100644 --- a/tests/monotouch-test/Phase/PhaseObjectTest.cs +++ b/tests/monotouch-test/Phase/PhaseObjectTest.cs @@ -35,40 +35,40 @@ public void TearDown () public void RightTest () { var right = PhaseObject.Right; - Assert.NotNull (right, "not null"); - Assert.AreEqual (1, right.Length (), "length"); + Assert.That (right, Is.Not.Null, "not null"); + Assert.That (right.Length (), Is.EqualTo (1), "length"); } [Test] public void UpTest () { var up = PhaseObject.Up; - Assert.NotNull (up, "not null"); - Assert.AreEqual (1, up.Length (), "length"); + Assert.That (up, Is.Not.Null, "not null"); + Assert.That (up.Length (), Is.EqualTo (1), "length"); } [Test] public void ForwardTest () { var fwd = PhaseObject.Forward; - Assert.NotNull (fwd, "not null"); - Assert.AreEqual (1, fwd.Length (), "length"); + Assert.That (fwd, Is.Not.Null, "not null"); + Assert.That (fwd.Length (), Is.EqualTo (1), "length"); } [Test] public void TransformTest () { var matrix = phaseObject.Transform; - Assert.NotNull (matrix, "not null"); - Assert.AreEqual (1, matrix.M11, "11"); + Assert.That (matrix, Is.Not.Null, "not null"); + Assert.That (matrix.M11, Is.EqualTo (1), "11"); } [Test] public void WorldTransform () { var matrix = phaseObject.WorldTransform; - Assert.NotNull (matrix, "not null"); - Assert.AreEqual (1, matrix.M11, "11"); + Assert.That (matrix, Is.Not.Null, "not null"); + Assert.That (matrix.M11, Is.EqualTo (1), "11"); } } diff --git a/tests/monotouch-test/Photos/FetchResultTest.cs b/tests/monotouch-test/Photos/FetchResultTest.cs index 717ec5770317..47076d6a892b 100644 --- a/tests/monotouch-test/Photos/FetchResultTest.cs +++ b/tests/monotouch-test/Photos/FetchResultTest.cs @@ -40,7 +40,8 @@ public void FetchResultToArray () // Actual Test var array = collection.ToArray (); - Assert.That (array is not null && array.Count () > 0); + Assert.That (array, Is.Not.Null); + Assert.That (array.Count (), Is.GreaterThan (0)); } [Test] @@ -54,7 +55,7 @@ public void FetchResultIndex () // Actual Test var obj = collection [0]; - Assert.IsNotNull (obj); + Assert.That (obj, Is.Not.Null); } [Test] @@ -68,7 +69,8 @@ public void FetchResultObjectsAt () // Actual Test var obj = collection.ObjectsAt (NSIndexSet.FromNSRange (new NSRange (0, 1))); - Assert.That (obj is not null && obj.Count () > 0); + Assert.That (obj, Is.Not.Null); + Assert.That (obj.Count (), Is.GreaterThan (0)); } } diff --git a/tests/monotouch-test/Photos/LivePhotoEditingContextTest.cs b/tests/monotouch-test/Photos/LivePhotoEditingContextTest.cs index 2e926127dcb3..244837de7b4c 100644 --- a/tests/monotouch-test/Photos/LivePhotoEditingContextTest.cs +++ b/tests/monotouch-test/Photos/LivePhotoEditingContextTest.cs @@ -36,7 +36,7 @@ public void Linker () using (var cei = new PHContentEditingInput ()) using (var lpec = new PHLivePhotoEditingContext (cei)) { // not much but it means the linker cannot remove it - Assert.Null (lpec.FrameProcessor, "FrameProcessor"); + Assert.That (lpec.FrameProcessor, Is.Null, "FrameProcessor"); } } @@ -60,10 +60,10 @@ public unsafe void FrameProcessingBlock2 () Assert.Ignore ("This test requires support for the dynamic registrar to setup the block"); var t = typeof (NSObject).Assembly.GetType ("ObjCRuntime.Trampolines+SDPHLivePhotoFrameProcessingBlock"); - Assert.NotNull (t, "SDPHLivePhotoFrameProcessingBlock2"); + Assert.That (t, Is.Not.Null, "SDPHLivePhotoFrameProcessingBlock2"); var m = t.GetMethod ("Invoke", BindingFlags.Static | BindingFlags.NonPublic); - Assert.NotNull (m, "Invoke"); + Assert.That (m, Is.Not.Null, "Invoke"); var d = m.CreateDelegate (typeof (DPHLivePhotoFrameProcessingBlock2)); var fptr = m.MethodHandle.GetFunctionPointer (); var del = new DPHLivePhotoFrameProcessingBlock2 ((IntPtr a, NativeHandle b, NativeHandle* c) => (NativeHandle) global::Bindings.Test.CFunctions.x_call_func_3 (fptr, (IntPtr) a, (IntPtr) b, (IntPtr) (void*) c)); diff --git a/tests/monotouch-test/PushKit/PushRegistryTest.cs b/tests/monotouch-test/PushKit/PushRegistryTest.cs index 11b037bd3db5..903810c6e97d 100644 --- a/tests/monotouch-test/PushKit/PushRegistryTest.cs +++ b/tests/monotouch-test/PushKit/PushRegistryTest.cs @@ -22,13 +22,13 @@ public void CtorDispatchQueue () using (var dq = new DispatchQueue ("pk-test-queue")) using (var pr = new PKPushRegistry (dq)) { - Assert.Null (pr.Delegate, "Delegate"); - Assert.Null (pr.DesiredPushTypes, "DesiredPushTypes"); - Assert.Null (pr.WeakDelegate, "WeakDelegate"); + Assert.That (pr.Delegate, Is.Null, "Delegate"); + Assert.That (pr.DesiredPushTypes, Is.Null, "DesiredPushTypes"); + Assert.That (pr.WeakDelegate, Is.Null, "WeakDelegate"); // it's nullable (setting a value needs more app setup or ObjC exceptions will occurs later) pr.DesiredPushTypes = null; - Assert.Null (pr.DesiredPushTypes, "DesiredPushTypes-2"); + Assert.That (pr.DesiredPushTypes, Is.Null, "DesiredPushTypes-2"); } } } diff --git a/tests/monotouch-test/QuickLook/PreviewControllerTest.cs b/tests/monotouch-test/QuickLook/PreviewControllerTest.cs index 891403cf054f..edac975afae8 100644 --- a/tests/monotouch-test/QuickLook/PreviewControllerTest.cs +++ b/tests/monotouch-test/QuickLook/PreviewControllerTest.cs @@ -25,7 +25,7 @@ public class PreviewControllerTest { public void Defaults () { using (QLPreviewController pc = new QLPreviewController ()) { - Assert.Null (pc.CurrentPreviewItem, "CurrentPreviewItem"); + Assert.That (pc.CurrentPreviewItem, Is.Null, "CurrentPreviewItem"); nint index = 0; #if !__MACCATALYST__ if (TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 10, 0)) @@ -35,11 +35,11 @@ public void Defaults () #endif Assert.That (pc.CurrentPreviewItemIndex, Is.EqualTo (index), "CurrentPreviewItemIndex"); - Assert.Null (pc.Delegate, "Delegate"); - Assert.Null (pc.WeakDelegate, "WeakDelegate"); + Assert.That (pc.Delegate, Is.Null, "Delegate"); + Assert.That (pc.WeakDelegate, Is.Null, "WeakDelegate"); - Assert.Null (pc.DataSource, "DataSource"); - Assert.Null (pc.WeakDataSource, "WeakDataSource"); + Assert.That (pc.DataSource, Is.Null, "DataSource"); + Assert.That (pc.WeakDataSource, Is.Null, "WeakDataSource"); pc.RefreshCurrentPreviewItem (); pc.ReloadData (); @@ -63,8 +63,8 @@ public void DelegateEvents () return new UIImage (); }; - Assert.NotNull (pc.Delegate, "Delegate"); - Assert.NotNull (pc.WeakDelegate, "WeakDelegate"); + Assert.That (pc.Delegate, Is.Not.Null, "Delegate"); + Assert.That (pc.WeakDelegate, Is.Not.Null, "WeakDelegate"); } } } diff --git a/tests/monotouch-test/SafariServices/ReadingListTest.cs b/tests/monotouch-test/SafariServices/ReadingListTest.cs index 9fdea3dfb7fd..8217b97a6b2c 100644 --- a/tests/monotouch-test/SafariServices/ReadingListTest.cs +++ b/tests/monotouch-test/SafariServices/ReadingListTest.cs @@ -32,13 +32,13 @@ public void DefaultReadingList () using (var http = new NSUrl ("http://www.xamarin.com")) using (var local = new NSUrl (local_file, false)) using (var rl = SSReadingList.DefaultReadingList) { - Assert.True (rl.Add (http, "title", "preview text", out error), "Add-1"); - Assert.Null (error, "error-1"); + Assert.That (rl.Add (http, "title", "preview text", out error), Is.True, "Add-1"); + Assert.That (error, Is.Null, "error-1"); - Assert.True (rl.Add (http, null, null, out error), "Add-2"); - Assert.Null (error, "error-2"); + Assert.That (rl.Add (http, null, null, out error), Is.True, "Add-2"); + Assert.That (error, Is.Null, "error-2"); - Assert.False (rl.Add (local, null, null, out error), "Add-3"); + Assert.That (rl.Add (local, null, null, out error), Is.False, "Add-3"); Assert.That (error.Domain, Is.EqualTo ((string) SSReadingListError.UrlSchemeNotAllowed.GetDomain ()), "Domain"); Assert.That (error.Code, Is.EqualTo ((nint) (int) SSReadingListError.UrlSchemeNotAllowed), "Code"); @@ -59,13 +59,13 @@ public void SupportsUrl () { TestRuntime.AssertSystemVersion (ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false); - Assert.False (SSReadingList.SupportsUrl (null), "null"); + Assert.That (SSReadingList.SupportsUrl (null), Is.False, "null"); using (var http = new NSUrl ("http://www.xamarin.com")) - Assert.True (SSReadingList.SupportsUrl (http), "http"); + Assert.That (SSReadingList.SupportsUrl (http), Is.True, "http"); using (var local = new NSUrl (local_file, false)) - Assert.False (SSReadingList.SupportsUrl (local), "local"); + Assert.That (SSReadingList.SupportsUrl (local), Is.False, "local"); } } } diff --git a/tests/monotouch-test/SceneKit/ActionTest.cs b/tests/monotouch-test/SceneKit/ActionTest.cs index 562d99e92ac0..9a67f0375989 100644 --- a/tests/monotouch-test/SceneKit/ActionTest.cs +++ b/tests/monotouch-test/SceneKit/ActionTest.cs @@ -30,7 +30,7 @@ public void TimingFunction_5072 () timeFunctionValue = f; return timeFunctionValue; }; - // Assert.Null (a.TimingFunction, "TimingFunction-end"); + // Assert.That (a.TimingFunction, Is.Null, "TimingFunction-end"); } } } diff --git a/tests/monotouch-test/SceneKit/GeometrySourceTest.cs b/tests/monotouch-test/SceneKit/GeometrySourceTest.cs index dcb9dab490b7..d4a7c566e362 100644 --- a/tests/monotouch-test/SceneKit/GeometrySourceTest.cs +++ b/tests/monotouch-test/SceneKit/GeometrySourceTest.cs @@ -30,7 +30,7 @@ public void FromMetalBuffer () using (var source = SCNGeometrySource.FromMetalBuffer (buffer, MTLVertexFormat.Char2, SCNGeometrySourceSemantic.Vertex, 36, 0, 0)) { // the fact that it works means the lack of respondToSelector (in introspection tests) is no // big deal and that the API really exists - Assert.NotNull (source); + Assert.That (source, Is.Not.Null); } } } diff --git a/tests/monotouch-test/SceneKit/SCNGeometrySource.cs b/tests/monotouch-test/SceneKit/SCNGeometrySource.cs index ef637404ae4f..faa68f531d40 100644 --- a/tests/monotouch-test/SceneKit/SCNGeometrySource.cs +++ b/tests/monotouch-test/SceneKit/SCNGeometrySource.cs @@ -10,7 +10,7 @@ public class SCNGeometrySourceTests { [Test] public void SCNGeometrySourceSemanticTest () { - Assert.IsNotNull (SCNGeometrySourceSemantic.Color, "Color"); + Assert.That (SCNGeometrySourceSemantic.Color, Is.Not.Null, "Color"); } [Test] diff --git a/tests/monotouch-test/SceneKit/SCNMatrixTest.cs b/tests/monotouch-test/SceneKit/SCNMatrixTest.cs index 626fc8418851..4eba0f7aeeba 100644 --- a/tests/monotouch-test/SceneKit/SCNMatrixTest.cs +++ b/tests/monotouch-test/SceneKit/SCNMatrixTest.cs @@ -140,7 +140,7 @@ public void Determinant () 5, 3, 5, 8, 9, 6, 4, 2, 4, 6, 9, 8); - Assert.AreEqual ((pfloat) (-165), matrix.Determinant, "Determinant"); + Assert.That (matrix.Determinant, Is.EqualTo ((pfloat) (-165)), "Determinant"); } @@ -169,22 +169,22 @@ public void Elements () 12, 22, 32, 42, 13, 23, 33, 43, 14, 24, 34, 44); - Assert.AreEqual ((pfloat) 11, matrix.M11, "M11"); - Assert.AreEqual ((pfloat) 12, matrix.M12, "M12"); - Assert.AreEqual ((pfloat) 13, matrix.M13, "M13"); - Assert.AreEqual ((pfloat) 14, matrix.M14, "M14"); - Assert.AreEqual ((pfloat) 21, matrix.M21, "M21"); - Assert.AreEqual ((pfloat) 22, matrix.M22, "M22"); - Assert.AreEqual ((pfloat) 23, matrix.M23, "M23"); - Assert.AreEqual ((pfloat) 24, matrix.M24, "M24"); - Assert.AreEqual ((pfloat) 31, matrix.M31, "M31"); - Assert.AreEqual ((pfloat) 32, matrix.M32, "M32"); - Assert.AreEqual ((pfloat) 33, matrix.M33, "M33"); - Assert.AreEqual ((pfloat) 34, matrix.M34, "M34"); - Assert.AreEqual ((pfloat) 41, matrix.M41, "M41"); - Assert.AreEqual ((pfloat) 42, matrix.M42, "M42"); - Assert.AreEqual ((pfloat) 43, matrix.M43, "M43"); - Assert.AreEqual ((pfloat) 44, matrix.M44, "M44"); + Assert.That (matrix.M11, Is.EqualTo ((pfloat) 11), "M11"); + Assert.That (matrix.M12, Is.EqualTo ((pfloat) 12), "M12"); + Assert.That (matrix.M13, Is.EqualTo ((pfloat) 13), "M13"); + Assert.That (matrix.M14, Is.EqualTo ((pfloat) 14), "M14"); + Assert.That (matrix.M21, Is.EqualTo ((pfloat) 21), "M21"); + Assert.That (matrix.M22, Is.EqualTo ((pfloat) 22), "M22"); + Assert.That (matrix.M23, Is.EqualTo ((pfloat) 23), "M23"); + Assert.That (matrix.M24, Is.EqualTo ((pfloat) 24), "M24"); + Assert.That (matrix.M31, Is.EqualTo ((pfloat) 31), "M31"); + Assert.That (matrix.M32, Is.EqualTo ((pfloat) 32), "M32"); + Assert.That (matrix.M33, Is.EqualTo ((pfloat) 33), "M33"); + Assert.That (matrix.M34, Is.EqualTo ((pfloat) 34), "M34"); + Assert.That (matrix.M41, Is.EqualTo ((pfloat) 41), "M41"); + Assert.That (matrix.M42, Is.EqualTo ((pfloat) 42), "M42"); + Assert.That (matrix.M43, Is.EqualTo ((pfloat) 43), "M43"); + Assert.That (matrix.M44, Is.EqualTo ((pfloat) 44), "M44"); var pos = new SCNVector3 (10, 20, 30); var transformed = SCNVector3.TransformPosition (pos, matrix); @@ -956,7 +956,7 @@ public void Operator_Equals () new SCNVector4 (921, 922, 923, 924), new SCNVector4 (931, 932, 933, 934), new SCNVector4 (941, 942, 943, 944)); - Assert.IsFalse (a == b, "Equals"); + Assert.That (a == b, Is.False, "Equals"); } [Test] @@ -972,7 +972,7 @@ public void Operator_NotEquals () new SCNVector4 (921, 922, 923, 924), new SCNVector4 (931, 932, 933, 934), new SCNVector4 (941, 942, 943, 944)); - Assert.IsTrue (a != b, "NotEquals"); + Assert.That (a != b, Is.True, "NotEquals"); } [Test] @@ -983,7 +983,7 @@ public void ToStringTest () new SCNVector4 (21, 22, 23, 24), new SCNVector4 (31, 32, 33, 34), new SCNVector4 (41, 42, 43, 44)); - Assert.AreEqual ("(11, 12, 13, 14)\n(21, 22, 23, 24)\n(31, 32, 33, 34)\n(41, 42, 43, 44)", matrix.ToString (), "ToString"); + Assert.That (matrix.ToString (), Is.EqualTo ("(11, 12, 13, 14)\n(21, 22, 23, 24)\n(31, 32, 33, 34)\n(41, 42, 43, 44)"), "ToString"); } [Test] @@ -999,7 +999,7 @@ public void Object_Equals () new SCNVector4 (921, 922, 923, 924), new SCNVector4 (931, 932, 933, 934), new SCNVector4 (941, 942, 943, 944)); - Assert.IsFalse (((object) a).Equals (b), "object.Equals"); + Assert.That (((object) a).Equals (b), Is.False, "object.Equals"); } [Test] @@ -1015,7 +1015,7 @@ public void IEquatable_Equals () new SCNVector4 (921, 922, 923, 924), new SCNVector4 (931, 932, 933, 934), new SCNVector4 (941, 942, 943, 944)); - Assert.IsFalse (((IEquatable) a).Equals (b), "object.Equals"); + Assert.That (((IEquatable) a).Equals (b), Is.False, "object.Equals"); } [Test] diff --git a/tests/monotouch-test/SceneKit/SCNNode.cs b/tests/monotouch-test/SceneKit/SCNNode.cs index 6380d67d71df..1e1a5dd5a5dd 100644 --- a/tests/monotouch-test/SceneKit/SCNNode.cs +++ b/tests/monotouch-test/SceneKit/SCNNode.cs @@ -17,11 +17,11 @@ public void SCNNode_AddAnimation () NSString key = new NSString ("MyKey"); c.AddAnimation (a, key); CAPropertyAnimation cur = (CAPropertyAnimation) c.GetAnimation (key); - Assert.IsNotNull (cur); - Assert.AreEqual (cur.KeyPath, "hidden"); + Assert.That (cur, Is.Not.Null); + Assert.That (cur.KeyPath, Is.EqualTo ("hidden")); c.RemoveAnimation (key); cur = (CAPropertyAnimation) c.GetAnimation (key); - Assert.IsNull (cur); + Assert.That (cur, Is.Null); } [Test] diff --git a/tests/monotouch-test/SceneKit/SCNParticleSystemTest.cs b/tests/monotouch-test/SceneKit/SCNParticleSystemTest.cs index ea4427448469..38ddabde8f36 100644 --- a/tests/monotouch-test/SceneKit/SCNParticleSystemTest.cs +++ b/tests/monotouch-test/SceneKit/SCNParticleSystemTest.cs @@ -29,8 +29,8 @@ public class SCNParticleSystemTest { public void Create () { using (var ps = SCNParticleSystem.Create ()) { - Assert.IsNotNull (ps, "Create should return non-null"); - Assert.AreNotEqual (IntPtr.Zero, ps.Handle, "Handle should not be zero"); + Assert.That (ps, Is.Not.Null, "Create should return non-null"); + Assert.That (ps.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle should not be zero"); } } @@ -44,7 +44,7 @@ public void CreateNamed_Null () public void CreateNamed_InvalidName () { var ps = SCNParticleSystem.Create ("nonexistent", null); - Assert.IsNull (ps, "Create with invalid name should return null"); + Assert.That (ps, Is.Null, "Create with invalid name should return null"); } [Test] @@ -52,7 +52,7 @@ public void CreateNamed_NullDirectory () { var ps = SCNParticleSystem.Create ("test", null); // Should not throw, just return null if not found - Assert.IsNull (ps, "Create with null directory should return null if not found"); + Assert.That (ps, Is.Null, "Create with null directory should return null if not found"); } [Test] @@ -63,7 +63,7 @@ public void PropertyControllers_Get () // PropertyControllers can be null initially // If not null, verify it's a valid object if (controllers is not null) { - Assert.IsNotNull (controllers, "PropertyControllers should be non-null or null"); + Assert.That (controllers, Is.Not.Null, "PropertyControllers should be non-null or null"); } } } @@ -73,7 +73,7 @@ public void PropertyControllers_SetNull () { using (var ps = SCNParticleSystem.Create ()) { ps.PropertyControllers = null; - Assert.IsNull (ps.PropertyControllers, "PropertyControllers should be null after setting to null"); + Assert.That (ps.PropertyControllers, Is.Null, "PropertyControllers should be null after setting to null"); } } @@ -83,7 +83,7 @@ public void PropertyControllers_Set () using (var ps = SCNParticleSystem.Create ()) { var controllers = new SCNPropertyControllers (); ps.PropertyControllers = controllers; - Assert.IsNotNull (ps.PropertyControllers, "PropertyControllers should be non-null after setting"); + Assert.That (ps.PropertyControllers, Is.Not.Null, "PropertyControllers should be non-null after setting"); } } @@ -91,231 +91,231 @@ public void PropertyControllers_Set () public void PropertyControllers_EmptyConstructor () { var controllers = new SCNPropertyControllers (); - Assert.IsNotNull (controllers, "Empty constructor should create valid object"); + Assert.That (controllers, Is.Not.Null, "Empty constructor should create valid object"); } [Test] public void PropertyControllers_Position () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.Position, "Position should be null initially"); + Assert.That (controllers.Position, Is.Null, "Position should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.Position = controller; - Assert.IsNotNull (controllers.Position, "Position should be non-null after setting"); + Assert.That (controllers.Position, Is.Not.Null, "Position should be non-null after setting"); } controllers.Position = null; - Assert.IsNull (controllers.Position, "Position should be null after setting to null"); + Assert.That (controllers.Position, Is.Null, "Position should be null after setting to null"); } [Test] public void PropertyControllers_Angle () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.Angle, "Angle should be null initially"); + Assert.That (controllers.Angle, Is.Null, "Angle should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.Angle = controller; - Assert.IsNotNull (controllers.Angle, "Angle should be non-null after setting"); + Assert.That (controllers.Angle, Is.Not.Null, "Angle should be non-null after setting"); } controllers.Angle = null; - Assert.IsNull (controllers.Angle, "Angle should be null after setting to null"); + Assert.That (controllers.Angle, Is.Null, "Angle should be null after setting to null"); } [Test] public void PropertyControllers_RotationAxis () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.RotationAxis, "RotationAxis should be null initially"); + Assert.That (controllers.RotationAxis, Is.Null, "RotationAxis should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.RotationAxis = controller; - Assert.IsNotNull (controllers.RotationAxis, "RotationAxis should be non-null after setting"); + Assert.That (controllers.RotationAxis, Is.Not.Null, "RotationAxis should be non-null after setting"); } controllers.RotationAxis = null; - Assert.IsNull (controllers.RotationAxis, "RotationAxis should be null after setting to null"); + Assert.That (controllers.RotationAxis, Is.Null, "RotationAxis should be null after setting to null"); } [Test] public void PropertyControllers_Velocity () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.Velocity, "Velocity should be null initially"); + Assert.That (controllers.Velocity, Is.Null, "Velocity should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.Velocity = controller; - Assert.IsNotNull (controllers.Velocity, "Velocity should be non-null after setting"); + Assert.That (controllers.Velocity, Is.Not.Null, "Velocity should be non-null after setting"); } controllers.Velocity = null; - Assert.IsNull (controllers.Velocity, "Velocity should be null after setting to null"); + Assert.That (controllers.Velocity, Is.Null, "Velocity should be null after setting to null"); } [Test] public void PropertyControllers_AngularVelocity () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.AngularVelocity, "AngularVelocity should be null initially"); + Assert.That (controllers.AngularVelocity, Is.Null, "AngularVelocity should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.AngularVelocity = controller; - Assert.IsNotNull (controllers.AngularVelocity, "AngularVelocity should be non-null after setting"); + Assert.That (controllers.AngularVelocity, Is.Not.Null, "AngularVelocity should be non-null after setting"); } controllers.AngularVelocity = null; - Assert.IsNull (controllers.AngularVelocity, "AngularVelocity should be null after setting to null"); + Assert.That (controllers.AngularVelocity, Is.Null, "AngularVelocity should be null after setting to null"); } [Test] public void PropertyControllers_Life () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.Life, "Life should be null initially"); + Assert.That (controllers.Life, Is.Null, "Life should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.Life = controller; - Assert.IsNotNull (controllers.Life, "Life should be non-null after setting"); + Assert.That (controllers.Life, Is.Not.Null, "Life should be non-null after setting"); } controllers.Life = null; - Assert.IsNull (controllers.Life, "Life should be null after setting to null"); + Assert.That (controllers.Life, Is.Null, "Life should be null after setting to null"); } [Test] public void PropertyControllers_Color () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.Color, "Color should be null initially"); + Assert.That (controllers.Color, Is.Null, "Color should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.Color = controller; - Assert.IsNotNull (controllers.Color, "Color should be non-null after setting"); + Assert.That (controllers.Color, Is.Not.Null, "Color should be non-null after setting"); } controllers.Color = null; - Assert.IsNull (controllers.Color, "Color should be null after setting to null"); + Assert.That (controllers.Color, Is.Null, "Color should be null after setting to null"); } [Test] public void PropertyControllers_Opacity () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.Opacity, "Opacity should be null initially"); + Assert.That (controllers.Opacity, Is.Null, "Opacity should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.Opacity = controller; - Assert.IsNotNull (controllers.Opacity, "Opacity should be non-null after setting"); + Assert.That (controllers.Opacity, Is.Not.Null, "Opacity should be non-null after setting"); } controllers.Opacity = null; - Assert.IsNull (controllers.Opacity, "Opacity should be null after setting to null"); + Assert.That (controllers.Opacity, Is.Null, "Opacity should be null after setting to null"); } [Test] public void PropertyControllers_Size () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.Size, "Size should be null initially"); + Assert.That (controllers.Size, Is.Null, "Size should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.Size = controller; - Assert.IsNotNull (controllers.Size, "Size should be non-null after setting"); + Assert.That (controllers.Size, Is.Not.Null, "Size should be non-null after setting"); } controllers.Size = null; - Assert.IsNull (controllers.Size, "Size should be null after setting to null"); + Assert.That (controllers.Size, Is.Null, "Size should be null after setting to null"); } [Test] public void PropertyControllers_Frame () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.Frame, "Frame should be null initially"); + Assert.That (controllers.Frame, Is.Null, "Frame should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.Frame = controller; - Assert.IsNotNull (controllers.Frame, "Frame should be non-null after setting"); + Assert.That (controllers.Frame, Is.Not.Null, "Frame should be non-null after setting"); } controllers.Frame = null; - Assert.IsNull (controllers.Frame, "Frame should be null after setting to null"); + Assert.That (controllers.Frame, Is.Null, "Frame should be null after setting to null"); } [Test] public void PropertyControllers_FrameRate () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.FrameRate, "FrameRate should be null initially"); + Assert.That (controllers.FrameRate, Is.Null, "FrameRate should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.FrameRate = controller; - Assert.IsNotNull (controllers.FrameRate, "FrameRate should be non-null after setting"); + Assert.That (controllers.FrameRate, Is.Not.Null, "FrameRate should be non-null after setting"); } controllers.FrameRate = null; - Assert.IsNull (controllers.FrameRate, "FrameRate should be null after setting to null"); + Assert.That (controllers.FrameRate, Is.Null, "FrameRate should be null after setting to null"); } [Test] public void PropertyControllers_Bounce () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.Bounce, "Bounce should be null initially"); + Assert.That (controllers.Bounce, Is.Null, "Bounce should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.Bounce = controller; - Assert.IsNotNull (controllers.Bounce, "Bounce should be non-null after setting"); + Assert.That (controllers.Bounce, Is.Not.Null, "Bounce should be non-null after setting"); } controllers.Bounce = null; - Assert.IsNull (controllers.Bounce, "Bounce should be null after setting to null"); + Assert.That (controllers.Bounce, Is.Null, "Bounce should be null after setting to null"); } [Test] public void PropertyControllers_Charge () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.Charge, "Charge should be null initially"); + Assert.That (controllers.Charge, Is.Null, "Charge should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.Charge = controller; - Assert.IsNotNull (controllers.Charge, "Charge should be non-null after setting"); + Assert.That (controllers.Charge, Is.Not.Null, "Charge should be non-null after setting"); } controllers.Charge = null; - Assert.IsNull (controllers.Charge, "Charge should be null after setting to null"); + Assert.That (controllers.Charge, Is.Null, "Charge should be null after setting to null"); } [Test] public void PropertyControllers_Friction () { var controllers = new SCNPropertyControllers (); - Assert.IsNull (controllers.Friction, "Friction should be null initially"); + Assert.That (controllers.Friction, Is.Null, "Friction should be null initially"); using (var animation = CAAnimation.CreateAnimation ()) using (var controller = SCNParticlePropertyController.Create (animation)) { controllers.Friction = controller; - Assert.IsNotNull (controllers.Friction, "Friction should be non-null after setting"); + Assert.That (controllers.Friction, Is.Not.Null, "Friction should be non-null after setting"); } controllers.Friction = null; - Assert.IsNull (controllers.Friction, "Friction should be null after setting to null"); + Assert.That (controllers.Friction, Is.Null, "Friction should be null after setting to null"); } [Test] @@ -331,9 +331,9 @@ public void PropertyControllers_MultipleProperties () controllers.Color = colorController; controllers.Size = sizeController; - Assert.IsNotNull (controllers.Position, "Position should be set"); - Assert.IsNotNull (controllers.Color, "Color should be set"); - Assert.IsNotNull (controllers.Size, "Size should be set"); + Assert.That (controllers.Position, Is.Not.Null, "Position should be set"); + Assert.That (controllers.Color, Is.Not.Null, "Color should be set"); + Assert.That (controllers.Size, Is.Not.Null, "Size should be set"); } } @@ -346,13 +346,13 @@ public void PropertyControllers_ReplaceProperty () using (var controller1 = SCNParticlePropertyController.Create (animation)) using (var controller2 = SCNParticlePropertyController.Create (animation)) { controllers.Position = controller1; - Assert.IsNotNull (controllers.Position, "Position should be set to first controller"); + Assert.That (controllers.Position, Is.Not.Null, "Position should be set to first controller"); controllers.Position = controller2; - Assert.IsNotNull (controllers.Position, "Position should be set to second controller"); + Assert.That (controllers.Position, Is.Not.Null, "Position should be set to second controller"); controllers.Position = null; - Assert.IsNull (controllers.Position, "Position should be null after clearing"); + Assert.That (controllers.Position, Is.Null, "Position should be null after clearing"); } } @@ -380,13 +380,13 @@ public void GetAnimationKeys () { using (var ps = SCNParticleSystem.Create ()) { var keys = ps.GetAnimationKeys (); - Assert.IsNotNull (keys, "GetAnimationKeys should return non-null"); - Assert.AreEqual (0, keys.Length, "Should have no animation keys initially"); + Assert.That (keys, Is.Not.Null, "GetAnimationKeys should return non-null"); + Assert.That (keys.Length, Is.EqualTo (0), "Should have no animation keys initially"); using (var animation = CAAnimation.CreateAnimation ()) { ps.AddAnimation (animation, "key1"); keys = ps.GetAnimationKeys (); - Assert.AreEqual (1, keys.Length, "Should have one animation key"); + Assert.That (keys.Length, Is.EqualTo (1), "Should have one animation key"); } } } @@ -399,11 +399,11 @@ public void RemoveAllAnimations () ps.AddAnimation (animation, "key1"); ps.AddAnimation (animation, "key2"); var keys = ps.GetAnimationKeys (); - Assert.AreEqual (2, keys.Length, "Should have two animation keys"); + Assert.That (keys.Length, Is.EqualTo (2), "Should have two animation keys"); ps.RemoveAllAnimations (); keys = ps.GetAnimationKeys (); - Assert.AreEqual (0, keys.Length, "Should have no animation keys after removal"); + Assert.That (keys.Length, Is.EqualTo (0), "Should have no animation keys after removal"); } } @@ -412,8 +412,8 @@ public void Copy () { using (var ps = SCNParticleSystem.Create ()) using (var copy = ps.Copy (null)) { - Assert.IsNotNull (copy, "Copy should return non-null"); - Assert.AreNotEqual (ps.Handle, copy.Handle, "Copy should have different handle"); + Assert.That (copy, Is.Not.Null, "Copy should return non-null"); + Assert.That (copy.Handle, Is.Not.EqualTo (ps.Handle), "Copy should have different handle"); } } @@ -423,13 +423,13 @@ public void NSCoding () using (var ps = SCNParticleSystem.Create ()) { // Test encoding/decoding var data = NSKeyedArchiver.GetArchivedData (ps, true, out var error); - Assert.IsNotNull (data, "Encoding should produce data"); - Assert.IsNull (error, "Encoding should not produce error"); + Assert.That (data, Is.Not.Null, "Encoding should produce data"); + Assert.That (error, Is.Null, "Encoding should not produce error"); var decoded = NSKeyedUnarchiver.GetUnarchivedObject (typeof (SCNParticleSystem), data, out error); - Assert.IsNotNull (decoded, "Decoding should produce object"); - Assert.IsNull (error, "Decoding should not produce error"); - Assert.IsInstanceOf (decoded, "Decoded object should be SCNParticleSystem"); + Assert.That (decoded, Is.Not.Null, "Decoding should produce object"); + Assert.That (error, Is.Null, "Decoding should not produce error"); + Assert.That (decoded, Is.InstanceOf (), "Decoded object should be SCNParticleSystem"); } } @@ -499,8 +499,8 @@ public void PropertyControllers_RoundTrip () ps.PropertyControllers = controllers; var retrieved = ps.PropertyControllers; - Assert.IsNotNull (retrieved, "Retrieved PropertyControllers should not be null"); - Assert.IsNotNull (retrieved.Position, "Retrieved Position controller should not be null"); + Assert.That (retrieved, Is.Not.Null, "Retrieved PropertyControllers should not be null"); + Assert.That (retrieved.Position, Is.Not.Null, "Retrieved Position controller should not be null"); } } } @@ -517,20 +517,20 @@ public void PropertyControllers_ClearAllProperties () controllers.Velocity = controller; controllers.Color = controller; - Assert.IsNotNull (controllers.Position, "Position should be set"); - Assert.IsNotNull (controllers.Angle, "Angle should be set"); - Assert.IsNotNull (controllers.Velocity, "Velocity should be set"); - Assert.IsNotNull (controllers.Color, "Color should be set"); + Assert.That (controllers.Position, Is.Not.Null, "Position should be set"); + Assert.That (controllers.Angle, Is.Not.Null, "Angle should be set"); + Assert.That (controllers.Velocity, Is.Not.Null, "Velocity should be set"); + Assert.That (controllers.Color, Is.Not.Null, "Color should be set"); controllers.Position = null; controllers.Angle = null; controllers.Velocity = null; controllers.Color = null; - Assert.IsNull (controllers.Position, "Position should be null"); - Assert.IsNull (controllers.Angle, "Angle should be null"); - Assert.IsNull (controllers.Velocity, "Velocity should be null"); - Assert.IsNull (controllers.Color, "Color should be null"); + Assert.That (controllers.Position, Is.Null, "Position should be null"); + Assert.That (controllers.Angle, Is.Null, "Angle should be null"); + Assert.That (controllers.Velocity, Is.Null, "Velocity should be null"); + Assert.That (controllers.Color, Is.Null, "Color should be null"); } } } diff --git a/tests/monotouch-test/SceneKit/SCNScene.cs b/tests/monotouch-test/SceneKit/SCNScene.cs index 4b62bba59439..0d7cfa1e7dfd 100644 --- a/tests/monotouch-test/SceneKit/SCNScene.cs +++ b/tests/monotouch-test/SceneKit/SCNScene.cs @@ -20,16 +20,16 @@ public void SCNSceneLoadingOptions_AnimationImportPolicyTest () [Test] public void SCNSceneLoadingOptions_AnimationImportPolicyTestKeysNonNull () { - Assert.IsNotNull (SCNSceneSourceLoading.AnimationImportPolicyPlay); - Assert.IsNotNull (SCNSceneSourceLoading.AnimationImportPolicyPlayRepeatedly); - Assert.IsNotNull (SCNSceneSourceLoading.AnimationImportPolicyDoNotPlay); - Assert.IsNotNull (SCNSceneSourceLoading.AnimationImportPolicyPlayUsingSceneTimeBase); + Assert.That (SCNSceneSourceLoading.AnimationImportPolicyPlay, Is.Not.Null); + Assert.That (SCNSceneSourceLoading.AnimationImportPolicyPlayRepeatedly, Is.Not.Null); + Assert.That (SCNSceneSourceLoading.AnimationImportPolicyDoNotPlay, Is.Not.Null); + Assert.That (SCNSceneSourceLoading.AnimationImportPolicyPlayUsingSceneTimeBase, Is.Not.Null); } void RoundTrip (SCNSceneLoadingOptions o, SCNAnimationImportPolicy policy) { o.AnimationImportPolicy = policy; - Assert.IsTrue (o.AnimationImportPolicy == policy); + Assert.That (o.AnimationImportPolicy, Is.EqualTo (policy)); } } } diff --git a/tests/monotouch-test/SceneKit/SCNViewTests.cs b/tests/monotouch-test/SceneKit/SCNViewTests.cs index cb466b007074..83d9fff31413 100644 --- a/tests/monotouch-test/SceneKit/SCNViewTests.cs +++ b/tests/monotouch-test/SceneKit/SCNViewTests.cs @@ -25,7 +25,7 @@ public void NullOverlaySceneTest () TestRuntime.AssertNotVirtualMachine (); var view = new SCNView (new CGRect (), (NSDictionary) null); - Assert.NotNull (view, "View not null"); + Assert.That (view, Is.Not.Null, "View not null"); Assert.DoesNotThrow (() => view.OverlayScene = null, "Should not throw"); } } diff --git a/tests/monotouch-test/SceneKit/SCNWorld.cs b/tests/monotouch-test/SceneKit/SCNWorld.cs index 2363589c73af..cef0a527c8a5 100644 --- a/tests/monotouch-test/SceneKit/SCNWorld.cs +++ b/tests/monotouch-test/SceneKit/SCNWorld.cs @@ -13,7 +13,7 @@ public class SCNWorldTests { public void SCNNode_BackfaceCulling () { if (IntPtr.Size == 8) { - Assert.IsNotNull (SCNPhysicsTestKeys.BackfaceCullingKey); + Assert.That (SCNPhysicsTestKeys.BackfaceCullingKey, Is.Not.Null); } } } diff --git a/tests/monotouch-test/SceneKit/SceneKit.cs b/tests/monotouch-test/SceneKit/SceneKit.cs index 6854897034d5..d9c4f1630862 100644 --- a/tests/monotouch-test/SceneKit/SceneKit.cs +++ b/tests/monotouch-test/SceneKit/SceneKit.cs @@ -15,21 +15,24 @@ public class SceneKitTests // Generic one off tests public void SCNGeometrySourceSemantic_ColorKeyTest () { NSString s = SCNGeometrySourceSemantic.Color; - Assert.IsTrue (s is not null && s != (NSString) (string.Empty)); + Assert.That (s, Is.Not.Null); + Assert.That (s, Is.Not.EqualTo ((NSString) (string.Empty))); } [Test] public void SCNPhysicsTestKeys_SearchModeKeyTest () { NSString s = SCNPhysicsTestKeys.SearchModeKey; - Assert.IsTrue (s is not null && s != (NSString) (string.Empty)); + Assert.That (s, Is.Not.Null); + Assert.That (s, Is.Not.EqualTo ((NSString) (string.Empty))); } [Test] public void SCNSceneSourceLoading_AnimationImportPolicyKeyTest () { NSString s = SCNSceneSourceLoading.AnimationImportPolicyKey; - Assert.IsTrue (s is not null && s != (NSString) (string.Empty)); + Assert.That (s, Is.Not.Null); + Assert.That (s, Is.Not.EqualTo ((NSString) (string.Empty))); } } } diff --git a/tests/monotouch-test/ScreenTime/STWebHistoryTest.cs b/tests/monotouch-test/ScreenTime/STWebHistoryTest.cs index e0756dad44ad..2fa6b305f5b0 100644 --- a/tests/monotouch-test/ScreenTime/STWebHistoryTest.cs +++ b/tests/monotouch-test/ScreenTime/STWebHistoryTest.cs @@ -22,8 +22,8 @@ public void Create_WithBundleIdentifier () { TestRuntime.AssertXcodeVersion (16, 3); using var obj = STWebHistory.Create ("com.xamarin.monotouch-test", out var error); - Assert.IsNotNull (obj, "Object"); - Assert.IsNull (error, "Error"); + Assert.That (obj, Is.Not.Null, "Object"); + Assert.That (error, Is.Null, "Error"); } [Test] @@ -31,8 +31,8 @@ public void Create_WithBundleIdentifierAndProfile () { TestRuntime.AssertXcodeVersion (16, 3); using var obj = STWebHistory.Create ("com.xamarin.monotouch-test", (NSString) "profile", out var error); - Assert.IsNotNull (obj, "Object"); - Assert.IsNull (error, "Error"); + Assert.That (obj, Is.Not.Null, "Object"); + Assert.That (error, Is.Null, "Error"); } } } diff --git a/tests/monotouch-test/ScriptingBridge/SBApplicationTest.cs b/tests/monotouch-test/ScriptingBridge/SBApplicationTest.cs index e266c8408915..7d2ee1372bb4 100644 --- a/tests/monotouch-test/ScriptingBridge/SBApplicationTest.cs +++ b/tests/monotouch-test/ScriptingBridge/SBApplicationTest.cs @@ -34,10 +34,10 @@ public void TestGetApplicationFromBundleIdentifier () using (var app2 = SBApplication.GetApplication (knownBundle)) using (var app3 = SBApplication.GetApplication (unknownBundle)) using (var app4 = SBApplication.GetApplication (unknownBundle)) { - Assert.IsNotNull (app1, "SBApplication from known bundle is null"); - Assert.IsNotNull (app2, "MySBApp from known bundle is null"); - Assert.IsNull (app3, "SBApplication from unknown bundle is non-null"); - Assert.IsNull (app4, "MySBApp from unknown bundle is non-null"); + Assert.That (app1, Is.Not.Null, "SBApplication from known bundle is null"); + Assert.That (app2, Is.Not.Null, "MySBApp from known bundle is null"); + Assert.That (app3, Is.Null, "SBApplication from unknown bundle is non-null"); + Assert.That (app4, Is.Null, "MySBApp from unknown bundle is non-null"); } } @@ -47,8 +47,8 @@ public void TestGetApplicationFromUrl () using (NSUrl knownUrl = new NSUrl ("http://www.xamarin.com")) using (var app1 = SBApplication.GetApplication (knownUrl)) using (var app2 = SBApplication.GetApplication (knownUrl)) { - Assert.IsNotNull (app1, "SBApplication from known URL is null"); - Assert.IsNotNull (app2, "MySBApp from known URL is null"); + Assert.That (app1, Is.Not.Null, "SBApplication from known URL is null"); + Assert.That (app2, Is.Not.Null, "MySBApp from known URL is null"); } } @@ -61,10 +61,10 @@ public void TestGetApplicationFromPid () using (var app2 = SBApplication.GetApplication (knownPid)) using (var app3 = SBApplication.GetApplication (unknownPid)) using (var app4 = SBApplication.GetApplication (unknownPid)) { - Assert.IsNotNull (app1, "SBApplication from known pid is null"); - Assert.IsNotNull (app2, "MySBApp from known pid is null"); - Assert.IsNotNull (app3, "SBApplication from unknown pid is null"); - Assert.IsNotNull (app4, "MySBApp from unknown pid is null"); + Assert.That (app1, Is.Not.Null, "SBApplication from known pid is null"); + Assert.That (app2, Is.Not.Null, "MySBApp from known pid is null"); + Assert.That (app3, Is.Not.Null, "SBApplication from unknown pid is null"); + Assert.That (app4, Is.Not.Null, "MySBApp from unknown pid is null"); } } } diff --git a/tests/monotouch-test/SearchKit/SearchKitTest.cs b/tests/monotouch-test/SearchKit/SearchKitTest.cs index 4be3afd5072a..0c7928bb05b7 100644 --- a/tests/monotouch-test/SearchKit/SearchKitTest.cs +++ b/tests/monotouch-test/SearchKit/SearchKitTest.cs @@ -48,11 +48,11 @@ public void TestCreate () using (var search = idx.Search ("some", SKSearchOptions.SpaceMeansOr)) { more = search.FindMatches (max, ref ids, ref scores, 1, out nfound); - Assert.IsFalse (more); + Assert.That (more, Is.False); for (nint i = 0; i < nfound; i++) { var doc = idx.GetDocument (ids [i]); - Assert.IsNotNull (doc, "TestCreate - GetDocument returned null"); + Assert.That (doc, Is.Not.Null, "TestCreate - GetDocument returned null"); } } @@ -70,7 +70,7 @@ public void TestCreate () // Now open idx = SKIndex.FromUrl (new NSUrl ("file://" + path), "myIndex", true); - Assert.NotNull (idx); + Assert.That (idx, Is.Not.Null); } @@ -79,14 +79,14 @@ public void TestInMemory () { var m = new NSMutableData (); var idx = SKIndex.CreateWithMutableData (m, "indexName", SKIndexType.Inverted, null); - Assert.NotNull (idx); + Assert.That (idx, Is.Not.Null); idx.AddDocumentWithText (new SKDocument (new NSUrl ("file:///etc/passwd")), "These are the contents of the passwd file, well, not really", true); idx.Flush (); idx.Compact (); idx.Close (); idx = SKIndex.FromMutableData (m, "indexName"); - Assert.NotNull (idx); + Assert.That (idx, Is.Not.Null); idx.Close (); } @@ -103,7 +103,7 @@ public void TestTextAnalysis () }; var idx = SKIndex.CreateWithMutableData (m, "indexName", SKIndexType.Inverted, properties); - Assert.NotNull (idx); + Assert.That (idx, Is.Not.Null); } @@ -115,42 +115,42 @@ public void TestSummary () "One day he ran into a solid rock in the park and was puzzled by it.\n\n" + "If I cook this rock enough, it will be soft and tasty. I might even get lucky and find some salt."); - Assert.NotNull (sum); + Assert.That (sum, Is.Not.Null); var rankOrder = new nint [10]; var sentenceIndex = new nint [10]; var paragraphIndex = new nint [10]; nint n; n = sum.GetSentenceSummaryInfo (10, rankOrder, sentenceIndex, paragraphIndex); - Assert.AreEqual ((nint) 4, n); - Assert.AreEqual ((nint) 2, paragraphIndex [3]); // 4th sentence (index 3) is on the 3rd (index 2) paragraph + Assert.That (n, Is.EqualTo ((nint) 4)); + Assert.That (paragraphIndex [3], Is.EqualTo ((nint) 2)); // 4th sentence (index 3) is on the 3rd (index 2) paragraph n = sum.GetSentenceSummaryInfo (10, null, sentenceIndex, paragraphIndex); - Assert.AreEqual ((nint) 4, n); + Assert.That (n, Is.EqualTo ((nint) 4)); n = sum.GetSentenceSummaryInfo (10, rankOrder, null, paragraphIndex); - Assert.AreEqual ((nint) 4, n); + Assert.That (n, Is.EqualTo ((nint) 4)); n = sum.GetSentenceSummaryInfo (10, rankOrder, sentenceIndex, null); - Assert.AreEqual ((nint) 4, n); + Assert.That (n, Is.EqualTo ((nint) 4)); n = sum.GetSentenceSummaryInfo (10, null, null, paragraphIndex); - Assert.AreEqual ((nint) 4, n); + Assert.That (n, Is.EqualTo ((nint) 4)); n = sum.GetSentenceSummaryInfo (10, null, sentenceIndex, null); - Assert.AreEqual ((nint) 4, n); + Assert.That (n, Is.EqualTo ((nint) 4)); n = sum.GetSentenceSummaryInfo (10, rankOrder, null, null); - Assert.AreEqual ((nint) 4, n); + Assert.That (n, Is.EqualTo ((nint) 4)); n = sum.GetSentenceSummaryInfo (10, null, null, null); - Assert.AreEqual ((nint) 4, n); + Assert.That (n, Is.EqualTo ((nint) 4)); n = sum.GetParagraphSummaryInfo (10, rankOrder, paragraphIndex); n = sum.GetParagraphSummaryInfo (10, null, paragraphIndex); n = sum.GetParagraphSummaryInfo (10, rankOrder, null); n = sum.GetParagraphSummaryInfo (10, null, null); var sentence = sum.GetSentence (3); - Assert.AreEqual ("I might even get lucky and find some salt.", sentence); + Assert.That (sentence, Is.EqualTo ("I might even get lucky and find some salt.")); var par = sum.GetParagraph (1); - Assert.AreEqual ("One day he ran into a solid rock in the park and was puzzled by it.\n", par); + Assert.That (par, Is.EqualTo ("One day he ran into a solid rock in the park and was puzzled by it.\n")); var ssum = sum.GetSentenceSummary (1); - Assert.NotNull (ssum); + Assert.That (ssum, Is.Not.Null); var psum = sum.GetParagraphSummary (1); - Assert.NotNull (psum); + Assert.That (psum, Is.Not.Null); } } } diff --git a/tests/monotouch-test/Security/CertificateTest.cs b/tests/monotouch-test/Security/CertificateTest.cs index dbe6d9b09555..d632eacbe1b8 100644 --- a/tests/monotouch-test/Security/CertificateTest.cs +++ b/tests/monotouch-test/Security/CertificateTest.cs @@ -284,25 +284,25 @@ void CheckMailGoogleCom (SecCertificate cert, nint expectedRetainCount) Assert.That (cert.GetSerialNumber ().ToStableString (), Is.EqualTo ("<72cd64e0 1fb60945 1085a390 91b53128>"), "GetSerialNumber"); var emailAddresses = cert.GetEmailAddresses (); - Assert.IsTrue (emailAddresses is null || emailAddresses.Length == 0, "GetEmailAddresses"); + Assert.That (emailAddresses is null || emailAddresses.Length == 0, Is.True, "GetEmailAddresses"); - Assert.NotNull (cert.GetNormalizedIssuerSequence (), "GetNormalizedIssuerSequence"); - Assert.NotNull (cert.GetNormalizedSubjectSequence (), "GetNormalizedSubjectSequence"); + Assert.That (cert.GetNormalizedIssuerSequence (), Is.Not.Null, "GetNormalizedIssuerSequence"); + Assert.That (cert.GetNormalizedSubjectSequence (), Is.Not.Null, "GetNormalizedSubjectSequence"); #if !__MACCATALYST__ - Assert.NotNull (cert.GetPublicKey (), "GetPublicKey"); + Assert.That (cert.GetPublicKey (), Is.Not.Null, "GetPublicKey"); #endif } if (TestRuntime.CheckXcodeVersion (9, 0)) { NSError err; Assert.That (cert.GetSerialNumber (out err).ToStableString (), Is.EqualTo ("<72cd64e0 1fb60945 1085a390 91b53128>"), "GetSerialNumber/NSError"); - Assert.Null (err, "err"); + Assert.That (err, Is.Null, "err"); } if (TestRuntime.CheckXcodeVersion (10, 0)) { - Assert.NotNull (cert.GetKey (), "GetKey"); + Assert.That (cert.GetKey (), Is.Not.Null, "GetKey"); } if (TestRuntime.CheckXcodeVersion (16, 0)) { - Assert.NotNull (cert.NotValidBeforeDate, "NotValidBeforeDate"); - Assert.NotNull (cert.NotValidAfterDate, "NotValidAfterDate"); + Assert.That (cert.NotValidBeforeDate, Is.Not.Null, "NotValidBeforeDate"); + Assert.That (cert.NotValidAfterDate, Is.Not.Null, "NotValidAfterDate"); } } diff --git a/tests/monotouch-test/Security/IdentityTest.cs b/tests/monotouch-test/Security/IdentityTest.cs index 32e03316aaac..5f5c5c2975ac 100644 --- a/tests/monotouch-test/Security/IdentityTest.cs +++ b/tests/monotouch-test/Security/IdentityTest.cs @@ -36,8 +36,8 @@ public void Create () public void Identity () { using (SecIdentity id = GetIdentity ()) { - Assert.NotNull (id.PrivateKey, "PrivateKey"); - Assert.NotNull (id.Certificate, "Certificate"); + Assert.That (id.PrivateKey, Is.Not.Null, "PrivateKey"); + Assert.That (id.Certificate, Is.Not.Null, "Certificate"); } } @@ -58,11 +58,11 @@ public void AccessCertificates () using (var i1 = GetIdentity ()) using (var i2 = new SecIdentity2 (i1, i1.Certificate)) { int call = 0; - Assert.True (i2.AccessCertificates ((c) => { + Assert.That (i2.AccessCertificates ((c) => { Assert.That (i1.Certificate.GetCommonName (), Is.EqualTo (c.Certificate.GetCommonName ()), "GetCommonName"); call++; - }), "Access"); + }), Is.True, "Access"); Assert.That (call, Is.EqualTo (1), "call"); } } @@ -74,7 +74,7 @@ public void Certificates () using var i1 = GetIdentity (); using var i2 = new SecIdentity2 (i1, i1.Certificate); var certs = i2.Certificates; - Assert.IsNotNull (certs, "Certificates"); + Assert.That (certs, Is.Not.Null, "Certificates"); Assert.That (certs!.Length, Is.GreaterThanOrEqualTo (1), "Certificates/length"); } } diff --git a/tests/monotouch-test/Security/ImportExportTest.cs b/tests/monotouch-test/Security/ImportExportTest.cs index e74e4163c7ae..0b9d2e79c5dd 100644 --- a/tests/monotouch-test/Security/ImportExportTest.cs +++ b/tests/monotouch-test/Security/ImportExportTest.cs @@ -45,7 +45,7 @@ public void P12_Success () Assert.That (x.Value, Is.TypeOf (typeof (NSObject)), "NSObject"); break; case "chain": - Assert.True (x.Value is NSArray, "NSArray"); + Assert.That (x.Value is NSArray, Is.True, "NSArray"); NSArray a = (x.Value as NSArray); Assert.That (a.Count, Is.EqualTo ((nuint) 1), "Count"); break; @@ -59,7 +59,7 @@ public void P12_Success () break; #endif default: - Assert.Fail ("Unexpected {0}", x.Key); + Assert.Fail ($"Unexpected {x.Key}"); break; } } diff --git a/tests/monotouch-test/Security/KeyChainTest.cs b/tests/monotouch-test/Security/KeyChainTest.cs index bd99664e3130..26d25b778d1a 100644 --- a/tests/monotouch-test/Security/KeyChainTest.cs +++ b/tests/monotouch-test/Security/KeyChainTest.cs @@ -75,14 +75,14 @@ public void AddQueryRemove_Identity () Assert.Inconclusive ("Test randomly fails (race condition between addtion/commit/query?"); Assert.That (code, Is.EqualTo (SecStatusCode.Success), "QueryAsRecord-2"); - Assert.NotNull (match, "match-2"); + Assert.That (match, Is.Not.Null, "match-2"); code = SecKeyChain.Remove (rec); Assert.That (code, Is.EqualTo (SecStatusCode.Success), "Remove"); match = SecKeyChain.QueryAsConcreteType (rec, out code); Assert.That (code, Is.EqualTo (SecStatusCode.ItemNotFound), "QueryAsRecord-3"); - Assert.Null (match, "match-3"); + Assert.That (match, Is.Null, "match-3"); } } @@ -160,7 +160,7 @@ public void QueryAsData () ); var data = SecKeyChain.QueryAsData (queryRec, true, out code); if (code == SecStatusCode.Success && queryRec is not null) { - Assert.NotNull (data.Bytes); + Assert.That (data.Bytes, Is.Not.Null); } } @@ -174,7 +174,7 @@ public void QueryAsDataArray () ); var data = SecKeyChain.QueryAsData (queryRec, true, 1, out code); if (code == SecStatusCode.Success && queryRec is not null) { - Assert.NotNull (data [0].Bytes); + Assert.That (data [0].Bytes, Is.Not.Null); } } diff --git a/tests/monotouch-test/Security/KeyTest.cs b/tests/monotouch-test/Security/KeyTest.cs index 9154ad663b81..851305bfd59a 100644 --- a/tests/monotouch-test/Security/KeyTest.cs +++ b/tests/monotouch-test/Security/KeyTest.cs @@ -121,21 +121,21 @@ public void RoundtripRSAMinPKCS1 () byte [] plain = new byte [20] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; byte [] cipher; if (TestRuntime.CheckXcodeVersion (8, 0)) { - Assert.True (public_key.IsAlgorithmSupported (SecKeyOperationType.Encrypt, SecKeyAlgorithm.RsaEncryptionPkcs1), "public/IsAlgorithmSupported/Encrypt"); + Assert.That (public_key.IsAlgorithmSupported (SecKeyOperationType.Encrypt, SecKeyAlgorithm.RsaEncryptionPkcs1), Is.True, "public/IsAlgorithmSupported/Encrypt"); #if MONOMAC - Assert.True (public_key.IsAlgorithmSupported (SecKeyOperationType.Decrypt, SecKeyAlgorithm.RsaEncryptionPkcs1), "public/IsAlgorithmSupported/Decrypt"); + Assert.That (public_key.IsAlgorithmSupported (SecKeyOperationType.Decrypt, SecKeyAlgorithm.RsaEncryptionPkcs1), Is.True, "public/IsAlgorithmSupported/Decrypt"); using (var pub = public_key.GetPublicKey ()) { // macOS behaviour is not consistent - but the test main goal is to check we get a key Assert.That (pub.Handle, Is.Not.EqualTo (IntPtr.Zero), "public/GetPublicKey"); } #else - Assert.True (public_key.IsAlgorithmSupported (SecKeyOperationType.Decrypt, SecKeyAlgorithm.RsaEncryptionPkcs1), "public/IsAlgorithmSupported/Decrypt"); + Assert.That (public_key.IsAlgorithmSupported (SecKeyOperationType.Decrypt, SecKeyAlgorithm.RsaEncryptionPkcs1), Is.True, "public/IsAlgorithmSupported/Decrypt"); using (var pub = public_key.GetPublicKey ()) { // a new native instance of the key is returned (so having a new managed SecKey is fine) - Assert.False (pub.Handle == public_key.Handle, "public/GetPublicKey"); + Assert.That (pub.Handle == public_key.Handle, Is.False, "public/GetPublicKey"); } #endif @@ -143,11 +143,11 @@ public void RoundtripRSAMinPKCS1 () Assert.That (attrs.Count, Is.GreaterThan ((nuint) 0), "public/GetAttributes"); } using (var data = public_key.GetExternalRepresentation (out error)) { - Assert.Null (error, "public/error-1"); - Assert.NotNull (data, "public/GetExternalRepresentation"); + Assert.That (error, Is.Null, "public/error-1"); + Assert.That (data, Is.Not.Null, "public/GetExternalRepresentation"); using (var key = SecKey.Create (data, SecKeyType.RSA, SecKeyClass.Public, MinRsaKeySize, null, out error)) { - Assert.Null (error, "public/Create/error-1"); + Assert.That (error, Is.Null, "public/Create/error-1"); } } } @@ -155,8 +155,8 @@ public void RoundtripRSAMinPKCS1 () byte [] result; if (TestRuntime.CheckXcodeVersion (8, 0)) { - Assert.False (private_key.IsAlgorithmSupported (SecKeyOperationType.Encrypt, SecKeyAlgorithm.RsaEncryptionPkcs1), "private/IsAlgorithmSupported/Encrypt"); - Assert.True (private_key.IsAlgorithmSupported (SecKeyOperationType.Decrypt, SecKeyAlgorithm.RsaEncryptionPkcs1), "private/IsAlgorithmSupported/Decrypt"); + Assert.That (private_key.IsAlgorithmSupported (SecKeyOperationType.Encrypt, SecKeyAlgorithm.RsaEncryptionPkcs1), Is.False, "private/IsAlgorithmSupported/Encrypt"); + Assert.That (private_key.IsAlgorithmSupported (SecKeyOperationType.Decrypt, SecKeyAlgorithm.RsaEncryptionPkcs1), Is.True, "private/IsAlgorithmSupported/Decrypt"); using (var pub2 = private_key.GetPublicKey ()) { #if MONOMAC @@ -172,11 +172,11 @@ public void RoundtripRSAMinPKCS1 () Assert.That (attrs.Count, Is.GreaterThan ((nuint) 0), "private/GetAttributes"); } using (var data2 = private_key.GetExternalRepresentation (out error)) { - Assert.Null (error, "private/error-1"); - Assert.NotNull (data2, "private/GetExternalRepresentation"); + Assert.That (error, Is.Null, "private/error-1"); + Assert.That (data2, Is.Not.Null, "private/GetExternalRepresentation"); using (var key = SecKey.Create (data2, SecKeyType.RSA, SecKeyClass.Private, MinRsaKeySize, null, out error)) { - Assert.Null (error, "private/Create/error-1"); + Assert.That (error, Is.Null, "private/Create/error-1"); } } } @@ -238,12 +238,12 @@ public void RoundtripRSA1024OAEP () byte [] plain = new byte [0]; byte [] cipher; if (TestRuntime.CheckXcodeVersion (8, 0)) { - Assert.True (public_key.IsAlgorithmSupported (SecKeyOperationType.Encrypt, SecKeyAlgorithm.RsaEncryptionOaepSha1), "public/IsAlgorithmSupported/Encrypt"); + Assert.That (public_key.IsAlgorithmSupported (SecKeyOperationType.Encrypt, SecKeyAlgorithm.RsaEncryptionOaepSha1), Is.True, "public/IsAlgorithmSupported/Encrypt"); // I would have expect false #if MONOMAC - Assert.True (public_key.IsAlgorithmSupported (SecKeyOperationType.Decrypt, SecKeyAlgorithm.RsaEncryptionOaepSha1), "public/IsAlgorithmSupported/Decrypt"); + Assert.That (public_key.IsAlgorithmSupported (SecKeyOperationType.Decrypt, SecKeyAlgorithm.RsaEncryptionOaepSha1), Is.True, "public/IsAlgorithmSupported/Decrypt"); #else - Assert.True (public_key.IsAlgorithmSupported (SecKeyOperationType.Decrypt, SecKeyAlgorithm.RsaEncryptionOaepSha1), "public/IsAlgorithmSupported/Decrypt"); + Assert.That (public_key.IsAlgorithmSupported (SecKeyOperationType.Decrypt, SecKeyAlgorithm.RsaEncryptionOaepSha1), Is.True, "public/IsAlgorithmSupported/Decrypt"); #endif } Assert.That (public_key.Encrypt (SecPadding.OAEP, plain, out cipher), Is.EqualTo (SecStatusCode.Success), "Encrypt"); @@ -251,8 +251,8 @@ public void RoundtripRSA1024OAEP () byte [] result; if (TestRuntime.CheckXcodeVersion (8, 0)) { - Assert.False (private_key.IsAlgorithmSupported (SecKeyOperationType.Encrypt, SecKeyAlgorithm.RsaEncryptionOaepSha1), "private/IsAlgorithmSupported/Encrypt"); - Assert.True (private_key.IsAlgorithmSupported (SecKeyOperationType.Decrypt, SecKeyAlgorithm.RsaEncryptionOaepSha1), "private/IsAlgorithmSupported/Decrypt"); + Assert.That (private_key.IsAlgorithmSupported (SecKeyOperationType.Encrypt, SecKeyAlgorithm.RsaEncryptionOaepSha1), Is.False, "private/IsAlgorithmSupported/Encrypt"); + Assert.That (private_key.IsAlgorithmSupported (SecKeyOperationType.Decrypt, SecKeyAlgorithm.RsaEncryptionOaepSha1), Is.True, "private/IsAlgorithmSupported/Decrypt"); } Assert.That (private_key.Decrypt (SecPadding.OAEP, cipher, out result), Is.EqualTo (SecStatusCode.Success), "Decrypt"); Assert.That (plain, Is.EqualTo (result), "match"); @@ -381,7 +381,7 @@ public void BenchmarkManaged4096 () var chrono = new Stopwatch (); chrono.Start (); var rsa = new RSACryptoServiceProvider (4096); - Assert.IsNotNull (rsa.ExportParameters (true), "ExportParameters"); // that will provoke the key generation + Assert.That (rsa.ExportParameters (true), Is.Not.Null, "ExportParameters"); // that will provoke the key generation Console.WriteLine ("Key generation {0} ms", chrono.ElapsedMilliseconds); chrono.Restart (); @@ -454,26 +454,26 @@ public void RSA () TestRuntime.AssertXcodeVersion (8, 0); NSError error; using (var key = SecKey.CreateRandomKey (SecKeyType.RSA, MinRsaKeySize, null, out error)) { - Assert.Null (error, "RSA/error"); + Assert.That (error, Is.Null, "RSA/error"); using (var data = NSData.FromArray (new byte [] { 1, 2, 3 })) { using (var sig = key.CreateSignature (SecKeyAlgorithm.RsaSignatureRaw, data, out error)) { - Assert.Null (error, "Sign/error"); + Assert.That (error, Is.Null, "Sign/error"); using (var pub = key.GetPublicKey ()) { var result = pub.VerifySignature (SecKeyAlgorithm.RsaSignatureRaw, data, sig, out error); - Assert.Null (error, "Verify/no-error"); - Assert.True (result, "Verify/true"); + Assert.That (error, Is.Null, "Verify/no-error"); + Assert.That (result, Is.True, "Verify/true"); result = pub.VerifySignature (SecKeyAlgorithm.RsaSignatureRaw, data, data, out error); - Assert.NotNull (error, "Verify/error"); - Assert.False (result, "Verify/false"); + Assert.That (error, Is.Not.Null, "Verify/error"); + Assert.That (result, Is.False, "Verify/false"); using (var cipher = pub.CreateEncryptedData (SecKeyAlgorithm.RsaEncryptionPkcs1, data, out error)) { - Assert.Null (error, "Encrypt/error"); + Assert.That (error, Is.Null, "Encrypt/error"); using (var plain = key.CreateDecryptedData (SecKeyAlgorithm.RsaEncryptionPkcs1, cipher, out error)) { - Assert.Null (error, "Decrypt/error"); + Assert.That (error, Is.Null, "Decrypt/error"); Assert.That (data.ToArray (), Is.EqualTo (plain.ToArray ()), "roundtrip"); } @@ -487,15 +487,15 @@ public void RSA () if (badDecrypt) { // on macOS this fails with CSSMERR_CSP_INPUT_LENGTH_ERROR (I haven't checked on iOS/tvOS) // but on Mac Catalyst apps on Sonoma this succeeds... which means Mac Catalyst can decrypt random data? the returned data looks random too. 🤷‍♂️ - Assert.Null (key.CreateDecryptedData (SecKeyAlgorithm.RsaEncryptionPkcs1, data, out error), "bad data"); - Assert.NotNull (error, "bad decrypt"); + Assert.That (key.CreateDecryptedData (SecKeyAlgorithm.RsaEncryptionPkcs1, data, out error), Is.Null, "bad data"); + Assert.That (error, Is.Not.Null, "bad decrypt"); } } } } using (var sig = key.CreateSignature (SecKeyAlgorithm.EcdsaSignatureRfc4754, data, out error)) { - Assert.NotNull (error, "wrong key type"); + Assert.That (error, Is.Not.Null, "wrong key type"); } } } @@ -507,36 +507,36 @@ public void EC () TestRuntime.AssertXcodeVersion (8, 0); NSError error; using (var key = SecKey.CreateRandomKey (SecKeyType.EC, 384, null, out error)) { - Assert.Null (error, "EC/error"); + Assert.That (error, Is.Null, "EC/error"); using (var data = NSData.FromArray (new byte [] { 1, 2, 3 })) { using (var sig = key.CreateSignature (SecKeyAlgorithm.EcdsaSignatureRfc4754, data, out error)) { - Assert.Null (error, "Sign/error"); + Assert.That (error, Is.Null, "Sign/error"); using (var pub = key.GetPublicKey ()) { var result = pub.VerifySignature (SecKeyAlgorithm.EcdsaSignatureRfc4754, data, sig, out error); - Assert.Null (error, "Verify/no-error"); - Assert.True (result, "Verify/true"); + Assert.That (error, Is.Null, "Verify/no-error"); + Assert.That (result, Is.True, "Verify/true"); result = pub.VerifySignature (SecKeyAlgorithm.EcdsaSignatureRfc4754, data, data, out error); - Assert.NotNull (error, "Verify/error"); - Assert.False (result, "Verify/false"); + Assert.That (error, Is.Not.Null, "Verify/error"); + Assert.That (result, Is.False, "Verify/false"); using (var cipher = pub.CreateEncryptedData (SecKeyAlgorithm.EciesEncryptionCofactorX963Sha1AesGcm, data, out error)) { - Assert.Null (error, "Encrypt/error"); + Assert.That (error, Is.Null, "Encrypt/error"); using (var plain = key.CreateDecryptedData (SecKeyAlgorithm.EciesEncryptionCofactorX963Sha1AesGcm, cipher, out error)) { - Assert.Null (error, "Decrypt/error"); + Assert.That (error, Is.Null, "Decrypt/error"); Assert.That (data.ToArray (), Is.EqualTo (plain.ToArray ()), "roundtrip"); } - Assert.Null (key.CreateDecryptedData (SecKeyAlgorithm.EciesEncryptionCofactorX963Sha1AesGcm, data, out error), "bad data"); - Assert.NotNull (error, "bad decrypt"); + Assert.That (key.CreateDecryptedData (SecKeyAlgorithm.EciesEncryptionCofactorX963Sha1AesGcm, data, out error), Is.Null, "bad data"); + Assert.That (error, Is.Not.Null, "bad decrypt"); } } } using (var sig = key.CreateSignature (SecKeyAlgorithm.RsaSignatureRaw, data, out error)) { - Assert.NotNull (error, "wrong key type"); + Assert.That (error, Is.Not.Null, "wrong key type"); } } } @@ -548,7 +548,7 @@ public void ECSecPrimeRandom () TestRuntime.AssertXcodeVersion (8, 0); NSError error; using (var key = SecKey.CreateRandomKey (SecKeyType.ECSecPrimeRandom, 384, null, out error)) { - Assert.Null (error, "ECSecPrimeRandom/error"); + Assert.That (error, Is.Null, "ECSecPrimeRandom/error"); SecKeyKeyExchangeParameter p = new SecKeyKeyExchangeParameter () { RequestedSize = 16, @@ -557,7 +557,7 @@ public void ECSecPrimeRandom () using (var pub = key.GetPublicKey ()) using (var ex = key.GetKeyExchangeResult (SecKeyAlgorithm.EcdhKeyExchangeStandardX963Sha512, pub, p.Dictionary, out error)) { - Assert.Null (error, "GetKeyExchangeResult/error"); + Assert.That (error, Is.Null, "GetKeyExchangeResult/error"); Assert.That (ex.Length, Is.EqualTo ((nuint) p.RequestedSize), "GetKeyExchangeResult/result"); } } diff --git a/tests/monotouch-test/Security/ProtocolOptionsTest.cs b/tests/monotouch-test/Security/ProtocolOptionsTest.cs index c383657bc71e..b3d0aeabc37b 100644 --- a/tests/monotouch-test/Security/ProtocolOptionsTest.cs +++ b/tests/monotouch-test/Security/ProtocolOptionsTest.cs @@ -33,13 +33,13 @@ public void Equals () using (var npo = new NWProtocolTlsOptions ()) { var options = npo.ProtocolOptions; - Assert.True (SecProtocolOptions.Equals (null, null), "1"); - Assert.True (SecProtocolOptions.Equals (options, options), "2"); - Assert.False (SecProtocolOptions.Equals (null, options), "3"); - Assert.False (SecProtocolOptions.Equals (options, null), "4"); + Assert.That (SecProtocolOptions.Equals (null, null), Is.True, "1"); + Assert.That (SecProtocolOptions.Equals (options, options), Is.True, "2"); + Assert.That (SecProtocolOptions.Equals (null, options), Is.False, "3"); + Assert.That (SecProtocolOptions.Equals (options, null), Is.False, "4"); - Assert.True (options.Equals (options), "5"); - Assert.False (options.Equals (null), "6"); + Assert.That (options.Equals (options), Is.True, "5"); + Assert.That (options.Equals (null), Is.False, "6"); } } diff --git a/tests/monotouch-test/Security/RecordTest.cs b/tests/monotouch-test/Security/RecordTest.cs index 314cb4fe31fb..b691a523cb9d 100644 --- a/tests/monotouch-test/Security/RecordTest.cs +++ b/tests/monotouch-test/Security/RecordTest.cs @@ -113,7 +113,7 @@ public void Identity () if (hasIdnt) Assert.That (dict ["class"].ToString (), Is.EqualTo ("idnt"), "idnt"); else - Assert.Null (dict ["class"], "idnt"); + Assert.That (dict ["class"], Is.Null, "idnt"); } } @@ -145,13 +145,13 @@ public void Match () var rec = CreateSecRecord (SecKind.GenericPassword, account: "Username" ); - Assert.Null (rec.MatchIssuers, "MatchIssuers"); + Assert.That (rec.MatchIssuers, Is.Null, "MatchIssuers"); // we do not have a way (except the getter) to craete SecKeyChain instances - Assert.Null (rec.MatchItemList, "MatchItemList"); + Assert.That (rec.MatchItemList, Is.Null, "MatchItemList"); using (var data = new NSData ()) { rec.MatchIssuers = new NSData [] { data }; - Assert.AreSame (rec.MatchIssuers [0], data, "MatchIssuers [0]"); + Assert.That (data, Is.SameAs (rec.MatchIssuers [0]), "MatchIssuers [0]"); } if (!TestRuntime.CheckXcodeVersion (7, 0)) @@ -327,27 +327,27 @@ public void DeskCase_83099_InmutableDictionary () try { //TEST 1: Save a keychain value var test1 = SaveKeychainEntry (testServer, testUsername, "testValue1", out var queryCode, out var addCode, out var updateCode); - Assert.IsTrue (test1, $"Password could not be saved to keychain. queryCode: {queryCode} addCode: {addCode} updateCode: {updateCode}"); + Assert.That (test1, Is.True, $"Password could not be saved to keychain. queryCode: {queryCode} addCode: {addCode} updateCode: {updateCode}"); //TEST 2: Get the saved keychain value var test2 = GetKeychainEntry (testServer, testUsername); - Assert.IsTrue (StringUtil.StringsEqual (test2, "testValue1", false)); + Assert.That (test2, Is.EqualTo ("testValue1")); //TEST 3: Update the keychain value var test3 = SaveKeychainEntry (testServer, testUsername, "testValue2", out queryCode, out addCode, out updateCode); - Assert.IsTrue (test3, $"Password could not be saved to keychain. queryCode: {queryCode} addCode: {addCode} updateCode: {updateCode}"); + Assert.That (test3, Is.True, $"Password could not be saved to keychain. queryCode: {queryCode} addCode: {addCode} updateCode: {updateCode}"); //TEST 4: Get the updated keychain value var test4 = GetKeychainEntry (testServer, testUsername); - Assert.IsTrue (StringUtil.StringsEqual (test4, "testValue2", false)); + Assert.That (test4, Is.EqualTo ("testValue2")); //TEST 5: Clear the keychain values var test5 = ClearKeychainEntry (testServer, testUsername, out queryCode, out var removeCode); - Assert.IsTrue (test5, $"Password could not be cleared from keychain. queryCode: {queryCode} removeCode: {removeCode}"); + Assert.That (test5, Is.True, $"Password could not be cleared from keychain. queryCode: {queryCode} removeCode: {removeCode}"); //TEST 6: Verify no keychain value var test6 = GetKeychainEntry (testServer, testUsername); - Assert.IsNull (test6, "No password should exist here"); + Assert.That (test6, Is.Null, "No password should exist here"); } finally { // Always clean up to avoid leaving stale entries for subsequent runs ForceRemoveKeychainEntry (testServer, testUsername); @@ -437,10 +437,10 @@ public void IdentityRecordTest () using (var identity = IdentityTest.GetIdentity ()) using (var rec = CreateSecRecord (identity)) { SecStatusCode code = SecKeyChain.Add (rec); - Assert.True (code == SecStatusCode.DuplicateItem || code == SecStatusCode.Success, "Identity added"); + Assert.That (code == SecStatusCode.DuplicateItem || code == SecStatusCode.Success, Is.True, "Identity added"); var ret = rec.GetIdentity (); - Assert.NotNull (ret, "ret is null"); + Assert.That (ret, Is.Not.Null, "ret is null"); Assert.That (identity.Handle, Is.EqualTo (ret.Handle), "Same Handle"); Assert.Throws (() => rec.GetKey (), "GetKey should throw"); @@ -455,7 +455,7 @@ public void SecRecordRecordTest () using (var cert = X509CertificateLoader.LoadCertificate (CertificateTest.mail_google_com)) using (var sc = new SecCertificate (cert)) using (var rec = CreateSecRecord (sc)) { - Assert.NotNull (rec, "rec is null"); + Assert.That (rec, Is.Not.Null, "rec is null"); var ret = rec.GetCertificate (); Assert.That (ret.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); @@ -475,7 +475,7 @@ public void KeyRecordTest () trust.Evaluate (); using (SecKey pubkey = trust.GetPublicKey ()) using (var rec = CreateSecRecord (pubkey)) { - Assert.NotNull (rec, "rec is null"); + Assert.That (rec, Is.Not.Null, "rec is null"); var ret = rec.GetKey (); Assert.That (ret.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); diff --git a/tests/monotouch-test/Security/SecProtocolMetadataTest.cs b/tests/monotouch-test/Security/SecProtocolMetadataTest.cs index b83a6b73586b..58210ced9ada 100644 --- a/tests/monotouch-test/Security/SecProtocolMetadataTest.cs +++ b/tests/monotouch-test/Security/SecProtocolMetadataTest.cs @@ -59,13 +59,13 @@ public void TlsDefaults () using (var m = connection.GetProtocolMetadata (NWProtocolDefinition.CreateTlsDefinition ())) { var s = m.SecProtocolMetadata; - Assert.False (s.EarlyDataAccepted, "EarlyDataAccepted"); - Assert.Null (s.NegotiatedProtocol, "NegotiatedProtocol"); + Assert.That (s.EarlyDataAccepted, Is.False, "EarlyDataAccepted"); + Assert.That (s.NegotiatedProtocol, Is.Null, "NegotiatedProtocol"); Assert.That (s.NegotiatedProtocolVersion, Is.EqualTo (SslProtocol.Tls_1_2).Or.EqualTo (SslProtocol.Tls_1_3), "NegotiatedProtocolVersion"); Assert.That (s.PeerPublicKey, Is.Null.Or.Not.Null, "PeerPublicKey"); - Assert.True (SecProtocolMetadata.ChallengeParametersAreEqual (s, s), "ChallengeParametersAreEqual"); - Assert.True (SecProtocolMetadata.PeersAreEqual (s, s), "PeersAreEqual"); + Assert.That (SecProtocolMetadata.ChallengeParametersAreEqual (s, s), Is.True, "ChallengeParametersAreEqual"); + Assert.That (SecProtocolMetadata.PeersAreEqual (s, s), Is.True, "PeersAreEqual"); if (TestRuntime.CheckXcodeVersion (11, 0)) { using (var d = s.CreateSecret ("Xamarin", 128)) { @@ -80,7 +80,7 @@ public void TlsDefaults () Assert.That (s.NegotiatedTlsCipherSuite, Is.Not.EqualTo (0), "NegotiatedTlsCipherSuite"); Assert.That (s.ServerName, Is.EqualTo ("www.microsoft.com"), "ServerName"); // we don't have a TLS-PSK enabled server to test this - Assert.False (s.AccessPreSharedKeys ((psk, pskId) => { }), "AccessPreSharedKeys"); + Assert.That (s.AccessPreSharedKeys ((psk, pskId) => { }), Is.False, "AccessPreSharedKeys"); } } diff --git a/tests/monotouch-test/Security/SecSharedCredentialTest.cs b/tests/monotouch-test/Security/SecSharedCredentialTest.cs index f1bf50ba6905..11e0667623eb 100644 --- a/tests/monotouch-test/Security/SecSharedCredentialTest.cs +++ b/tests/monotouch-test/Security/SecSharedCredentialTest.cs @@ -44,9 +44,7 @@ public void AddSharedWebCredentialNullAccount () } [Test] - // We do not want to block for a long period of time if the event is not set. // We are testing the fact that the trampoline works. - [Timeout (5000)] public void AddSharedWebCredentialNotNullPassword () { Action handler = (NSError e) => { @@ -56,9 +54,7 @@ public void AddSharedWebCredentialNotNullPassword () } [Test] - // We do not want to block for a long period of time if the event is not set. // We are testing the fact that the trampoline works. - [Timeout (5000)] public void AddSharedWebCredentialNullPassword () { password = null; @@ -69,9 +65,7 @@ public void AddSharedWebCredentialNullPassword () } [Test] - // We do not want to block for a long period of time if the event is not set. // We are testing the fact that the trampoline works. - [Timeout (5000)] public void RequestSharedWebCredentialTest () { Action handler = (SecSharedCredentialInfo [] creds, NSError e) => { @@ -81,9 +75,7 @@ public void RequestSharedWebCredentialTest () } [Test] - // We do not want to block for a long period of time if the event is not set. // We are testing the fact that the trampoline works. - [Timeout (5000)] public void RequestSharedWebCredentialNullDomainAndAccountTest () { Action handler = (SecSharedCredentialInfo [] creds, NSError e) => { @@ -96,7 +88,7 @@ public void RequestSharedWebCredentialNullDomainAndAccountTest () public void CreateSharedWebCredentialPassword () { var pwd = SecSharedCredential.CreateSharedWebCredentialPassword (); - Assert.IsNotNull (pwd); + Assert.That (pwd, Is.Not.Null); } } diff --git a/tests/monotouch-test/Security/SecStatusCodeTest.cs b/tests/monotouch-test/Security/SecStatusCodeTest.cs index ceb32a0938b2..eeff345d1a11 100644 --- a/tests/monotouch-test/Security/SecStatusCodeTest.cs +++ b/tests/monotouch-test/Security/SecStatusCodeTest.cs @@ -22,7 +22,7 @@ public void ErrorDescriptionTest () TestRuntime.AssertXcodeVersion (9, 3); var desc = SecStatusCode.Success.GetStatusDescription (); - Assert.NotNull (desc, $"{nameof (desc)} not null"); + Assert.That (desc, Is.Not.Null, $"{nameof (desc)} not null"); var noErr = "No error."; Assert.That (desc, Is.EqualTo (noErr), $"{nameof (desc)} == {noErr}"); diff --git a/tests/monotouch-test/Security/SecureTransportTest.cs b/tests/monotouch-test/Security/SecureTransportTest.cs index 79b9f89467f4..91b088cf0647 100644 --- a/tests/monotouch-test/Security/SecureTransportTest.cs +++ b/tests/monotouch-test/Security/SecureTransportTest.cs @@ -34,7 +34,7 @@ public void StreamDefaults () using (var ssl = new SslContext (SslProtocolSide.Client, SslConnectionType.Stream)) { Assert.That (ssl.BufferedReadSize, Is.EqualTo ((nint) 0), "BufferedReadSize"); Assert.That (ssl.ClientCertificateState, Is.EqualTo (SslClientCertificateState.None), "ClientCertificateState"); - Assert.Null (ssl.Connection, "Connection"); + Assert.That (ssl.Connection, Is.Null, "Connection"); Assert.That (ssl.DatagramWriteSize, Is.EqualTo ((nint) 0), "DatagramWriteSize"); Assert.That (ssl.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); Assert.That (ssl.MaxDatagramRecordSize, Is.EqualTo ((nint) 0), "MaxDatagramRecordSize"); @@ -51,7 +51,7 @@ public void StreamDefaults () ssl.PeerDomainName = null; Assert.That (ssl.PeerDomainName, Is.Empty, "PeerDomainName"); - Assert.Null (ssl.PeerId, "PeerId"); + Assert.That (ssl.PeerId, Is.Null, "PeerId"); ssl.PeerId = new byte [] { 0xff }; Assert.That (ssl.PeerId.Length, Is.EqualTo (1), "1a"); @@ -63,12 +63,12 @@ public void StreamDefaults () ssl.PeerId = new byte [] { 0x01, 0x02 }; Assert.That (ssl.PeerId.Length, Is.EqualTo (2), "2"); - Assert.Null (ssl.PeerTrust, "PeerTrust"); + Assert.That (ssl.PeerTrust, Is.Null, "PeerTrust"); Assert.That (ssl.SessionState, Is.EqualTo (SslSessionState.Idle), "SessionState"); Assert.That ((int) ssl.SetDatagramHelloCookie (new byte [32]), Is.EqualTo (-50), "no cookie in stream"); - // Assert.Null (ssl.GetDistinguishedNames (), "GetDistinguishedNames"); + // Assert.That (ssl.GetDistinguishedNames (), Is.Null, "GetDistinguishedNames"); if (TestRuntime.CheckXcodeVersion (9, 0)) { Assert.That (ssl.SetSessionTickets (false), Is.EqualTo (0), "SetSessionTickets"); @@ -104,14 +104,14 @@ public void DatagramDefaults () #endif using (var ssl = new SslContext (SslProtocolSide.Client, SslConnectionType.Datagram)) { Assert.That (ssl.BufferedReadSize, Is.EqualTo ((nint) 0), "BufferedReadSize"); - Assert.Null (ssl.Connection, "Connection"); + Assert.That (ssl.Connection, Is.Null, "Connection"); Assert.That (ssl.DatagramWriteSize, Is.EqualTo (dsize), "DatagramWriteSize"); Assert.That (ssl.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); Assert.That (ssl.MaxDatagramRecordSize, Is.EqualTo ((nint) 1400), "MaxDatagramRecordSize"); Assert.That (ssl.MaxProtocol, Is.EqualTo (SslProtocol.Dtls_1_0), "MaxProtocol"); Assert.That (ssl.MinProtocol, Is.EqualTo (SslProtocol.Dtls_1_0), "MinProtocol"); Assert.That (ssl.NegotiatedProtocol, Is.EqualTo (SslProtocol.Unknown), "NegotiatedProtocol"); - Assert.Null (ssl.PeerId, "PeerId"); + Assert.That (ssl.PeerId, Is.Null, "PeerId"); Assert.That (ssl.SessionState, Is.EqualTo (SslSessionState.Idle), "SessionState"); ssl.PeerId = new byte [] { 0xff }; @@ -130,45 +130,55 @@ public void DatagramDefaults () [Test] public void Tls12 () { - var client = new TcpClient ("google.ca", 443); - using (NetworkStream ns = client.GetStream ()) - using (var ssl = new SslContext (SslProtocolSide.Client, SslConnectionType.Stream)) { - - ssl.MinProtocol = SslProtocol.Tls_1_2; - Assert.That (ssl.MinProtocol, Is.EqualTo (SslProtocol.Tls_1_2), "MinProtocol"); - - ssl.Connection = new SslStreamConnection (ns); - - var result = ssl.Handshake (); - while (result == SslStatus.WouldBlock || result == (SslStatus) (-108)) { - // we need to ask again - but if we're too fast we'll get -108 (errSecAllocate) - Thread.Sleep (100); - // during the above call SessionState is Handshake - Assert.That (ssl.SessionState, Is.EqualTo (SslSessionState.Handshake), "Handshake/in progress"); - result = ssl.Handshake (); - } - Assert.That (result, Is.EqualTo (SslStatus.Success), "Handshake/done"); + try { + var client = new TcpClient ("google.ca", 443); + using (NetworkStream ns = client.GetStream ()) + using (var ssl = new SslContext (SslProtocolSide.Client, SslConnectionType.Stream)) { + + ssl.MinProtocol = SslProtocol.Tls_1_2; + Assert.That (ssl.MinProtocol, Is.EqualTo (SslProtocol.Tls_1_2), "MinProtocol"); + + ssl.Connection = new SslStreamConnection (ns); + + var deadline = DateTime.UtcNow.AddSeconds (30); + var result = ssl.Handshake (); + while (result == SslStatus.WouldBlock || result == (SslStatus) errSecAllocate) { + Assert.That (DateTime.UtcNow, Is.LessThan (deadline), "Handshake/timeout"); + // we need to ask again - but if we're too fast we'll get errSecAllocate + Thread.Sleep (100); + // during the above call SessionState is Handshake + Assert.That (ssl.SessionState, Is.EqualTo (SslSessionState.Handshake), "Handshake/in progress"); + result = ssl.Handshake (); + } + Assert.That (result, Is.EqualTo (SslStatus.Success), "Handshake/done"); - // FIXME: iOS 8 beta 1 bug ?!? the state is not updated (maybe delayed?) but the code still works - //Assert.That (ssl.SessionState, Is.EqualTo (SslSessionState.Connected), "Connected"); - Assert.That (ssl.NegotiatedProtocol, Is.EqualTo (SslProtocol.Tls_1_2), "NegotiatedProtocol"); + // FIXME: iOS 8 beta 1 bug ?!? the state is not updated (maybe delayed?) but the code still works + //Assert.That (ssl.SessionState, Is.EqualTo (SslSessionState.Connected), "Connected"); + Assert.That (ssl.NegotiatedProtocol, Is.EqualTo (SslProtocol.Tls_1_2), "NegotiatedProtocol"); - nint processed; - var data = Encoding.UTF8.GetBytes ("GET / HTTP/1.0" + Environment.NewLine + Environment.NewLine); - result = ssl.Write (data, out processed); - Assert.That (processed, Is.EqualTo ((nint) data.Length), "small buffer"); - Assert.That (result, Is.EqualTo (SslStatus.Success), "Write"); + nint processed; + var data = Encoding.UTF8.GetBytes ("GET / HTTP/1.0" + Environment.NewLine + Environment.NewLine); + result = ssl.Write (data, out processed); + Assert.That (processed, Is.EqualTo ((nint) data.Length), "small buffer"); + Assert.That (result, Is.EqualTo (SslStatus.Success), "Write"); - data = new byte [1024]; - result = ssl.Read (data, out processed); - while (result == SslStatus.WouldBlock) + data = new byte [1024]; + deadline = DateTime.UtcNow.AddSeconds (30); result = ssl.Read (data, out processed); - Assert.That (result, Is.EqualTo (SslStatus.Success), "Read"); + while (result == SslStatus.WouldBlock) { + Assert.That (DateTime.UtcNow, Is.LessThan (deadline), "Read/timeout"); + result = ssl.Read (data, out processed); + } + Assert.That (result, Is.EqualTo (SslStatus.Success), "Read"); - string s = Encoding.UTF8.GetString (data, 0, (int) processed); - // The result apparently depends on where you are: I get a 302, the bots get a 200. - // Also sometimes it fails with 502 Bad Gateway on the bots - Assert.That (s, Does.StartWith ("HTTP/1.0 302 Found").Or.StartWith ("HTTP/1.0 200 OK").Or.StartWith ("HTTP/1.0 502 Bad Gateway"), "response"); + string s = Encoding.UTF8.GetString (data, 0, (int) processed); + // The result apparently depends on where you are: I get a 302, the bots get a 200. + // Also sometimes it fails with 502 Bad Gateway on the bots + Assert.That (s, Does.StartWith ("HTTP/1.0 302 Found").Or.StartWith ("HTTP/1.0 200 OK").Or.StartWith ("HTTP/1.0 502 Bad Gateway"), "response"); + } + } catch (Exception ex) { + TestRuntime.IgnoreInCIIfBadNetwork (ex); + throw; } } } diff --git a/tests/monotouch-test/Security/TrustTest.cs b/tests/monotouch-test/Security/TrustTest.cs index 61ab56615a13..a6874e027743 100644 --- a/tests/monotouch-test/Security/TrustTest.cs +++ b/tests/monotouch-test/Security/TrustTest.cs @@ -88,7 +88,7 @@ void Trust_Leaf_Only (SecTrust trust, SecPolicy policy) }); Assert.That (err, Is.EqualTo (SecStatusCode.Success), "async1/err"); TestRuntime.RunAsync (TimeSpan.FromSeconds (5), called.Task); - Assert.True (assert, "async1"); + Assert.That (assert, Is.True, "async1"); } if (TestRuntime.CheckXcodeVersion (11, 0)) { @@ -101,7 +101,7 @@ void Trust_Leaf_Only (SecTrust trust, SecPolicy policy) }); Assert.That (err, Is.EqualTo (SecStatusCode.Success), "async2/err"); TestRuntime.RunAsync (TimeSpan.FromSeconds (5), called.Task); - Assert.True (assert, "async2"); + Assert.That (assert, Is.True, "async2"); } } @@ -111,9 +111,9 @@ void Trust_Leaf_Only (SecTrust trust, SecPolicy policy) var hasNetworkFetchAllowed = TestRuntime.CheckXcodeVersion (5, 0); #endif if (hasNetworkFetchAllowed) { - Assert.True (trust.NetworkFetchAllowed, "NetworkFetchAllowed-1"); + Assert.That (trust.NetworkFetchAllowed, Is.True, "NetworkFetchAllowed-1"); trust.NetworkFetchAllowed = false; - Assert.False (trust.NetworkFetchAllowed, "NetworkFetchAllowed-2"); + Assert.That (trust.NetworkFetchAllowed, Is.False, "NetworkFetchAllowed-2"); trust.SetPolicy (policy); @@ -206,7 +206,7 @@ public void Client_Leaf_Only () #endif if (hasGetResult) { // by default there's no *custom* anchors - Assert.Null (trust.GetCustomAnchorCertificates (), "GetCustomAnchorCertificates"); + Assert.That (trust.GetCustomAnchorCertificates (), Is.Null, "GetCustomAnchorCertificates"); using (var results = trust.GetResult ()) { Assert.That (CFGetRetainCount (results.Handle), Is.EqualTo ((nint) 1), "RetainCount"); @@ -283,8 +283,8 @@ void Trust_NoRoot (SecTrust trust, SecPolicy policy) } } if (TestRuntime.CheckXcodeVersion (10, 0)) { - Assert.False (trust.Evaluate (out var error), "Evaluate"); - Assert.NotNull (error, "error"); + Assert.That (trust.Evaluate (out var error), Is.False, "Evaluate"); + Assert.That (error, Is.Not.Null, "error"); } } @@ -341,13 +341,13 @@ void Trust_FullChain (SecTrust trust, SecPolicy policy, X509CertificateCollectio Assert.That (trust.GetTrustResult (), Is.EqualTo (SecTrustResult.Unspecified), "GetTrustResult-2"); if (result == SecTrustResult.Unspecified) { - Assert.True (trust.Evaluate (out var error), $"Evaluate: {error}"); - Assert.Null (error, "error"); + Assert.That (trust.Evaluate (out var error), Is.True, $"Evaluate: {error}"); + Assert.That (error, Is.Null, "error"); } else if (result == SecTrustResult.RecoverableTrustFailure) { if (trust.Evaluate (out var error)) - Assert.Null (error, "error"); + Assert.That (error, Is.Null, "error"); else - Assert.NotNull (error, "error"); + Assert.That (error, Is.Not.Null, "error"); } else { Assert.Fail ($"Unexpected trust result: {result}"); } diff --git a/tests/monotouch-test/Simd/MatrixFloat2x2Test.cs b/tests/monotouch-test/Simd/MatrixFloat2x2Test.cs index 032244c9933e..1611ba571067 100644 --- a/tests/monotouch-test/Simd/MatrixFloat2x2Test.cs +++ b/tests/monotouch-test/Simd/MatrixFloat2x2Test.cs @@ -22,7 +22,7 @@ public void ToStringTest () { var actual = new MatrixFloat2x2 (1, 2, 3, 4); - Assert.AreEqual ("(1, 2)\n(3, 4)", actual.ToString (), "tostring"); + Assert.That (actual.ToString (), Is.EqualTo ("(1, 2)\n(3, 4)"), "tostring"); } } } diff --git a/tests/monotouch-test/Simd/MatrixFloat3x3Test.cs b/tests/monotouch-test/Simd/MatrixFloat3x3Test.cs index 840af15d6ea8..577040667d73 100644 --- a/tests/monotouch-test/Simd/MatrixFloat3x3Test.cs +++ b/tests/monotouch-test/Simd/MatrixFloat3x3Test.cs @@ -23,7 +23,7 @@ public void ToStringTest () { var actual = new MatrixFloat3x3 (1, 2, 3, 4, 5, 6, 7, 8, 9); - Assert.AreEqual ("(1, 2, 3)\n(4, 5, 6)\n(7, 8, 9)", actual.ToString (), "tostring"); + Assert.That (actual.ToString (), Is.EqualTo ("(1, 2, 3)\n(4, 5, 6)\n(7, 8, 9)"), "tostring"); } } } diff --git a/tests/monotouch-test/Simd/MatrixFloat4x3Test.cs b/tests/monotouch-test/Simd/MatrixFloat4x3Test.cs index 911265a752a0..e2ea86e992b6 100644 --- a/tests/monotouch-test/Simd/MatrixFloat4x3Test.cs +++ b/tests/monotouch-test/Simd/MatrixFloat4x3Test.cs @@ -25,18 +25,18 @@ public void Elements () var expected = GetTestMatrix (); var actual = (NMatrix4x3) expected; - Assert.AreEqual (expected.M11, actual.M11, "m11 getter"); - Assert.AreEqual (expected.M12, actual.M12, "m12 getter"); - Assert.AreEqual (expected.M13, actual.M13, "m13 getter"); - Assert.AreEqual (expected.M14, actual.M14, "m14 getter"); - Assert.AreEqual (expected.M21, actual.M21, "m21 getter"); - Assert.AreEqual (expected.M22, actual.M22, "m22 getter"); - Assert.AreEqual (expected.M23, actual.M23, "m23 getter"); - Assert.AreEqual (expected.M24, actual.M24, "m24 getter"); - Assert.AreEqual (expected.M31, actual.M31, "m31 getter"); - Assert.AreEqual (expected.M32, actual.M32, "m32 getter"); - Assert.AreEqual (expected.M33, actual.M33, "m33 getter"); - Assert.AreEqual (expected.M34, actual.M34, "m34 getter"); + Assert.That (actual.M11, Is.EqualTo (expected.M11), "m11 getter"); + Assert.That (actual.M12, Is.EqualTo (expected.M12), "m12 getter"); + Assert.That (actual.M13, Is.EqualTo (expected.M13), "m13 getter"); + Assert.That (actual.M14, Is.EqualTo (expected.M14), "m14 getter"); + Assert.That (actual.M21, Is.EqualTo (expected.M21), "m21 getter"); + Assert.That (actual.M22, Is.EqualTo (expected.M22), "m22 getter"); + Assert.That (actual.M23, Is.EqualTo (expected.M23), "m23 getter"); + Assert.That (actual.M24, Is.EqualTo (expected.M24), "m24 getter"); + Assert.That (actual.M31, Is.EqualTo (expected.M31), "m31 getter"); + Assert.That (actual.M32, Is.EqualTo (expected.M32), "m32 getter"); + Assert.That (actual.M33, Is.EqualTo (expected.M33), "m33 getter"); + Assert.That (actual.M34, Is.EqualTo (expected.M34), "m34 getter"); var newExpected = GetTestMatrix (); actual.M11 = newExpected.M11; @@ -51,18 +51,18 @@ public void Elements () actual.M32 = newExpected.M32; actual.M33 = newExpected.M33; actual.M34 = newExpected.M34; - Assert.AreEqual (newExpected.M11, actual.M11, "m11 setter"); - Assert.AreEqual (newExpected.M12, actual.M12, "m12 setter"); - Assert.AreEqual (newExpected.M13, actual.M13, "m13 setter"); - Assert.AreEqual (newExpected.M14, actual.M14, "m14 setter"); - Assert.AreEqual (newExpected.M21, actual.M21, "m21 setter"); - Assert.AreEqual (newExpected.M22, actual.M22, "m22 setter"); - Assert.AreEqual (newExpected.M23, actual.M23, "m23 setter"); - Assert.AreEqual (newExpected.M24, actual.M24, "m24 setter"); - Assert.AreEqual (newExpected.M31, actual.M31, "m31 setter"); - Assert.AreEqual (newExpected.M32, actual.M32, "m32 setter"); - Assert.AreEqual (newExpected.M33, actual.M33, "m33 setter"); - Assert.AreEqual (newExpected.M34, actual.M34, "m34 setter"); + Assert.That (actual.M11, Is.EqualTo (newExpected.M11), "m11 setter"); + Assert.That (actual.M12, Is.EqualTo (newExpected.M12), "m12 setter"); + Assert.That (actual.M13, Is.EqualTo (newExpected.M13), "m13 setter"); + Assert.That (actual.M14, Is.EqualTo (newExpected.M14), "m14 setter"); + Assert.That (actual.M21, Is.EqualTo (newExpected.M21), "m21 setter"); + Assert.That (actual.M22, Is.EqualTo (newExpected.M22), "m22 setter"); + Assert.That (actual.M23, Is.EqualTo (newExpected.M23), "m23 setter"); + Assert.That (actual.M24, Is.EqualTo (newExpected.M24), "m24 setter"); + Assert.That (actual.M31, Is.EqualTo (newExpected.M31), "m31 setter"); + Assert.That (actual.M32, Is.EqualTo (newExpected.M32), "m32 setter"); + Assert.That (actual.M33, Is.EqualTo (newExpected.M33), "m33 setter"); + Assert.That (actual.M34, Is.EqualTo (newExpected.M34), "m34 setter"); } [Test] @@ -74,16 +74,16 @@ public void Equality_Operator () var inputSimdR = (NMatrix4x3) inputR; // matrices are different - Assert.AreEqual (inputL == inputR, inputSimdL == inputSimdR, "inequality"); - Assert.IsFalse (inputL == inputR, "inequality 2 expected"); - Assert.IsFalse (inputSimdL == inputSimdR, "inequality 2 actual"); + Assert.That (inputSimdL == inputSimdR, Is.EqualTo (inputL == inputR), "inequality"); + Assert.That (inputL == inputR, Is.False, "inequality 2 expected"); + Assert.That (inputSimdL == inputSimdR, Is.False, "inequality 2 actual"); inputL = inputR; inputSimdL = inputSimdR; // matrices are identical - Assert.AreEqual (inputL == inputR, inputSimdL == inputSimdR, "equality"); - Assert.IsTrue (inputL == inputR, "equality 2 expected"); - Assert.IsTrue (inputSimdL == inputSimdR, "equality 2 actual"); + Assert.That (inputSimdL == inputSimdR, Is.EqualTo (inputL == inputR), "equality"); + Assert.That (inputL == inputR, Is.True, "equality 2 expected"); + Assert.That (inputSimdL == inputSimdR, Is.True, "equality 2 actual"); } [Test] @@ -95,16 +95,16 @@ public void Inequality_Operator () var inputSimdR = (NMatrix4x3) inputR; // matrices are different - Assert.AreEqual (inputL != inputR, inputSimdL != inputSimdR, "inequality"); - Assert.IsTrue (inputL != inputR, "inequality 2 expected"); - Assert.IsTrue (inputSimdL != inputSimdR, "inequality 2 actual"); + Assert.That (inputSimdL != inputSimdR, Is.EqualTo (inputL != inputR), "inequality"); + Assert.That (inputL != inputR, Is.True, "inequality 2 expected"); + Assert.That (inputSimdL != inputSimdR, Is.True, "inequality 2 actual"); inputL = inputR; inputSimdL = inputSimdR; // matrices are identical - Assert.AreEqual (inputL != inputR, inputSimdL != inputSimdR, "equality"); - Assert.IsFalse (inputL != inputR, "equality 2 expected"); - Assert.IsFalse (inputSimdL != inputSimdR, "equality 2 actual"); + Assert.That (inputSimdL != inputSimdR, Is.EqualTo (inputL != inputR), "equality"); + Assert.That (inputL != inputR, Is.False, "equality 2 expected"); + Assert.That (inputSimdL != inputSimdR, Is.False, "equality 2 actual"); } [Test] @@ -113,7 +113,7 @@ public void ToStringTest () var expected = GetTestMatrix (); var actual = (NMatrix4x3) expected; - Assert.AreEqual (expected.ToString (), actual.ToString (), "tostring"); + Assert.That (actual.ToString (), Is.EqualTo (expected.ToString ()), "tostring"); } // GetHashCode doesn't have to be identical, so no need to test @@ -126,10 +126,10 @@ public void Equals_Object () var actualA = (NMatrix4x3) expectedA; var actualB = (NMatrix4x3) expectedB; - Assert.IsTrue (actualA.Equals ((object) actualA), "self"); - Assert.IsFalse (actualA.Equals ((object) actualB), "other"); - Assert.IsFalse (actualA.Equals (null), "null"); - Assert.IsTrue (actualA.Equals (expectedA), "other type"); + Assert.That (actualA.Equals ((object) actualA), Is.True, "self"); + Assert.That (actualA.Equals ((object) actualB), Is.False, "other"); + Assert.That (actualA.Equals (null), Is.False, "null"); + Assert.That (actualA.Equals (expectedA), Is.True, "other type"); } [Test] @@ -140,8 +140,8 @@ public void Equals_Matrix () var actualA = (NMatrix4x3) expectedA; var actualB = (NMatrix4x3) expectedB; - Assert.IsTrue (actualA.Equals (actualA), "self"); - Assert.IsFalse (actualA.Equals (actualB), "other"); + Assert.That (actualA.Equals (actualA), Is.True, "self"); + Assert.That (actualA.Equals (actualB), Is.False, "other"); } // A collection of test matrices. diff --git a/tests/monotouch-test/Simd/NVector3dTest.cs b/tests/monotouch-test/Simd/NVector3dTest.cs index 4f004211290e..8b87130fea35 100644 --- a/tests/monotouch-test/Simd/NVector3dTest.cs +++ b/tests/monotouch-test/Simd/NVector3dTest.cs @@ -25,16 +25,16 @@ public void Equality_Operator () var inputSimdR = (NVector3d) inputR; // matrices are different - Assert.AreEqual (inputL == inputR, inputSimdL == inputSimdR, "inequality"); - Assert.IsFalse (inputL == inputR, "inequality 2 expected"); - Assert.IsFalse (inputSimdL == inputSimdR, "inequality 2 actual"); + Assert.That (inputSimdL == inputSimdR, Is.EqualTo (inputL == inputR), "inequality"); + Assert.That (inputL == inputR, Is.False, "inequality 2 expected"); + Assert.That (inputSimdL == inputSimdR, Is.False, "inequality 2 actual"); inputL = inputR; inputSimdL = inputSimdR; // matrices are identical - Assert.AreEqual (inputL == inputR, inputSimdL == inputSimdR, "equality"); - Assert.IsTrue (inputL == inputR, "equality 2 expected"); - Assert.IsTrue (inputSimdL == inputSimdR, "equality 2 actual"); + Assert.That (inputSimdL == inputSimdR, Is.EqualTo (inputL == inputR), "equality"); + Assert.That (inputL == inputR, Is.True, "equality 2 expected"); + Assert.That (inputSimdL == inputSimdR, Is.True, "equality 2 actual"); } [Test] @@ -46,16 +46,16 @@ public void Inequality_Operator () var inputSimdR = (NVector3d) inputR; // matrices are different - Assert.AreEqual (inputL != inputR, inputSimdL != inputSimdR, "inequality"); - Assert.IsTrue (inputL != inputR, "inequality 2 expected"); - Assert.IsTrue (inputSimdL != inputSimdR, "inequality 2 actual"); + Assert.That (inputSimdL != inputSimdR, Is.EqualTo (inputL != inputR), "inequality"); + Assert.That (inputL != inputR, Is.True, "inequality 2 expected"); + Assert.That (inputSimdL != inputSimdR, Is.True, "inequality 2 actual"); inputL = inputR; inputSimdL = inputSimdR; // matrices are identical - Assert.AreEqual (inputL != inputR, inputSimdL != inputSimdR, "equality"); - Assert.IsFalse (inputL != inputR, "equality 2 expected"); - Assert.IsFalse (inputSimdL != inputSimdR, "equality 2 actual"); + Assert.That (inputSimdL != inputSimdR, Is.EqualTo (inputL != inputR), "equality"); + Assert.That (inputL != inputR, Is.False, "equality 2 expected"); + Assert.That (inputSimdL != inputSimdR, Is.False, "equality 2 actual"); } [Test] @@ -63,7 +63,7 @@ public void ToStringTest () { var vector = new NVector3d (1, 2, 3); - Assert.AreEqual ("(1, 2, 3)", vector.ToString (), "tostring"); + Assert.That (vector.ToString (), Is.EqualTo ("(1, 2, 3)"), "tostring"); } // GetHashCode doesn't have to be identical, so no need to test @@ -76,10 +76,10 @@ public void Equals_Object () var actualA = (NVector3d) expectedA; var actualB = (NVector3d) expectedB; - Assert.IsTrue (actualA.Equals ((object) actualA), "self"); - Assert.IsFalse (actualA.Equals ((object) actualB), "other"); - Assert.IsFalse (actualA.Equals (null), "null"); - Assert.IsTrue (actualA.Equals (expectedA), "same type"); + Assert.That (actualA.Equals ((object) actualA), Is.True, "self"); + Assert.That (actualA.Equals ((object) actualB), Is.False, "other"); + Assert.That (actualA.Equals (null), Is.False, "null"); + Assert.That (actualA.Equals (expectedA), Is.True, "same type"); } [Test] @@ -90,8 +90,8 @@ public void Equals_Vector () var actualA = (NVector3d) expectedA; var actualB = (NVector3d) expectedB; - Assert.IsTrue (actualA.Equals (actualA), "self"); - Assert.IsFalse (actualA.Equals (actualB), "other"); + Assert.That (actualA.Equals (actualA), Is.True, "self"); + Assert.That (actualA.Equals (actualB), Is.False, "other"); } static NVector3d [] test_vectors = new [] { diff --git a/tests/monotouch-test/Simd/VectorByte16Test.cs b/tests/monotouch-test/Simd/VectorByte16Test.cs index b8461b2ccaa9..71589b527b4d 100644 --- a/tests/monotouch-test/Simd/VectorByte16Test.cs +++ b/tests/monotouch-test/Simd/VectorByte16Test.cs @@ -17,7 +17,7 @@ public void DefaultConstructor () { var vector = new VectorByte16 (); for (int i = 0; i < 16; i++) { - Assert.AreEqual (0, vector [i], $"default constructor element {i}"); + Assert.That (vector [i], Is.EqualTo (0), $"default constructor element {i}"); } } @@ -27,7 +27,7 @@ public void ArrayConstructor () var expected = GetTestByteArray (); var actual = new VectorByte16 (expected); for (int i = 0; i < 16; i++) { - Assert.AreEqual (expected [i], actual [i], $"array ctor element {i}"); + Assert.That (actual [i], Is.EqualTo (expected [i]), $"array ctor element {i}"); } } @@ -36,7 +36,7 @@ public void ArrayConstructor_Null () { var actual = new VectorByte16 (null); for (int i = 0; i < 16; i++) { - Assert.AreEqual (0, actual [i], $"null array ctor element {i}"); + Assert.That (actual [i], Is.EqualTo (0), $"null array ctor element {i}"); } } @@ -46,10 +46,10 @@ public void ArrayConstructor_PartialArray () var partialArray = new byte [] { 1, 2, 3, 4, 5 }; var actual = new VectorByte16 (partialArray); for (int i = 0; i < 5; i++) { - Assert.AreEqual (partialArray [i], actual [i], $"partial array ctor element {i}"); + Assert.That (actual [i], Is.EqualTo (partialArray [i]), $"partial array ctor element {i}"); } for (int i = 5; i < 16; i++) { - Assert.AreEqual (0, actual [i], $"partial array ctor uninitialized element {i}"); + Assert.That (actual [i], Is.EqualTo (0), $"partial array ctor uninitialized element {i}"); } } @@ -62,7 +62,7 @@ public void ArrayConstructor_LargeArray () } var actual = new VectorByte16 (largeArray); for (int i = 0; i < 16; i++) { - Assert.AreEqual (largeArray [i], actual [i], $"large array ctor element {i}"); + Assert.That (actual [i], Is.EqualTo (largeArray [i]), $"large array ctor element {i}"); } } @@ -72,7 +72,7 @@ public void Indexer_Get () var expected = GetTestByteArray (); var vector = new VectorByte16 (expected); for (int i = 0; i < 16; i++) { - Assert.AreEqual (expected [i], vector [i], $"indexer get element {i}"); + Assert.That (vector [i], Is.EqualTo (expected [i]), $"indexer get element {i}"); } } @@ -85,7 +85,7 @@ public void Indexer_Set () vector [i] = expected [i]; } for (int i = 0; i < 16; i++) { - Assert.AreEqual (expected [i], vector [i], $"indexer set element {i}"); + Assert.That (vector [i], Is.EqualTo (expected [i]), $"indexer set element {i}"); } } @@ -112,11 +112,11 @@ public void Equality_Operator () var inputR = GetTestVector (); // vectors are different - Assert.IsFalse (inputL == inputR, "inequality"); + Assert.That (inputL == inputR, Is.False, "inequality"); inputL = inputR; // vectors are identical - Assert.IsTrue (inputL == inputR, "equality"); + Assert.That (inputL == inputR, Is.True, "equality"); } [Test] @@ -126,18 +126,18 @@ public void Inequality_Operator () var inputR = GetTestVector (); // vectors are different - Assert.IsTrue (inputL != inputR, "inequality"); + Assert.That (inputL != inputR, Is.True, "inequality"); inputL = inputR; // vectors are identical - Assert.IsFalse (inputL != inputR, "equality"); + Assert.That (inputL != inputR, Is.False, "equality"); } [Test] public void ToStringTest () { var vector = new VectorByte16 (new byte [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }); - Assert.AreEqual ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)", vector.ToString (), "toString"); + Assert.That (vector.ToString (), Is.EqualTo ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)"), "toString"); } [Test] @@ -146,10 +146,10 @@ public void Equals_Object () var expectedA = GetTestVector (); var expectedB = GetTestVector (); - Assert.IsTrue (expectedA.Equals ((object) expectedA), "self"); - Assert.IsFalse (expectedA.Equals ((object) expectedB), "other"); - Assert.IsFalse (expectedA.Equals (null), "null"); - Assert.IsFalse (expectedA.Equals ("string"), "wrong type"); + Assert.That (expectedA.Equals ((object) expectedA), Is.True, "self"); + Assert.That (expectedA.Equals ((object) expectedB), Is.False, "other"); + Assert.That (expectedA.Equals (null), Is.False, "null"); + Assert.That (expectedA.Equals ("string"), Is.False, "wrong type"); } [Test] @@ -158,8 +158,8 @@ public void Equals_Vector () var expectedA = GetTestVector (); var expectedB = GetTestVector (); - Assert.IsTrue (expectedA.Equals (expectedA), "self"); - Assert.IsFalse (expectedA.Equals (expectedB), "other"); + Assert.That (expectedA.Equals (expectedA), Is.True, "self"); + Assert.That (expectedA.Equals (expectedB), Is.False, "other"); } [Test] @@ -169,9 +169,9 @@ public void AsSpan () var vector = new VectorByte16 (expected); var span = vector.AsSpan (); - Assert.AreEqual (16, span.Length, "span length"); + Assert.That (span.Length, Is.EqualTo (16), "span length"); for (int i = 0; i < 16; i++) { - Assert.AreEqual (expected [i], span [i], $"span element {i}"); + Assert.That (span [i], Is.EqualTo (expected [i]), $"span element {i}"); } } @@ -182,7 +182,7 @@ public void GetHashCode_SameVectors () var vector1 = new VectorByte16 (byteArray); var vector2 = new VectorByte16 (byteArray); - Assert.AreEqual (vector1.GetHashCode (), vector2.GetHashCode (), "same vectors should have same hash code"); + Assert.That (vector2.GetHashCode (), Is.EqualTo (vector1.GetHashCode ()), "same vectors should have same hash code"); } [Test] @@ -191,7 +191,7 @@ public void GetHashCode_DifferentVectors () var vector1 = GetTestVector (); var vector2 = GetTestVector (); - Assert.AreNotEqual (vector1.GetHashCode (), vector2.GetHashCode (), "different vectors should have different hash codes"); + Assert.That (vector2.GetHashCode (), Is.Not.EqualTo (vector1.GetHashCode ()), "different vectors should have different hash codes"); } [Test] @@ -199,7 +199,7 @@ public void Zero_Property () { var zero = VectorByte16.Zero; for (int i = 0; i < 16; i++) { - Assert.AreEqual (0, zero [i], $"Zero property element {i}"); + Assert.That (zero [i], Is.EqualTo (0), $"Zero property element {i}"); } } diff --git a/tests/monotouch-test/Simd/VectorFloat3Test.cs b/tests/monotouch-test/Simd/VectorFloat3Test.cs index 162fd848a7f1..046fe2400ee6 100644 --- a/tests/monotouch-test/Simd/VectorFloat3Test.cs +++ b/tests/monotouch-test/Simd/VectorFloat3Test.cs @@ -26,16 +26,16 @@ public void Equality_Operator () var inputSimdR = (VectorFloat3) inputR; // matrices are different - Assert.AreEqual (inputL == inputR, inputSimdL == inputSimdR, "inequality"); - Assert.IsFalse (inputL == inputR, "inequality 2 expected"); - Assert.IsFalse (inputSimdL == inputSimdR, "inequality 2 actual"); + Assert.That (inputSimdL == inputSimdR, Is.EqualTo (inputL == inputR), "inequality"); + Assert.That (inputL == inputR, Is.False, "inequality 2 expected"); + Assert.That (inputSimdL == inputSimdR, Is.False, "inequality 2 actual"); inputL = inputR; inputSimdL = inputSimdR; // matrices are identical - Assert.AreEqual (inputL == inputR, inputSimdL == inputSimdR, "equality"); - Assert.IsTrue (inputL == inputR, "equality 2 expected"); - Assert.IsTrue (inputSimdL == inputSimdR, "equality 2 actual"); + Assert.That (inputSimdL == inputSimdR, Is.EqualTo (inputL == inputR), "equality"); + Assert.That (inputL == inputR, Is.True, "equality 2 expected"); + Assert.That (inputSimdL == inputSimdR, Is.True, "equality 2 actual"); } [Test] @@ -47,16 +47,16 @@ public void Inequality_Operator () var inputSimdR = (VectorFloat3) inputR; // matrices are different - Assert.AreEqual (inputL != inputR, inputSimdL != inputSimdR, "inequality"); - Assert.IsTrue (inputL != inputR, "inequality 2 expected"); - Assert.IsTrue (inputSimdL != inputSimdR, "inequality 2 actual"); + Assert.That (inputSimdL != inputSimdR, Is.EqualTo (inputL != inputR), "inequality"); + Assert.That (inputL != inputR, Is.True, "inequality 2 expected"); + Assert.That (inputSimdL != inputSimdR, Is.True, "inequality 2 actual"); inputL = inputR; inputSimdL = inputSimdR; // matrices are identical - Assert.AreEqual (inputL != inputR, inputSimdL != inputSimdR, "equality"); - Assert.IsFalse (inputL != inputR, "equality 2 expected"); - Assert.IsFalse (inputSimdL != inputSimdR, "equality 2 actual"); + Assert.That (inputSimdL != inputSimdR, Is.EqualTo (inputL != inputR), "equality"); + Assert.That (inputL != inputR, Is.False, "equality 2 expected"); + Assert.That (inputSimdL != inputSimdR, Is.False, "equality 2 actual"); } [Test] @@ -82,7 +82,7 @@ public void ToStringTest () { var vector = new VectorFloat3 (1, 2, 3); - Assert.AreEqual ("(1, 2, 3)", vector.ToString (), "tostring"); + Assert.That (vector.ToString (), Is.EqualTo ("(1, 2, 3)"), "tostring"); } // GetHashCode doesn't have to be identical, so no need to test @@ -95,10 +95,10 @@ public void Equals_Object () var actualA = (VectorFloat3) expectedA; var actualB = (VectorFloat3) expectedB; - Assert.IsTrue (actualA.Equals ((object) actualA), "self"); - Assert.IsFalse (actualA.Equals ((object) actualB), "other"); - Assert.IsFalse (actualA.Equals (null), "null"); - Assert.IsTrue (actualA.Equals (expectedA), "same type"); + Assert.That (actualA.Equals ((object) actualA), Is.True, "self"); + Assert.That (actualA.Equals ((object) actualB), Is.False, "other"); + Assert.That (actualA.Equals (null), Is.False, "null"); + Assert.That (actualA.Equals (expectedA), Is.True, "same type"); } [Test] @@ -109,8 +109,8 @@ public void Equals_Vector () var actualA = (VectorFloat3) expectedA; var actualB = (VectorFloat3) expectedB; - Assert.IsTrue (actualA.Equals (actualA), "self"); - Assert.IsFalse (actualA.Equals (actualB), "other"); + Assert.That (actualA.Equals (actualA), Is.True, "self"); + Assert.That (actualA.Equals (actualB), Is.False, "other"); } static VectorFloat3 [] test_vectors = new [] { diff --git a/tests/monotouch-test/SpriteKit/FieldNodeTest.cs b/tests/monotouch-test/SpriteKit/FieldNodeTest.cs index 659daad19bc4..9fd1356782dd 100644 --- a/tests/monotouch-test/SpriteKit/FieldNodeTest.cs +++ b/tests/monotouch-test/SpriteKit/FieldNodeTest.cs @@ -22,16 +22,16 @@ public void CreateRadialGravityField () var v = new Vector4 (1, 2, 3, 4); node.Direction = v; - Assert.AreEqual (node.Direction.X, 1, "#x1"); - Assert.AreEqual (node.Direction.Y, 2, "#y1"); - Assert.AreEqual (node.Direction.Z, 3, "#z1"); - Assert.AreEqual (node.Direction.W, 0, "#w1"); + Assert.That (node.Direction.X, Is.EqualTo (1), "#x1"); + Assert.That (node.Direction.Y, Is.EqualTo (2), "#y1"); + Assert.That (node.Direction.Z, Is.EqualTo (3), "#z1"); + Assert.That (node.Direction.W, Is.EqualTo (0), "#w1"); v = node.Direction; - Assert.AreEqual (v.X, 1, "#x2"); - Assert.AreEqual (v.Y, 2, "#y2"); - Assert.AreEqual (v.Z, 3, "#z2"); - Assert.AreEqual (v.W, 0, "#w2"); + Assert.That (v.X, Is.EqualTo (1), "#x2"); + Assert.That (v.Y, Is.EqualTo (2), "#y2"); + Assert.That (v.Z, Is.EqualTo (3), "#z2"); + Assert.That (v.W, Is.EqualTo (0), "#w2"); } } @@ -40,7 +40,7 @@ public void CreateLinearGravityField () { using (var node = SKFieldNode.CreateLinearGravityField (new Vector4 (1, 2, 3, 4))) { - Assert.AreEqual (0.00457763672f, node.MinimumRadius, "#minimum radius"); + Assert.That (node.MinimumRadius, Is.EqualTo (0.00457763672f), "#minimum radius"); } } @@ -49,7 +49,7 @@ public void CreateVelocityField () { using (var node = SKFieldNode.CreateVelocityField (new Vector4 (1, 2, 3, 4))) { - Assert.AreEqual (0.00457763672f, node.MinimumRadius, "#minimum radius"); + Assert.That (node.MinimumRadius, Is.EqualTo (0.00457763672f), "#minimum radius"); } } @@ -62,10 +62,10 @@ public void CreateCustomField () // FIXME: the code below doesn't end up calling the anonymous delegate above. var v = node.Direction; - Assert.AreEqual (0, v.X, "#x2"); - Assert.AreEqual (0, v.Y, "#y2"); - Assert.AreEqual (0, v.Z, "#z2"); - Assert.AreEqual (0, v.W, "#w2"); + Assert.That (v.X, Is.EqualTo (0), "#x2"); + Assert.That (v.Y, Is.EqualTo (0), "#y2"); + Assert.That (v.Z, Is.EqualTo (0), "#z2"); + Assert.That (v.W, Is.EqualTo (0), "#w2"); } } } diff --git a/tests/monotouch-test/SpriteKit/PhysicsWorldTest.cs b/tests/monotouch-test/SpriteKit/PhysicsWorldTest.cs index eb8d6015fe7f..56bff0544c31 100644 --- a/tests/monotouch-test/SpriteKit/PhysicsWorldTest.cs +++ b/tests/monotouch-test/SpriteKit/PhysicsWorldTest.cs @@ -20,9 +20,9 @@ public void SampleFields () using (var scene = new SKScene ()) { using (var world = scene.PhysicsWorld) { var v = world.SampleFields (new Vector3 (1, 2, 3)); - Assert.AreEqual (0, v.X, "#x1"); - Assert.AreEqual (0, v.Y, "#y1"); - Assert.AreEqual (0, v.Z, "#z1"); + Assert.That (v.X, Is.EqualTo (0), "#x1"); + Assert.That (v.Y, Is.EqualTo (0), "#y1"); + Assert.That (v.Z, Is.EqualTo (0), "#z1"); } } } diff --git a/tests/monotouch-test/SpriteKit/SK3DNodeTest.cs b/tests/monotouch-test/SpriteKit/SK3DNodeTest.cs index 118fa1374135..909912c61d64 100644 --- a/tests/monotouch-test/SpriteKit/SK3DNodeTest.cs +++ b/tests/monotouch-test/SpriteKit/SK3DNodeTest.cs @@ -30,9 +30,9 @@ public void ProjectPoint () using (var node = new SK3DNode ()) { var v = node.ProjectPoint (new Vector3 (1, 2, 3)); - Assert.AreEqual (1, v.X, "#x1"); - Assert.AreEqual (2, v.Y, "#y1"); - Assert.AreEqual (3, v.Z, "#z1"); + Assert.That (v.X, Is.EqualTo (1), "#x1"); + Assert.That (v.Y, Is.EqualTo (2), "#y1"); + Assert.That (v.Z, Is.EqualTo (3), "#z1"); } } @@ -48,9 +48,9 @@ public void UnprojectPoint () using (var node = new SK3DNode ()) { var v = node.UnprojectPoint (new Vector3 (1, 2, 3)); - Assert.AreEqual (1, v.X, "#x1"); - Assert.AreEqual (2, v.Y, "#y1"); - Assert.AreEqual (3, v.Z, "#z1"); + Assert.That (v.X, Is.EqualTo (1), "#x1"); + Assert.That (v.Y, Is.EqualTo (2), "#y1"); + Assert.That (v.Z, Is.EqualTo (3), "#z1"); } } } diff --git a/tests/monotouch-test/SpriteKit/SKPaymentTests.cs b/tests/monotouch-test/SpriteKit/SKPaymentTests.cs index d44bb18e7ab7..7b91cbec75c0 100644 --- a/tests/monotouch-test/SpriteKit/SKPaymentTests.cs +++ b/tests/monotouch-test/SpriteKit/SKPaymentTests.cs @@ -13,7 +13,7 @@ public void SKPayment_PaymentWithProduct () { SKProduct product = new SKProduct (); SKPayment payment = SKPayment.CreateFrom (product); - Assert.IsNotNull (payment); + Assert.That (payment, Is.Not.Null); } } } diff --git a/tests/monotouch-test/SpriteKit/SKScene.cs b/tests/monotouch-test/SpriteKit/SKScene.cs index 1da17da539fa..3d081dfa146d 100644 --- a/tests/monotouch-test/SpriteKit/SKScene.cs +++ b/tests/monotouch-test/SpriteKit/SKScene.cs @@ -18,7 +18,7 @@ public void SKScene_InitWithSize () SKNode c = new SKNode (); //SKScene c = new SKScene (new CGSize (50, 50)); - Assert.IsNotNull (c); + Assert.That (c, Is.Not.Null); } [Test] @@ -28,7 +28,7 @@ public void SKScene_InitWithSizeSuper () return; MyScene c = new MyScene (new CGSize (50, 50)); - Assert.IsNotNull (c); + Assert.That (c, Is.Not.Null); } class MyScene : SKScene { diff --git a/tests/monotouch-test/SpriteKit/SKShapeNodeTest.cs b/tests/monotouch-test/SpriteKit/SKShapeNodeTest.cs index 063b8fb06e9c..59585145172a 100644 --- a/tests/monotouch-test/SpriteKit/SKShapeNodeTest.cs +++ b/tests/monotouch-test/SpriteKit/SKShapeNodeTest.cs @@ -29,7 +29,7 @@ public void FromPointsTest () }; var result = SKShapeNode.FromPoints (pts); - Assert.IsNotNull (result, "result should not be null"); + Assert.That (result, Is.Not.Null, "result should not be null"); } [Test] @@ -44,7 +44,7 @@ public void FromPointsOffsetTest () }; var result = SKShapeNode.FromPoints (pts, 1, 1); - Assert.IsNotNull (result, "result should not be null"); + Assert.That (result, Is.Not.Null, "result should not be null"); Assert.Throws (() => SKShapeNode.FromPoints (pts, 1, 2)); } @@ -61,7 +61,7 @@ public void FromSplinePointsTest () }; var result = SKShapeNode.FromSplinePoints (pts); - Assert.IsNotNull (result, "result should not be null"); + Assert.That (result, Is.Not.Null, "result should not be null"); } [Test] @@ -76,7 +76,7 @@ public void FromSplinePointsOffsetTest () }; var result = SKShapeNode.FromSplinePoints (pts, 1, 1); - Assert.IsNotNull (result, "result should not be null"); + Assert.That (result, Is.Not.Null, "result should not be null"); Assert.Throws (() => SKShapeNode.FromSplinePoints (pts, 1, 2)); } diff --git a/tests/monotouch-test/SpriteKit/SKTransformNodeTest.cs b/tests/monotouch-test/SpriteKit/SKTransformNodeTest.cs index 17729d31f827..64401660101a 100644 --- a/tests/monotouch-test/SpriteKit/SKTransformNodeTest.cs +++ b/tests/monotouch-test/SpriteKit/SKTransformNodeTest.cs @@ -34,9 +34,9 @@ public void EulerAngles () V3 = new VectorFloat3 (1, 2, 3); obj.EulerAngles = V3; // The values bellow match what the same code in Swift returns. - Assert.AreEqual (-2.14159298f, obj.EulerAngles.X, 0.000001f, "#x1"); - Assert.AreEqual (1.14159274f, obj.EulerAngles.Y, 0.000001f, "#y1"); - Assert.AreEqual (-0.141592711f, obj.EulerAngles.Z, 0.000001f, "#z1"); + Assert.That (obj.EulerAngles.X, Is.EqualTo (-2.14159298f).Within (0.000001f), "#x1"); + Assert.That (obj.EulerAngles.Y, Is.EqualTo (1.14159274f).Within (0.000001f), "#y1"); + Assert.That (obj.EulerAngles.Z, Is.EqualTo (-0.141592711f).Within (0.000001f), "#z1"); } } @@ -66,8 +66,8 @@ public void RotationMatrix () ); obj.RotationMatrix = rotatedMatrix; Asserts.AreEqual (rotatedMatrix, obj.RotationMatrix, 0.000001f, "RotationMatrix b"); - Assert.AreEqual ((nfloat) (Math.PI / 2), obj.XRotation, 0.000001f, "XRotation b"); - Assert.AreEqual (0, obj.YRotation, 0.000001f, "YRotation b"); // Setting YRotation changes RotationMatrix, but setting RotationMatrix doesn't change YRotation. + Assert.That ((double) obj.XRotation, Is.EqualTo (Math.PI / 2).Within (0.000001), "XRotation b"); + Assert.That ((double) obj.YRotation, Is.EqualTo (0.0).Within (0.000001), "YRotation b"); // Setting YRotation changes RotationMatrix, but setting RotationMatrix doesn't change YRotation. } } diff --git a/tests/monotouch-test/SpriteKit/SpriteNodeTest.cs b/tests/monotouch-test/SpriteKit/SpriteNodeTest.cs index 5171d6bdc86b..c915a8ced95c 100644 --- a/tests/monotouch-test/SpriteKit/SpriteNodeTest.cs +++ b/tests/monotouch-test/SpriteKit/SpriteNodeTest.cs @@ -26,10 +26,10 @@ public class SpriteNodeTest { void CheckEmpty (SKSpriteNode n) { - Assert.IsNotNull (n.Color, "Color"); - Assert.Null (n.Name, "Name"); - Assert.True (n.Size.IsEmpty, "Size"); - Assert.Null (n.Texture, "Texture"); + Assert.That (n.Color, Is.Not.Null, "Color"); + Assert.That (n.Name, Is.Null, "Name"); + Assert.That (n.Size.IsEmpty, Is.True, "Size"); + Assert.That (n.Texture, Is.Null, "Texture"); } [SetUp] @@ -101,9 +101,9 @@ public void Texture () { using (var t = SKTexture.FromImageNamed ("basn3p08.png")) using (var n = new SKSpriteNode (t)) { - Assert.AreSame (n.Texture, t, "Texture-1"); + Assert.That (t, Is.SameAs (n.Texture), "Texture-1"); n.Texture = null; - Assert.IsNull (n.Texture, "Texture-2"); + Assert.That (n.Texture, Is.Null, "Texture-2"); } } } diff --git a/tests/monotouch-test/SpriteKit/TextureTest.cs b/tests/monotouch-test/SpriteKit/TextureTest.cs index c3aa2ba1a0c0..232a2e8c2327 100644 --- a/tests/monotouch-test/SpriteKit/TextureTest.cs +++ b/tests/monotouch-test/SpriteKit/TextureTest.cs @@ -52,7 +52,7 @@ public void Atlas_MissingResource () #endif Assert.That (texture.TextureRect, Is.EqualTo (new CGRect (0, 0, 1, 1)), "TextureRect"); - Assert.False (texture.UsesMipmaps, "UsesMipmaps"); + Assert.That (texture.UsesMipmaps, Is.False, "UsesMipmaps"); } } } diff --git a/tests/monotouch-test/SpriteKit/UniformTest.cs b/tests/monotouch-test/SpriteKit/UniformTest.cs index 23d0a9a70d97..8d2ed703915d 100644 --- a/tests/monotouch-test/SpriteKit/UniformTest.cs +++ b/tests/monotouch-test/SpriteKit/UniformTest.cs @@ -31,29 +31,29 @@ public void Ctors () var N3Zero = default (NMatrix3); var N2Zero = default (NMatrix2); - Assert.AreEqual ("name", obj.Name, "1 Name"); - Assert.AreEqual (SKUniformType.None, obj.UniformType, "1 UniformType"); - Assert.IsNull (obj.TextureValue, "1 TextureValue"); - Assert.AreEqual (0.0f, obj.FloatValue, "1 FloatValue"); + Assert.That (obj.Name, Is.EqualTo ("name"), "1 Name"); + Assert.That (obj.UniformType, Is.EqualTo (SKUniformType.None), "1 UniformType"); + Assert.That (obj.TextureValue, Is.Null, "1 TextureValue"); + Assert.That (obj.FloatValue, Is.EqualTo (0.0f), "1 FloatValue"); Asserts.AreEqual (N2Zero, obj.MatrixFloat2x2Value, "1 MatrixFloat2x2Value"); Asserts.AreEqual (N3Zero, obj.MatrixFloat3x3Value, "1 MatrixFloat3x3Value"); Asserts.AreEqual (N4Zero, obj.MatrixFloat4x4Value, "1 MatrixFloat4x4Value"); texture = SKTexture.FromImageNamed ("basn3p08.png"); obj.TextureValue = texture; - Assert.AreEqual (texture, obj.TextureValue, "2 TextureValue"); + Assert.That (obj.TextureValue, Is.EqualTo (texture), "2 TextureValue"); obj.FloatValue = 0.5f; - Assert.AreEqual (0.5f, obj.FloatValue, "2 FloatValue"); + Assert.That (obj.FloatValue, Is.EqualTo (0.5f), "2 FloatValue"); } bool hasSimdConstructors = TestRuntime.CheckXcodeVersion (8, 0); using (var obj = new SKUniform ("name", texture)) { - Assert.AreEqual (texture, obj.TextureValue, "3 TextureValue"); + Assert.That (obj.TextureValue, Is.EqualTo (texture), "3 TextureValue"); } using (var obj = new SKUniform ("name", 3.1415f)) { - Assert.AreEqual (3.1415f, obj.FloatValue, "4 FloatValue"); + Assert.That (obj.FloatValue, Is.EqualTo (3.1415f), "4 FloatValue"); } } diff --git a/tests/monotouch-test/SpriteKit/WarpGeometryGridTest.cs b/tests/monotouch-test/SpriteKit/WarpGeometryGridTest.cs index 288b88b3de6a..cdade79482c4 100644 --- a/tests/monotouch-test/SpriteKit/WarpGeometryGridTest.cs +++ b/tests/monotouch-test/SpriteKit/WarpGeometryGridTest.cs @@ -16,7 +16,7 @@ public void SKWarpGeometryGridTest () TestRuntime.AssertXcodeVersion (8, 0); var grid = new SKWarpGeometryGrid (1, 1, points, points); - Assert.NotNull (grid, "new SKWarpGeometryGrid () should not return null"); + Assert.That (grid, Is.Not.Null, "new SKWarpGeometryGrid () should not return null"); } [Test] @@ -25,7 +25,7 @@ public void CreateTest () TestRuntime.AssertXcodeVersion (8, 0); var grid = SKWarpGeometryGrid.Create (1, 1, points, points); - Assert.NotNull (grid, "SKWarpGeometryGrid.Create should not return null"); + Assert.That (grid, Is.Not.Null, "SKWarpGeometryGrid.Create should not return null"); } [Test] @@ -35,7 +35,7 @@ public void GetGridByReplacingSourcePositionsTest () using (var grid = SKWarpGeometryGrid.GetGrid ()) { var r = grid.GetGridByReplacingSourcePositions (points); - Assert.NotNull (r, "GetGridByReplacingSourcePositions should not return null"); + Assert.That (r, Is.Not.Null, "GetGridByReplacingSourcePositions should not return null"); } } @@ -46,7 +46,7 @@ public void GetGridByReplacingDestPositionsTest () using (var grid = SKWarpGeometryGrid.GetGrid ()) { var r = grid.GetGridByReplacingDestPositions (points); - Assert.NotNull (r, "GetGridByReplacingDestPositions should not return null"); + Assert.That (r, Is.Not.Null, "GetGridByReplacingDestPositions should not return null"); } } } diff --git a/tests/monotouch-test/StoreKit/SKCloudServiceSetupOptionsTest.cs b/tests/monotouch-test/StoreKit/SKCloudServiceSetupOptionsTest.cs index c7665f6103bb..5cb4fdb804da 100644 --- a/tests/monotouch-test/StoreKit/SKCloudServiceSetupOptionsTest.cs +++ b/tests/monotouch-test/StoreKit/SKCloudServiceSetupOptionsTest.cs @@ -25,8 +25,8 @@ public void ActionTest () var optionsObject = new SKCloudServiceSetupOptions { Action = SKCloudServiceSetupAction.Subscribe }; - Assert.AreEqual ("sdkSubscribe", optionsObject.Dictionary ["SKCloudServiceSetupOptionsActionKey"].ToString (), "SKCloudServiceSetupOptionsActionKey"); - Assert.AreEqual (SKCloudServiceSetupAction.Subscribe, optionsObject.Action, "SKCloudServiceSetupOptions.Action"); + Assert.That (optionsObject.Dictionary ["SKCloudServiceSetupOptionsActionKey"].ToString (), Is.EqualTo ("sdkSubscribe"), "SKCloudServiceSetupOptionsActionKey"); + Assert.That (optionsObject.Action, Is.EqualTo (SKCloudServiceSetupAction.Subscribe), "SKCloudServiceSetupOptions.Action"); } } } diff --git a/tests/monotouch-test/System.Net.Http/MessageHandlers.cs b/tests/monotouch-test/System.Net.Http/MessageHandlers.cs index 03f759bdf6c6..b159fab8c8c5 100644 --- a/tests/monotouch-test/System.Net.Http/MessageHandlers.cs +++ b/tests/monotouch-test/System.Net.Http/MessageHandlers.cs @@ -3,6 +3,7 @@ // using System.Collections; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Net; @@ -25,6 +26,9 @@ namespace MonoTests.System.Net.Http { [TestFixture] [Preserve (AllMembers = true)] public class MessageHandlerTest { + const string AllowSameOriginRedirectCredentialsSwitch = "Foundation.NSUrlSessionHandler.AllowSameOriginRedirectCredentials"; + const string UseSharedCredentialStorageSwitch = "Foundation.NSUrlSessionHandler.UseSharedCredentialStorage"; + public MessageHandlerTest () { // Https seems broken on our macOS 10.9 bot, so skip this test. @@ -63,9 +67,9 @@ public void DnsFailure (Type handlerType) response = await client.GetStringAsync ("http://doesnotexist.xamarin.com"); }, out var ex); - Assert.IsTrue (done, "Did not time out"); - Assert.IsNull (response, $"Response is not null {response}"); - Assert.IsInstanceOf (typeof (HttpRequestException), ex, "Exception"); + Assert.That (done, Is.True, "Did not time out"); + Assert.That (response, Is.Null, $"Response is not null {response}"); + Assert.That (ex, Is.InstanceOf (typeof (HttpRequestException)), "Exception"); } // ensure that we do get the same cookies as the managed handler for the default session @@ -107,14 +111,17 @@ void TestNSUrlSessionHandlerCookiesImpl (NSUrlSessionHandler nativeHandler) Assert.That (nativeHandler.UseCookies, Is.EqualTo (true), "UseCookies"); }, out var ex); - if (!completed || !managedCookieResult || !nativeCookieResult) + var managedHasExpectedCookie = managedCookies?.Any (v => v.StartsWith ("cookie=chocolate-chip;", StringComparison.Ordinal)) == true; + var nativeHasExpectedCookie = nativeCookies?.Any (v => v.StartsWith ("cookie=chocolate-chip;", StringComparison.Ordinal)) == true; + + if (!completed || !managedCookieResult || !nativeCookieResult || !managedHasExpectedCookie || !nativeHasExpectedCookie) TestRuntime.IgnoreInCI ("Transient network failure - ignore in CI"); - Assert.IsTrue (completed, "Network request completed"); - Assert.IsNull (ex, "Exception"); - Assert.IsTrue (managedCookieResult, $"Failed to get managed cookies"); - Assert.IsTrue (nativeCookieResult, $"Failed to get native cookies"); - Assert.That (managedCookies.Any (v => v.StartsWith ("cookie=chocolate-chip;", StringComparison.Ordinal)), Is.True, $"Managed Cookie Value"); - Assert.That (nativeCookies.Any (v => v.StartsWith ("cookie=chocolate-chip;", StringComparison.Ordinal)), Is.True, $"Native Cookie Value"); + Assert.That (completed, Is.True, "Network request completed"); + Assert.That (ex, Is.Null, "Exception"); + Assert.That (managedCookieResult, Is.True, $"Failed to get managed cookies"); + Assert.That (nativeCookieResult, Is.True, $"Failed to get native cookies"); + Assert.That (managedHasExpectedCookie, Is.True, $"Managed Cookie Value"); + Assert.That (nativeHasExpectedCookie, Is.True, $"Native Cookie Value"); } // ensure that we can use a cookie container to set the cookies for a url @@ -168,10 +175,10 @@ void TestNSUrlSessionHandlerCookieContainerImpl (NSUrlSessionHandler nativeHandl if (intermittentFailures.Any (v => managedCookieResult.Contains (v) || nativeCookieResult.Contains (v))) TestRuntime.IgnoreInCI ("Intermittent network failure - ignore in CI"); - Assert.IsTrue (completed, "Network request completed"); - Assert.IsNull (ex, "Exception"); - Assert.IsNotNull (managedCookieResult, "Managed cookies result"); - Assert.IsNotNull (nativeCookieResult, "Native cookies result"); + Assert.That (completed, Is.True, "Network request completed"); + Assert.That (ex, Is.Null, "Exception"); + Assert.That (managedCookieResult, Is.Not.Null, "Managed cookies result"); + Assert.That (nativeCookieResult, Is.Not.Null, "Native cookies result"); Assert.That (managedCookieResult, Does.Contain ("\"cookie\": \"chocolate-chip\""), "Managed cookies"); Assert.That (nativeCookieResult, Does.Contain ("\"cookie\": \"chocolate-chip\""), "Native cookies"); } @@ -197,11 +204,14 @@ public void TestNSurlSessionHandlerCookieContainerSetCookie () if (!completed) TestRuntime.IgnoreInCI ("Transient network failure - ignore in CI"); - Assert.IsTrue (completed, "Network request completed"); - Assert.IsNull (ex, "Exception"); - Assert.IsNotNull (nativeCookieResult, "Native cookies result"); + Assert.That (completed, Is.True, "Network request completed"); + Assert.That (ex, Is.Null, "Exception"); + Assert.That (nativeCookieResult, Is.Not.Null, "Native cookies result"); var cookiesFromServer = cookieContainer.GetCookies (new Uri (url)); - Assert.That (cookiesFromServer.Cast ().Any (v => v.Name == "cookie" && v.Value == "chocolate-chip"), Is.True, "Cookies received from server."); + var hasExpectedCookie = cookiesFromServer.Cast ().Any (v => v.Name == "cookie" && v.Value == "chocolate-chip"); + if (!hasExpectedCookie) + TestRuntime.IgnoreInCI ("Transient network failure - ignore in CI"); + Assert.That (hasExpectedCookie, Is.True, "Cookies received from server."); } [Test] @@ -231,11 +241,11 @@ public void TestNSUrlSessionDefaultDisabledCookies () if (!completed) TestRuntime.IgnoreInCI ("Transient network failure - ignore in CI"); - Assert.IsTrue (completed, "Network request completed"); - Assert.IsNull (ex, "Exception"); - Assert.IsNotNull (nativeSetCookieResult, "Native set-cookies result"); - Assert.IsNotNull (nativeCookieResult, "Native cookies result"); - Assert.IsFalse (nativeCookieResult.Contains ("chocolate-chip")); + Assert.That (completed, Is.True, "Network request completed"); + Assert.That (ex, Is.Null, "Exception"); + Assert.That (nativeSetCookieResult, Is.Not.Null, "Native set-cookies result"); + Assert.That (nativeCookieResult, Is.Not.Null, "Native cookies result"); + Assert.That (nativeCookieResult.Contains ("chocolate-chip"), Is.False); } [Test] @@ -266,13 +276,13 @@ public void TestNSUrlSessionDefaultDisableCookiesWithManagedContainer () if (!completed) TestRuntime.IgnoreInCI ("Transient network failure - ignore in CI"); - Assert.IsTrue (completed, "Network request completed"); - Assert.IsNull (ex, "Exception"); - Assert.IsNotNull (nativeSetCookieResult, "Native set-cookies result"); - Assert.IsNotNull (nativeCookieResult, "Native cookies result"); - Assert.IsFalse (nativeCookieResult.Contains ("chocolate-chip")); + Assert.That (completed, Is.True, "Network request completed"); + Assert.That (ex, Is.Null, "Exception"); + Assert.That (nativeSetCookieResult, Is.Not.Null, "Native set-cookies result"); + Assert.That (nativeCookieResult, Is.Not.Null, "Native cookies result"); + Assert.That (nativeCookieResult.Contains ("chocolate-chip"), Is.False); var cookiesFromServer = cookieContainer.GetCookies (new Uri (url)); - Assert.AreEqual (0, cookiesFromServer.Count, "Cookies received from server."); + Assert.That (cookiesFromServer.Count, Is.EqualTo (0), "Cookies received from server."); } [Test] @@ -417,12 +427,12 @@ public void TestNSUrlSessionTimeoutExceptionWhileStreamingContent () Assert.Inconclusive ("Test run timedout."); } - Assert.IsNull (ex, "Exception"); + Assert.That (ex, Is.Null, "Exception"); if (!timeoutExceptionShouldHaveBeenThrown) { Assert.Inconclusive ("Failed to produce a timeout. The response content was streamed completely."); } else { - Assert.IsTrue (timeoutExceptionWasThrown, "Timeout exception is thrown."); + Assert.That (timeoutExceptionWasThrown, Is.True, "Timeout exception is thrown."); } } @@ -457,8 +467,140 @@ public void RedirectionWithAuthorizationHeaders (Type handlerType) } else if (!containsHeaders) { Assert.Inconclusive ("Response from httpbin does not contain headers, therefore we cannot ensure that if the authoriation is present."); } else { - Assert.IsFalse (containsAuthorizarion, $"Authorization header did reach the final destination. {json}"); - Assert.IsNull (ex, $"Exception {ex} for {json}"); + Assert.That (containsAuthorizarion, Is.False, $"Authorization header did reach the final destination. {json}"); + Assert.That (ex, Is.Null, $"Exception {ex} for {json}"); + } + } + + [TestCase (true, false, HttpStatusCode.Unauthorized, false, TestName = "NSUrlSessionHandlerOriginCredentialCacheNotSentToCrossOriginRedirectTarget")] + [TestCase (true, true, HttpStatusCode.OK, true, TestName = "NSUrlSessionHandlerTargetCredentialCacheSentToCrossOriginRedirectTarget")] + [TestCase (false, false, HttpStatusCode.Unauthorized, false, TestName = "NSUrlSessionHandlerNetworkCredentialNotSentToCrossOriginRedirectTarget")] + public void NSUrlSessionHandlerCredentialsCrossOriginRedirectTarget (bool useCredentialCache, bool cacheRedirectTarget, HttpStatusCode expectedStatusCode, bool expectAuthorizationHeader) + { + if (!HttpListener.IsSupported) { + Assert.Inconclusive ("HttpListener is not supported"); + } + + using var server = new RedirectBasicAuthServer (crossOrigin: true); + using var handler = new NSUrlSessionHandler (); + var username = "origin-user"; + var password = "origin-password"; + + if (useCredentialCache) { + var cache = new CredentialCache (); + var credentialUri = cacheRedirectTarget ? new Uri (server.TargetUri, "protected") : server.OriginUri; + cache.Add (credentialUri, "basic", new NetworkCredential (username, password)); + handler.Credentials = cache; + } else { + handler.Credentials = new NetworkCredential (username, password); + } + + HttpStatusCode statusCode = HttpStatusCode.NotFound; + var done = TestRuntime.TryRunAsync (TimeSpan.FromSeconds (30), async () => { + using var client = new HttpClient (handler); + using var response = await client.GetAsync (new Uri (server.OriginUri, "start")); + statusCode = response.StatusCode; + }, out var ex); + + Assert.That (done, Is.True, "Request timed out."); + Assert.That (ex, Is.Null, "Exception"); + Assert.That (statusCode, Is.EqualTo (expectedStatusCode), "StatusCode"); + Assert.That (server.TargetRequestCount, Is.GreaterThanOrEqualTo (1), "Target request count"); + Assert.That (server.TargetAuthorizationHeaders.Length > 0, Is.EqualTo (expectAuthorizationHeader), "Authorization header presence."); + } + + [TestCase (false, HttpStatusCode.Unauthorized, TestName = "NSUrlSessionHandlerNetworkCredentialNotSentAfterSameOriginRedirectByDefault")] + [TestCase (true, HttpStatusCode.OK, TestName = "NSUrlSessionHandlerNetworkCredentialSentAfterSameOriginRedirectWithAppContextSwitch")] + public void NSUrlSessionHandlerNetworkCredentialSameOriginRedirectCredentials (bool allowSameOriginRedirectCredentials, HttpStatusCode expectedStatusCode) + { + if (!HttpListener.IsSupported) { + Assert.Inconclusive ("HttpListener is not supported"); + } + + AppContext.TryGetSwitch (AllowSameOriginRedirectCredentialsSwitch, out var originalValue); + try { + AppContext.SetSwitch (AllowSameOriginRedirectCredentialsSwitch, allowSameOriginRedirectCredentials); + + using var server = new RedirectBasicAuthServer (crossOrigin: false); + using var handler = new NSUrlSessionHandler { + Credentials = new NetworkCredential ("origin-user", "origin-password"), + }; + + HttpStatusCode statusCode = HttpStatusCode.NotFound; + var done = TestRuntime.TryRunAsync (TimeSpan.FromSeconds (30), async () => { + using var client = new HttpClient (handler); + using var response = await client.GetAsync (new Uri (server.OriginUri, "start")); + statusCode = response.StatusCode; + }, out var ex); + + Assert.That (done, Is.True, "Request timed out."); + Assert.That (ex, Is.Null, "Exception"); + Assert.That (statusCode, Is.EqualTo (expectedStatusCode), "StatusCode"); + Assert.That (server.TargetRequestCount, Is.GreaterThanOrEqualTo (1), "Target request count"); + Assert.That (server.TargetAuthorizationHeaders.Length > 0, Is.EqualTo (allowSameOriginRedirectCredentials), "Authorization header presence."); + } finally { + AppContext.SetSwitch (AllowSameOriginRedirectCredentialsSwitch, originalValue); + } + } + + [TestCase (false, HttpStatusCode.Unauthorized, false, TestName = "NSUrlSessionHandlerNetworkCredentialNotSentToCrossOriginRedirectWithDefaultCredentialStorage")] + [TestCase (true, HttpStatusCode.OK, true, TestName = "NSUrlSessionHandlerNetworkCredentialSentToCrossOriginRedirectWithSharedCredentialStorage")] + public void NSUrlSessionHandlerUseSharedCredentialStorage (bool useSharedCredentialStorage, HttpStatusCode expectedStatusCode, bool expectSecondRequestAuthorizationHeader) + { + if (!HttpListener.IsSupported) { + Assert.Inconclusive ("HttpListener is not supported"); + } + + AppContext.TryGetSwitch (UseSharedCredentialStorageSwitch, out var originalValue); + try { + AppContext.SetSwitch (UseSharedCredentialStorageSwitch, useSharedCredentialStorage); + + using var server = new RedirectBasicAuthServer (crossOrigin: true); + + // First, prime the shared credential storage by making a successful auth request + // using a CredentialCache with the target URI. When shared storage is enabled, + // NSUrlSession stores the credential with ForSession persistence in SharedCredentialStorage, + // making it available to subsequent handlers targeting the same host:port. + var cache = new CredentialCache (); + cache.Add (new Uri (server.TargetUri, "protected"), "basic", new NetworkCredential ("origin-user", "origin-password")); + + using (var primingHandler = new NSUrlSessionHandler { Credentials = cache }) { + var primingDone = TestRuntime.TryRunAsync (TimeSpan.FromSeconds (30), async () => { + using var client = new HttpClient (primingHandler); + using var response = await client.GetAsync (new Uri (server.OriginUri, "start")); + }, out var primingEx); + + Assert.That (primingDone, Is.True, "Priming request timed out."); + Assert.That (primingEx, Is.Null, "Priming exception"); + } + + // Record how many auth headers the server received from the priming request + var authHeadersAfterPriming = server.TargetAuthorizationHeaders.Length; + + // Now make a second request with a NetworkCredential (not CredentialCache) to the same server. + // With shared storage enabled, NSUrlSession finds cached credentials in SharedCredentialStorage + // and pre-emptively authenticates the redirect target without calling DidReceiveChallenge. + // With shared storage disabled (default), no stored credentials exist, and the + // DidReceiveChallenge delegate blocks the NetworkCredential after the cross-origin redirect. + using var handler = new NSUrlSessionHandler { + Credentials = new NetworkCredential ("origin-user", "origin-password"), + }; + + HttpStatusCode statusCode = HttpStatusCode.NotFound; + var done = TestRuntime.TryRunAsync (TimeSpan.FromSeconds (30), async () => { + using var client = new HttpClient (handler); + using var response = await client.GetAsync (new Uri (server.OriginUri, "start")); + statusCode = response.StatusCode; + }, out var ex); + + Assert.That (done, Is.True, "Request timed out."); + Assert.That (ex, Is.Null, "Exception"); + Assert.That (statusCode, Is.EqualTo (expectedStatusCode), "StatusCode"); + + var authHeadersFromSecondRequest = server.TargetAuthorizationHeaders.Length - authHeadersAfterPriming; + Assert.That (authHeadersFromSecondRequest > 0, Is.EqualTo (expectSecondRequestAuthorizationHeader), "Authorization header on second request."); + } finally { + AppContext.SetSwitch (UseSharedCredentialStorageSwitch, originalValue); } } @@ -531,13 +673,13 @@ public void RejectSslCertificatesServicePointManager (Type handlerType) Assert.Inconclusive ("Request timedout."); } else { // the ServicePointManager.ServerCertificateValidationCallback will never be executed. - Assert.False (invalidServicePointManagerCbWasExcuted, "Invalid SPM executed"); - Assert.True (validationCbWasExecuted, "Validation Callback called"); + Assert.That (invalidServicePointManagerCbWasExcuted, Is.False, "Invalid SPM executed"); + Assert.That (validationCbWasExecuted, Is.True, "Validation Callback called"); // assert the exception type - Assert.IsNotNull (ex, (result is null) ? "Expected exception is missing and got no result" : $"Expected exception but got {result.Content.ReadAsStringAsync ().Result}"); - Assert.IsInstanceOf (typeof (HttpRequestException), ex, "Exception type"); - Assert.IsNotNull (ex.InnerException, "InnerException"); - Assert.IsInstanceOf (expectedExceptionType, ex.InnerException, "InnerException type"); + Assert.That (ex, Is.Not.Null, (result is null) ? "Expected exception is missing and got no result" : $"Expected exception but got {result.Content.ReadAsStringAsync ().Result}"); + Assert.That (ex, Is.InstanceOf (typeof (HttpRequestException)), "Exception type"); + Assert.That (ex.InnerException, Is.Not.Null, "InnerException"); + Assert.That (ex.InnerException, Is.InstanceOf (expectedExceptionType), "InnerException type"); } } @@ -585,11 +727,12 @@ public void AcceptSslCertificatesServicePointManager (Type handlerType) // assert that we did not get an exception if (ex is not null && ex.InnerException is not null) { // we could get here.. if we have a diff issue, in that case, lets get the exception message and assert is not the trust issue - Assert.AreNotEqual (ex.InnerException.Message, "Error: TrustFailure"); + Assert.That (ex.InnerException.Message, Is.Not.EqualTo ("Error: TrustFailure")); } } - Assert.IsNull (ex); - // Assert.IsTrue (servicePointManagerCbWasExcuted, "Executed"); + TestRuntime.IgnoreInCIIfBadNetwork (ex); + Assert.That (ex, Is.Null); + // Assert.That (servicePointManagerCbWasExcuted, Is.True, "Executed"); } [Ignore ("https://github.com/dotnet/macios/issues/21912")] @@ -622,12 +765,12 @@ public void AcceptSslCertificatesWithCustomValidationCallbackNSUrlSessionHandler if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail Assert.Inconclusive ("Request timedout."); } else { - Assert.True (callbackWasExecuted, "Validation Callback called"); - Assert.AreNotEqual (SslPolicyErrors.None, sslPolicyErrors, "Callback was called with unexpected SslPolicyErrors"); - Assert.IsNotNull (serverCertificate, "Server certificate is null"); - Assert.IsNull (ex, "Exception wasn't expected."); - Assert.IsNotNull (result, "Result was null"); - Assert.IsTrue (result.IsSuccessStatusCode, $"Status code was not success: {result.StatusCode}"); + Assert.That (callbackWasExecuted, Is.True, "Validation Callback called"); + Assert.That (sslPolicyErrors, Is.Not.EqualTo (SslPolicyErrors.None), "Callback was called with unexpected SslPolicyErrors"); + Assert.That (serverCertificate, Is.Not.Null, "Server certificate is null"); + Assert.That (ex, Is.Null, "Exception wasn't expected."); + Assert.That (result, Is.Not.Null, "Result was null"); + Assert.That (result.IsSuccessStatusCode, Is.True, $"Status code was not success: {result.StatusCode}"); } } @@ -645,10 +788,10 @@ public void RejectSslCertificatesWithCustomValidationCallbackNSUrlSessionHandler ServerCertificateCustomValidationCallback = (sender, certificate, chain, errors) => { callbackWasExecuted = true; try { - Assert.IsNotNull (certificate); + Assert.That (certificate, Is.Not.Null); if (errors == SslPolicyErrors.RemoteCertificateChainErrors && TestRuntime.IsInCI) return false; - Assert.AreEqual (SslPolicyErrors.None, errors); + Assert.That (errors, Is.EqualTo (SslPolicyErrors.None)); } catch (ResultStateException) { throw; } catch (Exception e) { @@ -666,12 +809,12 @@ public void RejectSslCertificatesWithCustomValidationCallbackNSUrlSessionHandler if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail Assert.Inconclusive ("Request timedout."); } else { - Assert.True (callbackWasExecuted, "Validation Callback called."); - Assert.IsNotNull (ex, result is null ? "Expected exception is missing and got no result." : $"Expected exception but got {result.Content.ReadAsStringAsync ().Result}."); - Assert.IsInstanceOf (typeof (HttpRequestException), ex, "Exception type"); - Assert.IsNotNull (ex.InnerException, "InnerException"); - Assert.IsInstanceOf (typeof (WebException), ex.InnerException, "InnerException type"); - Assert.IsNull (ex2, "Callback asserts"); + Assert.That (callbackWasExecuted, Is.True, "Validation Callback called."); + Assert.That (ex, Is.Not.Null, result is null ? "Expected exception is missing and got no result." : $"Expected exception but got {result.Content.ReadAsStringAsync ().Result}."); + Assert.That (ex, Is.InstanceOf (typeof (HttpRequestException)), "Exception type"); + Assert.That (ex.InnerException, Is.Not.Null, "InnerException"); + Assert.That (ex.InnerException, Is.InstanceOf (typeof (WebException)), "InnerException type"); + Assert.That (ex2, Is.Null, "Callback asserts"); } } @@ -704,9 +847,9 @@ public void TestNSUrlSessionHandlerSendClientCertificate () Assert.Inconclusive ("Request timedout."); } else { TestRuntime.IgnoreInCIIfBadNetwork (ex); - Assert.IsNull (ex, "Exception wasn't expected."); + Assert.That (ex, Is.Null, "Exception wasn't expected."); X509Certificate2 certificate2 = X509CertificateLoader.LoadCertificate (global::System.Convert.FromBase64String (content)); - Assert.AreEqual (certificate.Thumbprint, certificate2.Thumbprint); + Assert.That (certificate2.Thumbprint, Is.EqualTo (certificate.Thumbprint)); } } @@ -725,8 +868,8 @@ public void TestNSUrlSessionHandlerOptionalClientCertificate () var response = await client.GetAsync ($"https://localhost:{port}/"); response.EnsureSuccessStatusCode (); }, out var ex); - Assert.IsTrue (done, "Request to localhost timed out."); - Assert.IsNull (ex, $"Exception wasn't expected, but got: {ex}"); + Assert.That (done, Is.True, "Request to localhost timed out."); + Assert.That (ex, Is.Null, $"Exception wasn't expected, but got: {ex}"); } finally { listener?.Cancel (); listener?.Dispose (); @@ -747,12 +890,12 @@ public void TestNSUrlSessionHandlerDetectMissingClientCertificate () using var client = new HttpClient (handler); await client.GetAsync ($"https://localhost:{port}/"); }, out var ex); - Assert.IsTrue (done, "Request to localhost timed out."); - Assert.IsNotNull (ex, "Exception was expected."); - Assert.IsInstanceOf (typeof (HttpRequestException), ex, "Exception"); - Assert.IsInstanceOf (typeof (WebException), ex!.InnerException, "InnerException Type"); + Assert.That (done, Is.True, "Request to localhost timed out."); + Assert.That (ex, Is.Not.Null, "Exception was expected."); + Assert.That (ex, Is.InstanceOf (typeof (HttpRequestException)), "Exception"); + Assert.That (ex!.InnerException, Is.InstanceOf (typeof (WebException)), "InnerException Type"); Assert.That (((WebException) ex.InnerException!).Status, Is.EqualTo (WebExceptionStatus.SecureChannelFailure), "InnerException Status"); - Assert.IsInstanceOf (typeof (AuthenticationException), ex.InnerException.InnerException, "InnerException.InnerException Type"); + Assert.That (ex.InnerException.InnerException, Is.InstanceOf (typeof (AuthenticationException)), "InnerException.InnerException Type"); } finally { listener?.Cancel (); listener?.Dispose (); @@ -775,11 +918,11 @@ public void TestNSUrlSessionHandlerDetectMissingClientCertificateOptOut () using var client = new HttpClient (handler); await client.GetAsync ($"https://localhost:{port}/"); }, out var ex); - Assert.IsTrue (done, "Request to localhost timed out."); + Assert.That (done, Is.True, "Request to localhost timed out."); // With the opt-out switch enabled, the new specific exception is not thrown. // Instead we get a generic connection error (no WebException/AuthenticationException chain). - Assert.IsNotNull (ex, "Exception was expected."); - Assert.IsInstanceOf (typeof (HttpRequestException), ex, "Exception"); + Assert.That (ex, Is.Not.Null, "Exception was expected."); + Assert.That (ex, Is.InstanceOf (typeof (HttpRequestException)), "Exception"); if (ex!.InnerException is WebException we) Assert.That (we.Status, Is.Not.EqualTo (WebExceptionStatus.SecureChannelFailure), "Should not be SecureChannelFailure"); } finally { @@ -860,17 +1003,165 @@ static NWListener CreateNWTlsListener (bool requireClientCert) return (cert.Export (X509ContentType.Pfx, password), password); } + sealed class RedirectBasicAuthServer : IDisposable { + readonly bool crossOrigin; + readonly HttpListener originListener; + readonly HttpListener? targetListener; + readonly Task originTask; + readonly Task? targetTask; + readonly object targetAuthorizationHeadersLock = new object (); + readonly List targetAuthorizationHeaders = new List (); + readonly string expectedBasicAuth; + int targetRequestCount; + + public Uri OriginUri { get; } + public Uri TargetUri { get; } + public int TargetRequestCount => Volatile.Read (ref targetRequestCount); + + public string [] TargetAuthorizationHeaders { + get { + lock (targetAuthorizationHeadersLock) + return targetAuthorizationHeaders.ToArray (); + } + } + + public RedirectBasicAuthServer (bool crossOrigin, string username = "origin-user", string password = "origin-password") + { + this.crossOrigin = crossOrigin; + expectedBasicAuth = "Basic " + Convert.ToBase64String (global::System.Text.Encoding.UTF8.GetBytes ($"{username}:{password}")); + originListener = CreateStartedHttpListener (out var originUri); + OriginUri = originUri; + + if (crossOrigin) { + targetListener = CreateStartedHttpListener (out var targetUri); + TargetUri = targetUri; + } else { + TargetUri = OriginUri; + } + + originTask = Task.Run (RunOrigin); + if (targetListener is not null) + targetTask = Task.Run (RunTarget); + } + + async Task RunOrigin () + { + while (true) { + var context = await GetContextAsync (originListener); + if (context is null) + return; + + if (!crossOrigin && string.Equals (context.Request.Url?.AbsolutePath, "/protected", StringComparison.Ordinal)) { + RespondToProtectedResource (context); + } else { + RespondWithRedirect (context); + } + } + } + + async Task RunTarget () + { + if (targetListener is null) + return; + + while (true) { + var context = await GetContextAsync (targetListener); + if (context is null) + return; + + RespondToProtectedResource (context); + } + } + + void RespondWithRedirect (HttpListenerContext context) + { + var response = context.Response; + response.StatusCode = (int) HttpStatusCode.Redirect; + response.RedirectLocation = new Uri (TargetUri, "protected").AbsoluteUri; + response.Close (); + } + + void RespondToProtectedResource (HttpListenerContext context) + { + Interlocked.Increment (ref targetRequestCount); + + var authorization = context.Request.Headers ["Authorization"]; + if (!string.IsNullOrEmpty (authorization)) { + lock (targetAuthorizationHeadersLock) + targetAuthorizationHeaders.Add (authorization); + } + + var response = context.Response; + if (string.Equals (authorization, expectedBasicAuth, StringComparison.Ordinal)) { + response.StatusCode = (int) HttpStatusCode.OK; + } else { + response.StatusCode = (int) HttpStatusCode.Unauthorized; + response.AddHeader ("WWW-Authenticate", "Basic realm=\"redirect-target\""); + } + response.Close (); + } + + static async Task GetContextAsync (HttpListener listener) + { + try { + return await listener.GetContextAsync (); + } catch (HttpListenerException) { + return null; + } catch (ObjectDisposedException) { + return null; + } catch (InvalidOperationException) { + return null; + } + } + + static HttpListener CreateStartedHttpListener (out Uri uri) + { + const int MinPort = 49215; + const int MaxPort = 65535; + + for (var port = MinPort; port < MaxPort; port++) { + var listener = new HttpListener (); + var url = $"http://127.0.0.1:{port}/"; + listener.Prefixes.Add (url); + try { + listener.Start (); + uri = new Uri (url); + return listener; + } catch { + listener.Close (); + } + } + + throw new InvalidOperationException ("Could not start a local HTTP listener."); + } + + public void Dispose () + { + originListener.Close (); + targetListener?.Close (); + + try { + if (targetTask is null) + Task.WaitAll (new [] { originTask }, TimeSpan.FromSeconds (1)); + else + Task.WaitAll (new [] { originTask, targetTask }, TimeSpan.FromSeconds (1)); + } catch { + // Listener disposal wakes the request loops. + } + } + } + [Test] public void AssertDefaultValuesNSUrlSessionHandler () { using (var handler = new NSUrlSessionHandler ()) { - Assert.True (handler.AllowAutoRedirect, "Default redirects value"); - Assert.True (handler.AllowsCellularAccess, "Default cellular data value."); + Assert.That (handler.AllowAutoRedirect, Is.True, "Default redirects value"); + Assert.That (handler.AllowsCellularAccess, Is.True, "Default cellular data value."); } using (var config = NSUrlSessionConfiguration.DefaultSessionConfiguration) { config.AllowsCellularAccess = false; using (var handler = new NSUrlSessionHandler (config)) { - Assert.False (handler.AllowsCellularAccess, "Configuration cellular data value."); + Assert.That (handler.AllowsCellularAccess, Is.False, "Configuration cellular data value."); } } } @@ -896,9 +1187,10 @@ public void GHIssue8342 (HttpStatusCode expectedStatus, string validUsername, st if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail Assert.Inconclusive ("Request timedout."); } else { + TestRuntime.IgnoreInCIIfBadNetwork (ex); TestRuntime.IgnoreInCIIfBadNetwork (httpStatus); - Assert.IsNull (ex, "Exception not null"); - Assert.AreEqual (expectedStatus, httpStatus, "Status not ok"); + Assert.That (ex, Is.Null, "Exception not null"); + Assert.That (httpStatus, Is.EqualTo (expectedStatus), "Status not ok"); } } @@ -922,9 +1214,10 @@ public void SupportsDigestAuthentication (HttpStatusCode expectedStatus, string if (!done) { Assert.Inconclusive ("Request timedout."); } else { + TestRuntime.IgnoreInCIIfBadNetwork (ex); TestRuntime.IgnoreInCIIfBadNetwork (httpStatus); - Assert.IsNull (ex, "Exception not null"); - Assert.AreEqual (expectedStatus, httpStatus, "Status not ok"); + Assert.That (ex, Is.Null, "Exception not null"); + Assert.That (httpStatus, Is.EqualTo (expectedStatus), "Status not ok"); } } @@ -953,8 +1246,8 @@ public void GHIssue8344 () Assert.Inconclusive ("First request timedout."); } else { TestRuntime.IgnoreInCIIfBadNetwork (httpStatus); - Assert.IsNull (ex, "First request exception not null"); - Assert.AreEqual (HttpStatusCode.OK, httpStatus, "First status not ok"); + Assert.That (ex, Is.Null, "First request exception not null"); + Assert.That (httpStatus, Is.EqualTo (HttpStatusCode.OK), "First status not ok"); } // exactly same operation, diff handler, wrong password, should fail @@ -974,8 +1267,8 @@ public void GHIssue8344 () Assert.Inconclusive ("Second request timedout."); } else { TestRuntime.IgnoreInCIIfBadNetwork (httpStatus); - Assert.IsNull (ex, "Second request exception not null"); - Assert.AreEqual (HttpStatusCode.Unauthorized, httpStatus, "Second status not ok"); + Assert.That (ex, Is.Null, "Second request exception not null"); + Assert.That (httpStatus, Is.EqualTo (HttpStatusCode.Unauthorized), "Second status not ok"); } } @@ -1033,14 +1326,15 @@ public void GHIssue16339 () if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail Assert.Inconclusive ("Request timedout."); } else { - Assert.IsNull (ex, "Exception"); + TestRuntime.IgnoreInCIIfBadNetwork (ex); + Assert.That (ex, Is.Null, "Exception"); for (var i = 0; i < iterations; i++) { var rsp = delegatingHandler.Responses [i]; TestRuntime.IgnoreInCIIfBadNetwork (rsp.StatusCode); - Assert.IsTrue (delegatingHandler.IsCompleted (i), $"Completed #{i}"); - Assert.AreEqual ("OK", rsp.ReasonPhrase, $"ReasonPhrase #{i}"); - Assert.AreEqual (HttpStatusCode.OK, rsp.StatusCode, $"StatusCode #{i}"); + Assert.That (delegatingHandler.IsCompleted (i), Is.True, $"Completed #{i}"); + Assert.That (rsp.ReasonPhrase, Is.EqualTo ("OK"), $"ReasonPhrase #{i}"); + Assert.That (rsp.StatusCode, Is.EqualTo (HttpStatusCode.OK), $"StatusCode #{i}"); var body = bodies [i]; // Poor-man's json parser @@ -1048,7 +1342,7 @@ public void GHIssue16339 () data = data.Trim ().Replace ("\"data\": \"", "").TrimEnd ('"', ','); data = data.Replace ("\\\"", "\""); - Assert.AreEqual (json, data, $"Post data #{i}"); + Assert.That (data, Is.EqualTo (json), $"Post data #{i}"); } } } @@ -1064,17 +1358,17 @@ public void UpdateRequestUriAfterRedirect (Type handlerType) var postRequestUri = NetworkResources.Httpbin.Url + "/"; var initialRequestUri = NetworkResources.Httpbin.GetRedirectToUrl (postRequestUri); var request = new HttpRequestMessage (HttpMethod.Get, initialRequestUri); - Assert.AreEqual (initialRequestUri, request.RequestUri.ToString (), "Initial RequestUri"); + Assert.That (request.RequestUri.ToString (), Is.EqualTo (initialRequestUri), "Initial RequestUri"); var response = await client.SendAsync (request); TestRuntime.IgnoreInCIIfBadNetwork (response.StatusCode); - Assert.AreEqual (postRequestUri, request.RequestUri.ToString (), "Post RequestUri"); + Assert.That (request.RequestUri.ToString (), Is.EqualTo (postRequestUri), "Post RequestUri"); }, out var ex); if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc. we do not want to fail Assert.Inconclusive ("Request timedout."); } else { TestRuntime.IgnoreInCIIfBadNetwork (ex); - Assert.IsNull (ex, "Exception"); + Assert.That (ex, Is.Null, "Exception"); } } @@ -1088,17 +1382,17 @@ public void RequestUriNotUpdatedIfNotRedirect (Type handlerType) var client = new HttpClient (GetHandler (handlerType)); var requestUri = NetworkResources.Httpbin.Uri + "?stuffHere=[]{}"; var request = new HttpRequestMessage (HttpMethod.Get, requestUri); - Assert.AreEqual (requestUri, request.RequestUri.ToString (), "Initial RequestUri"); + Assert.That (request.RequestUri.ToString (), Is.EqualTo (requestUri), "Initial RequestUri"); var response = await client.SendAsync (request); TestRuntime.IgnoreInCIIfBadNetwork (response.StatusCode); - Assert.AreEqual (requestUri, request.RequestUri.ToString (), "Post RequestUri"); + Assert.That (request.RequestUri.ToString (), Is.EqualTo (requestUri), "Post RequestUri"); }, out var ex); if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc. we do not want to fail Assert.Inconclusive ("Request timedout."); } else { TestRuntime.IgnoreInCIIfBadNetwork (ex); - Assert.IsNull (ex, "Exception"); + Assert.That (ex, Is.Null, "Exception"); } } @@ -1135,7 +1429,7 @@ void SslCertificatesWithoutOCSPEndPointsNSUrlSessionHandler (string url, X509Ver if (verificationFlags.HasValue) handler.CertificateChainPolicy.VerificationFlags = verificationFlags.Value; - Assert.IsTrue (handler.CheckCertificateRevocationList, "CheckCertificateRevocationList"); + Assert.That (handler.CheckCertificateRevocationList, Is.True, "CheckCertificateRevocationList"); for (var i = 0; i < 3; i++) { callbackWasExecuted = false; @@ -1170,11 +1464,11 @@ void SslCertificatesWithoutOCSPEndPointsNSUrlSessionHandler (string url, X509Ver if (!callbackWasExecuted) Assert.Inconclusive ("Validation callback was not called."); - Assert.AreEqual (expectedError, sslPolicyErrors, "Callback was called with unexpected SslPolicyErrors"); - Assert.IsNotNull (serverCertificate, "Server certificate is null"); - Assert.IsNull (ex, "Exception wasn't expected."); - Assert.IsNotNull (result, "Result was null"); - Assert.IsTrue (result.IsSuccessStatusCode, $"Status code was not success: {result.StatusCode}"); + Assert.That (sslPolicyErrors, Is.EqualTo (expectedError), "Callback was called with unexpected SslPolicyErrors"); + Assert.That (serverCertificate, Is.Not.Null, "Server certificate is null"); + Assert.That (ex, Is.Null, "Exception wasn't expected."); + Assert.That (result, Is.Not.Null, "Result was null"); + Assert.That (result.IsSuccessStatusCode, Is.True, $"Status code was not success: {result.StatusCode}"); } } } diff --git a/tests/monotouch-test/System.Net.Http/NSUrlSessionHandlerTest.cs b/tests/monotouch-test/System.Net.Http/NSUrlSessionHandlerTest.cs index 7f63862663b0..79c787d387c1 100644 --- a/tests/monotouch-test/System.Net.Http/NSUrlSessionHandlerTest.cs +++ b/tests/monotouch-test/System.Net.Http/NSUrlSessionHandlerTest.cs @@ -3,7 +3,10 @@ // using System; +using System.Net; using System.Net.Http; +using System.Text; +using System.Threading; using System.Threading.Tasks; using Foundation; using NUnit.Framework; @@ -47,10 +50,10 @@ public void DecompressedResponseDoesNotHaveContentEncodingOrContentLength () Assert.Inconclusive ("Request timed out."); } TestRuntime.IgnoreInCIIfBadNetwork (ex); - Assert.IsNull (ex, $"Exception: {ex}"); - Assert.IsTrue (noContentEncoding, "Content-Encoding header should be removed for decompressed content"); - Assert.IsTrue (noContentLength, "Content-Length header should be removed for decompressed content"); - Assert.IsTrue (body.Contains ("\"gzipped\"", StringComparison.OrdinalIgnoreCase), "Response body should contain decompressed gzip data"); + Assert.That (ex, Is.Null, $"Exception: {ex}"); + Assert.That (noContentEncoding, Is.True, "Content-Encoding header should be removed for decompressed content"); + Assert.That (noContentLength, Is.True, "Content-Length header should be removed for decompressed content"); + Assert.That (body.Contains ("\"gzipped\"", StringComparison.OrdinalIgnoreCase), Is.True, "Response body should contain decompressed gzip data"); } // https://github.com/dotnet/macios/issues/23958 @@ -86,11 +89,11 @@ public void NonCompressedResponseHasContentLength () Assert.Inconclusive ("Request timed out."); } TestRuntime.IgnoreInCIIfBadNetwork (ex); - Assert.IsNull (ex, $"Exception: {ex}"); - Assert.IsTrue (noContentEncoding, "Content-Encoding should not be present for non-compressed content"); - Assert.IsNotNull (contentLength, "Content-Length header should be present for non-compressed content"); - Assert.IsTrue (contentLength > 0, "Content-Length should be greater than zero"); - Assert.IsTrue (body.Length > 0, "Response body should not be empty"); + Assert.That (ex, Is.Null, $"Exception: {ex}"); + Assert.That (noContentEncoding, Is.True, "Content-Encoding should not be present for non-compressed content"); + Assert.That (contentLength, Is.Not.Null, "Content-Length header should be present for non-compressed content"); + Assert.That (contentLength > 0, Is.True, "Content-Length should be greater than zero"); + Assert.That (body.Length > 0, Is.True, "Response body should not be empty"); } // https://github.com/dotnet/macios/issues/23958 @@ -125,10 +128,10 @@ public void KeepHeadersAfterDecompressionSwitch () Assert.Inconclusive ("Request timed out."); } TestRuntime.IgnoreInCIIfBadNetwork (ex); - Assert.IsNull (ex, $"Exception: {ex}"); - Assert.IsTrue (hasContentEncoding, "Content-Encoding header should be preserved when KeepHeadersAfterDecompression is enabled"); - Assert.IsTrue (hasContentLength, "Content-Length header should be preserved when KeepHeadersAfterDecompression is enabled"); - Assert.IsTrue (body.Contains ("\"gzipped\"", StringComparison.OrdinalIgnoreCase), "Response body should contain decompressed gzip data"); + Assert.That (ex, Is.Null, $"Exception: {ex}"); + Assert.That (hasContentEncoding, Is.True, "Content-Encoding header should be preserved when KeepHeadersAfterDecompression is enabled"); + Assert.That (hasContentLength, Is.True, "Content-Length header should be preserved when KeepHeadersAfterDecompression is enabled"); + Assert.That (body.Contains ("\"gzipped\"", StringComparison.OrdinalIgnoreCase), Is.True, "Response body should contain decompressed gzip data"); } finally { AppContext.SetSwitch ("Foundation.NSUrlSessionHandler.KeepHeadersAfterDecompression", false); } @@ -145,8 +148,8 @@ public void DisposeAndRecreateBackgroundSessionHandler () using (var handler = new NSUrlSessionHandler (NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration ("test-id"))) { using (var client = new HttpClient (handler)) { var response = await client.GetByteArrayAsync (NetworkResources.MicrosoftUrl); - Assert.IsNotNull (response, "First request response"); - Assert.IsTrue (response.Length > 0, "First request response length"); + Assert.That (response, Is.Not.Null, "First request response"); + Assert.That (response.Length > 0, Is.True, "First request response length"); firstRequestSucceeded = true; } } @@ -159,15 +162,15 @@ public void DisposeAndRecreateBackgroundSessionHandler () IgnoreIfExceptionDueToBackgroundServiceInUseByAnotherProcess (ex); TestRuntime.IgnoreInCIIfBadNetwork (ex); - Assert.IsNull (ex, "First request exception"); + Assert.That (ex, Is.Null, "First request exception"); // Second request with new handler using same background session ID - should not timeout done = TestRuntime.TryRunAsync (TimeSpan.FromSeconds (30), async () => { using (var handler = new NSUrlSessionHandler (NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration ("test-id"))) { using (var client = new HttpClient (handler)) { var response = await client.GetByteArrayAsync (NetworkResources.MicrosoftUrl); - Assert.IsNotNull (response, "Second request response"); - Assert.IsTrue (response.Length > 0, "Second request response length"); + Assert.That (response, Is.Not.Null, "Second request response"); + Assert.That (response.Length > 0, Is.True, "Second request response length"); } } }, out ex); @@ -197,7 +200,7 @@ public void DisposeAndRecreateBackgroundSessionHandler () // * Detect this scenario here, and just mark the test as inconclusive. The test does something somewhat unusual (create two background sessions with the same identifier in quick succession), so this seems like the best approach for now. Assert.Inconclusive ("The previous background session wasn't fully invalidated before we tried to create a new background session (with the same identifier)"); } - Assert.IsNull (ex, "Second request exception"); + Assert.That (ex, Is.Null, "Second request exception"); } void IgnoreIfExceptionDueToBackgroundServiceInUseByAnotherProcess (Exception? e) @@ -216,5 +219,129 @@ void IgnoreIfExceptionDueToBackgroundServiceInUseByAnotherProcess (Exception? e) Assert.Ignore ("The background service is in use by another process."); } + + // https://github.com/dotnet/macios/issues/25485 + [Test] + public void BasicAuthWorksWhenBearerIsAdvertisedFirst () + { + if (!HttpListener.IsSupported) { + Assert.Inconclusive ("HttpListener is not supported"); + } + + const string username = "admin"; + const string password = "secret"; + var expectedBasicValue = Convert.ToBase64String (Encoding.UTF8.GetBytes ($"{username}:{password}")); + + var serverReady = new SemaphoreSlim (0, 1); + int requestIndex = 0; + int firstUnauthenticatedIndex = -1; + int firstAuthenticatedIndex = -1; + + var httpListener = StartListenerOnAvailablePort (out var listeningPort); + if (httpListener is null) { + Assert.Inconclusive ("Could not find an available port for the test server."); + return; + } + + var serverTask = Task.Run (async () => { + serverReady.Release (); + try { + while (httpListener.IsListening) { + var context = await httpListener.GetContextAsync ().ConfigureAwait (false); + var request = context.Request; + var response = context.Response; + + var authHeader = request.Headers ["Authorization"]; + var currentIndex = Interlocked.Increment (ref requestIndex); + if (authHeader is not null && authHeader == $"Basic {expectedBasicValue}") { + // Authenticated - return success + Interlocked.CompareExchange (ref firstAuthenticatedIndex, currentIndex, -1); + response.StatusCode = 200; + var body = Encoding.UTF8.GetBytes ("authenticated"); + response.ContentLength64 = body.Length; + response.OutputStream.Write (body, 0, body.Length); + } else { + // Return 401 with Bearer first, then Basic + Interlocked.CompareExchange (ref firstUnauthenticatedIndex, currentIndex, -1); + response.StatusCode = 401; + response.AddHeader ("WWW-Authenticate", "Bearer realm=\"test\", charset=\"UTF-8\""); + response.AppendHeader ("WWW-Authenticate", "Basic realm=\"test\", charset=\"UTF-8\""); + } + response.Close (); + } + } catch (ObjectDisposedException) { + // listener was stopped + } catch (HttpListenerException) { + // listener was stopped + } + }); + + HttpStatusCode? statusCode = null; + string responseBody = null; + + try { + var done = TestRuntime.TryRunAsync (TimeSpan.FromSeconds (30), async () => { + await serverReady.WaitAsync ().ConfigureAwait (false); + + using var handler = new NSUrlSessionHandler (); + handler.Credentials = new NetworkCredential (username, password); + using var client = new HttpClient (handler); + // Use 127.0.0.1 instead of localhost to avoid IPv6 resolution + // issues where NSUrlSession may connect to ::1 while + // HttpListener only binds to IPv4. + using var request = new HttpRequestMessage (HttpMethod.Get, $"http://127.0.0.1:{listeningPort}/test"); + var response = await client.SendAsync (request).ConfigureAwait (false); + statusCode = response.StatusCode; + responseBody = await response.Content.ReadAsStringAsync ().ConfigureAwait (false); + }, out var ex); + + if (!done) { + TestRuntime.IgnoreInCI ("Transient localhost server failure - ignore in CI"); + Assert.Inconclusive ("Request timed out."); + } + TestRuntime.IgnoreInCIIfBadNetwork (ex); + Assert.That (ex, Is.Null, $"Exception: {ex}"); + // If no request reached the server, the failure is an infrastructure + // issue (e.g. port conflict), not a code bug. + if (Volatile.Read (ref requestIndex) == 0 && statusCode == HttpStatusCode.NotFound) { + TestRuntime.IgnoreInCI ($"Server received no requests and got status {statusCode} - infrastructure issue, ignore in CI"); + Assert.Inconclusive ($"Server received no requests; status was {statusCode}. Likely a port/binding issue."); + } + Assert.That (statusCode, Is.EqualTo (HttpStatusCode.OK), "Expected 200 OK after Basic auth negotiation"); + Assert.That (responseBody, Is.EqualTo ("authenticated"), "Response body"); + Assert.That (firstUnauthenticatedIndex, Is.GreaterThan (0), "Server should have received an unauthenticated request"); + Assert.That (firstAuthenticatedIndex, Is.GreaterThan (0), "Server should have received an authenticated request"); + Assert.That (firstUnauthenticatedIndex, Is.LessThan (firstAuthenticatedIndex), "Unauthenticated request should have arrived before the authenticated retry"); + + if (serverTask.IsFaulted) + Assert.Fail ($"Server task failed: {serverTask.Exception}"); + } finally { + httpListener.Stop (); + httpListener.Close (); + } + } + + static HttpListener? StartListenerOnAvailablePort (out int listeningPort) + { + // IANA suggested range for dynamic or private ports + const int MinPort = 49215; + const int MaxPort = 65535; + + for (var port = MinPort; port < MaxPort; port++) { + var listener = new HttpListener (); + listener.Prefixes.Add ($"http://127.0.0.1:{port}/"); + try { + listener.Start (); + listeningPort = port; + return listener; + } catch { + // port in use, try next + listener.Close (); + } + } + + listeningPort = -1; + return null; + } } } diff --git a/tests/monotouch-test/System.Net.Http/NetworkResources.cs b/tests/monotouch-test/System.Net.Http/NetworkResources.cs index 99fe7fc5c24f..6fa21fe58507 100644 --- a/tests/monotouch-test/System.Net.Http/NetworkResources.cs +++ b/tests/monotouch-test/System.Net.Http/NetworkResources.cs @@ -6,6 +6,7 @@ namespace MonoTests.System.Net.Http { [Preserve (AllMembers = true)] public static class NetworkResources { + public const string AppleHost = "apple.com"; public static string MicrosoftUrl => AssertNetworkConnection ("https://www.microsoft.com"); public static Uri MicrosoftUri => new Uri (MicrosoftUrl); public static string MicrosoftHttpUrl => AssertNetworkConnection ("http://www.microsoft.com"); diff --git a/tests/monotouch-test/SystemConfiguration/CaptiveNetworkTest.cs b/tests/monotouch-test/SystemConfiguration/CaptiveNetworkTest.cs index e38e3edd8f3f..e6da5b5ef926 100644 --- a/tests/monotouch-test/SystemConfiguration/CaptiveNetworkTest.cs +++ b/tests/monotouch-test/SystemConfiguration/CaptiveNetworkTest.cs @@ -56,7 +56,7 @@ public void TryCopyCurrentNetworkInfo () if (status == StatusCode.NoKey) return; - Assert.AreEqual (StatusCode.OK, status, "Status"); + Assert.That (status, Is.EqualTo (StatusCode.OK), "Status"); // It's quite complex to figure out whether we should get a dictionary back or not. // References: // * https://github.com/dotnet/macios/commit/24331f35dd67d19f3ed9aca7b8b21827ce0823c0 @@ -72,7 +72,7 @@ public void TryGetSupportedInterfaces () { #if !__TVOS__ var status = CaptiveNetwork.TryGetSupportedInterfaces (out var ifaces); - Assert.AreEqual (StatusCode.OK, status, "Status"); + Assert.That (status, Is.EqualTo (StatusCode.OK), "Status"); #endif // __TVOS__ } #endif @@ -92,7 +92,7 @@ public void MarkPortalOnline () #if !__TVOS__ - Assert.False (CaptiveNetwork.MarkPortalOnline ("xamxam")); + Assert.That (CaptiveNetwork.MarkPortalOnline ("xamxam"), Is.False); #endif } @@ -110,7 +110,7 @@ public void MarkPortalOffline () TestRuntime.AssertSystemVersion (ApplePlatform.MacOSX, 10, 8, throwIfOtherPlatform: false); #if !__TVOS__ - Assert.False (CaptiveNetwork.MarkPortalOffline ("xamxam")); + Assert.That (CaptiveNetwork.MarkPortalOffline ("xamxam"), Is.False); #endif } diff --git a/tests/monotouch-test/SystemConfiguration/NetworkReachabilityTest.cs b/tests/monotouch-test/SystemConfiguration/NetworkReachabilityTest.cs index e4da98fe4040..0c57a89ef086 100644 --- a/tests/monotouch-test/SystemConfiguration/NetworkReachabilityTest.cs +++ b/tests/monotouch-test/SystemConfiguration/NetworkReachabilityTest.cs @@ -14,6 +14,8 @@ using System.Net; using System.Threading; using System.Threading.Tasks; +using System.Net.Sockets; +using MonoTests.System.Net.Http; namespace MonoTouchFixtures.SystemConfiguration { @@ -26,7 +28,7 @@ public void CtorNameAddress () using (var nr = new NetworkReachability ("apple.com")) { NetworkReachabilityFlags flags; - Assert.IsTrue (nr.TryGetFlags (out flags)); + Assert.That (nr.TryGetFlags (out flags), Is.True); flags &= ~NetworkReachabilityFlags.TransientConnection; // Remove the TransientConnection flag if it's set Assert.That (flags, Is.EqualTo (NetworkReachabilityFlags.Reachable), "Reachable"); } @@ -38,27 +40,27 @@ public void CtorIPAddress () using (var nr = new NetworkReachability (IPAddress.Loopback)) { NetworkReachabilityFlags flags; - Assert.IsTrue (nr.TryGetFlags (out flags), "#1"); + Assert.That (nr.TryGetFlags (out flags), Is.True, "#1"); // inconsistent results across different iOS versions // < 9.0 -> Reachable | IsLocalAddress // 9.x -> Reachable | IsLocalAddress | IsDirect // 10.0 -> Reachable // so we're only checking the (most important) Reachable flag - Assert.True ((flags & NetworkReachabilityFlags.Reachable) != 0, "Reachable"); + Assert.That ((flags & NetworkReachabilityFlags.Reachable) != 0, Is.True, "Reachable"); } using (var nr = new NetworkReachability (new IPAddress (new byte [] { 10, 99, 99, 99 }))) { NetworkReachabilityFlags flags; - Assert.IsTrue (nr.TryGetFlags (out flags), "#2"); + Assert.That (nr.TryGetFlags (out flags), Is.True, "#2"); //Assert.That (flags, Is.EqualTo (NetworkReachabilityFlags.Reachable), "#2 Reachable"); } using (var nr = new NetworkReachability (IPAddress.IPv6Loopback)) { NetworkReachabilityFlags flags; - Assert.IsTrue (nr.TryGetFlags (out flags), "#3"); + Assert.That (nr.TryGetFlags (out flags), Is.True, "#3"); //Assert.That (flags, Is.EqualTo ( // NetworkReachabilityFlags.TransientConnection | NetworkReachabilityFlags.Reachable | NetworkReachabilityFlags.ConnectionRequired), "#3 Reachable"); } @@ -66,7 +68,7 @@ public void CtorIPAddress () using (var nr = new NetworkReachability (IPAddress.Parse ("2001:4860:4860::8844"))) { NetworkReachabilityFlags flags; - Assert.IsTrue (nr.TryGetFlags (out flags), "#4"); + Assert.That (nr.TryGetFlags (out flags), Is.True, "#4"); // TODO: Will probably change when IPv6 is enabled locally //Assert.That (flags, Is.EqualTo ( @@ -78,26 +80,43 @@ public void CtorIPAddress () [Test] public void CtorIPAddressPair () { - var address = Dns.GetHostAddresses ("apple.com") [0]; + IPAddress address; + try { + var addresses = Dns.GetHostAddresses (NetworkResources.AppleHost); + address = null; + foreach (var candidate in addresses) { + if (candidate.AddressFamily == AddressFamily.InterNetwork) { + address = candidate; + break; + } + } + if (address is null) + throw new InvalidOperationException ("No IPv4 address found."); + } catch (Exception e) { + TestRuntime.IgnoreInCIIfBadNetwork (e); + throw; + } + using (var nr = new NetworkReachability (IPAddress.Loopback, address)) { NetworkReachabilityFlags flags; - Assert.IsTrue (nr.TryGetFlags (out flags), "#1"); + Assert.That (nr.TryGetFlags (out flags), Is.True, "#1"); CheckLoopbackFlags (flags, "1", true); } using (var nr = new NetworkReachability (null, address)) { NetworkReachabilityFlags flags; - Assert.IsTrue (nr.TryGetFlags (out flags), "#2"); - flags &= ~NetworkReachabilityFlags.TransientConnection; // Remove the TransientConnection flag if it's set - Assert.That (flags, Is.EqualTo (NetworkReachabilityFlags.Reachable), "#2 Reachable"); + Assert.That (nr.TryGetFlags (out flags), Is.True, "#2"); + // Different OS versions report different flags, so just + // check that Reachable is set and no unexpected flags appear. + CheckRemoteFlags (flags, "2"); } using (var nr = new NetworkReachability (IPAddress.Loopback, null)) { NetworkReachabilityFlags flags; - Assert.IsTrue (nr.TryGetFlags (out flags), "#3"); + Assert.That (nr.TryGetFlags (out flags), Is.True, "#3"); CheckLoopbackFlags (flags, "3", false); } } @@ -111,7 +130,18 @@ void CheckLoopbackFlags (NetworkReachabilityFlags flags, string number, bool has // figure out which OS versions have which flags set turned out to // be a never-ending game of whack-a-mole, so just don't assert // that any specific flags are set. - Assert.AreEqual (noFlags, otherFlags, $"#{number} No other flags: {flags.ToString ()}"); + Assert.That (otherFlags, Is.EqualTo (noFlags), $"#{number} No other flags: {flags.ToString ()}"); + } + + void CheckRemoteFlags (NetworkReachabilityFlags flags, string number) + { + var noFlags = (NetworkReachabilityFlags) 0; + var otherFlags = (flags & ~(NetworkReachabilityFlags.Reachable | NetworkReachabilityFlags.TransientConnection | NetworkReachabilityFlags.ConnectionRequired)); + + // Different versions of OSes report different flags, so just + // verify Reachable is set and no unexpected flags appear. + Assert.That (flags & NetworkReachabilityFlags.Reachable, Is.Not.EqualTo (noFlags), $"#{number} Reachable: {flags.ToString ()}"); + Assert.That (otherFlags, Is.EqualTo (noFlags), $"#{number} No other flags: {flags.ToString ()}"); } [Test] @@ -141,8 +171,8 @@ public void Schedule () { var ip = new IPAddress (0); using var defaultRouteReachability = new NetworkReachability (ip); - Assert.IsTrue (defaultRouteReachability.Schedule (CFRunLoop.Main, CFRunLoop.ModeDefault), "Schedule"); - Assert.IsTrue (defaultRouteReachability.Unschedule (CFRunLoop.Main, CFRunLoop.ModeDefault), "Unschedule"); + Assert.That (defaultRouteReachability.Schedule (CFRunLoop.Main, CFRunLoop.ModeDefault), Is.True, "Schedule"); + Assert.That (defaultRouteReachability.Unschedule (CFRunLoop.Main, CFRunLoop.ModeDefault), Is.True, "Unschedule"); } [Test] @@ -154,16 +184,16 @@ public void SetNotification () // Test setting a notification var statusCode = reachability.SetNotification ((flags) => { }); - Assert.AreEqual (StatusCode.OK, statusCode, "SetNotification should succeed"); + Assert.That (statusCode, Is.EqualTo (StatusCode.OK), "SetNotification should succeed"); // Test clearing the notification (this should free the GCHandle) statusCode = reachability.SetNotification (null); - Assert.AreEqual (StatusCode.OK, statusCode, "SetNotification(null) should succeed"); + Assert.That (statusCode, Is.EqualTo (StatusCode.OK), "SetNotification(null) should succeed"); // Test setting notification again after clearing statusCode = reachability.SetNotification ((flags) => { }); - Assert.AreEqual (StatusCode.OK, statusCode, "SetNotification should succeed again"); + Assert.That (statusCode, Is.EqualTo (StatusCode.OK), "SetNotification should succeed again"); // Test that disposing also works (should free the GCHandle in Dispose) } @@ -208,7 +238,7 @@ public void SetNotification_GCHandleFreed () } } - Assert.IsTrue (collectedCount > 0, $"Expected at least one NetworkReachability instance to be collected, but {collectedCount} were collected"); + Assert.That (collectedCount > 0, Is.True, $"Expected at least one NetworkReachability instance to be collected, but {collectedCount} were collected"); } [Test] @@ -251,7 +281,7 @@ public void SetNotification_GCHandleFreedWithNull () } } - Assert.IsTrue (collectedCount > 0, $"Expected at least one NetworkReachability instance to be collected, but {collectedCount} were collected"); + Assert.That (collectedCount > 0, Is.True, $"Expected at least one NetworkReachability instance to be collected, but {collectedCount} were collected"); } } } diff --git a/tests/monotouch-test/SystemConfiguration/StatusCodeErrorTest.cs b/tests/monotouch-test/SystemConfiguration/StatusCodeErrorTest.cs index 6bc19154a5ce..d5ebfceed445 100644 --- a/tests/monotouch-test/SystemConfiguration/StatusCodeErrorTest.cs +++ b/tests/monotouch-test/SystemConfiguration/StatusCodeErrorTest.cs @@ -20,15 +20,15 @@ public void InvalidStatusCode () { var s = StatusCodeError.GetErrorDescription ((StatusCode) 1); // "Operation not permitted" (might be localized so we just check non-null) - Assert.NotNull (s, "1"); + Assert.That (s, Is.Not.Null, "1"); s = StatusCodeError.GetErrorDescription ((StatusCode) Int32.MinValue); // in previous version of xcode, if the error was not known you would get a null ptr, in Xcode 13 and later you // get a message stating that the error is not knwon. if (TestRuntime.CheckXcodeVersion (13, 0, 0)) { - Assert.NotNull (s, "MinValue null"); - Assert.True (s.StartsWith ("Unknown error:"), "MinValue value"); + Assert.That (s, Is.Not.Null, "MinValue null"); + Assert.That (s.StartsWith ("Unknown error:"), Is.True, "MinValue value"); } else { - Assert.Null (s, "MinValue"); + Assert.That (s, Is.Null, "MinValue"); } } } diff --git a/tests/monotouch-test/TestLoader.cs b/tests/monotouch-test/TestLoader.cs index 2505e47dd0c6..595bfb897cb0 100644 --- a/tests/monotouch-test/TestLoader.cs +++ b/tests/monotouch-test/TestLoader.cs @@ -16,6 +16,6 @@ static partial void AddTestAssembliesImpl (HashSet assemblies) public class LoaderTest { public void TestAssemblyCount () { - Assert.AreEqual (3, TestLoader.GetTestAssemblies ().Count (), "Test assembly count"); + Assert.That (TestLoader.GetTestAssemblies ().Count (), Is.EqualTo (3), "Test assembly count"); } } diff --git a/tests/monotouch-test/UIKit/AccessibilityTest.cs b/tests/monotouch-test/UIKit/AccessibilityTest.cs index 094b6a418318..e28d443ee6bb 100644 --- a/tests/monotouch-test/UIKit/AccessibilityTest.cs +++ b/tests/monotouch-test/UIKit/AccessibilityTest.cs @@ -26,7 +26,7 @@ public void RequestGuidedAccessSession () // should not affect execution since it needs to be a "supervised" device (and allowed in MDM) UIAccessibility.RequestGuidedAccessSession (true, delegate (bool didSuccess) { - Assert.False (didSuccess, "devices are not supervised by default"); + Assert.That (didSuccess, Is.False, "devices are not supervised by default"); }); UIAccessibility.RequestGuidedAccessSession (false, null); } @@ -35,14 +35,14 @@ public void RequestGuidedAccessSession () public void ButtonShapesEnabled () { TestRuntime.AssertXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch); - Assert.False (UIAccessibility.ButtonShapesEnabled); + Assert.That (UIAccessibility.ButtonShapesEnabled, Is.False); } [Test] public void PrefersCrossFadeTransitions () { TestRuntime.AssertXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch); - Assert.False (UIAccessibility.PrefersCrossFadeTransitions); + Assert.That (UIAccessibility.PrefersCrossFadeTransitions, Is.False); } } } diff --git a/tests/monotouch-test/UIKit/ActionSheetTest.cs b/tests/monotouch-test/UIKit/ActionSheetTest.cs index 75f3f86cea96..85c00bb3a333 100644 --- a/tests/monotouch-test/UIKit/ActionSheetTest.cs +++ b/tests/monotouch-test/UIKit/ActionSheetTest.cs @@ -18,18 +18,18 @@ void CheckDefault (UIActionSheet a) { Assert.That (a.ButtonCount, Is.EqualTo ((nint) 0), "ButtonCount"); Assert.That (a.CancelButtonIndex, Is.EqualTo ((nint) (-1)), "CancelButtonIndex"); - Assert.Null (a.Delegate, "Delegate"); + Assert.That (a.Delegate, Is.Null, "Delegate"); Assert.That (a.DestructiveButtonIndex, Is.EqualTo ((nint) (-1)), "DestructiveButtonIndex"); Assert.That (a.FirstOtherButtonIndex, Is.EqualTo ((nint) (-1)), "FirstOtherButtonIndex"); var style = TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 8, 0) ? UIActionSheetStyle.Default : UIActionSheetStyle.Automatic; Assert.That (a.Style, Is.EqualTo (style), "Style"); - Assert.Null (a.Title, "Title"); + Assert.That (a.Title, Is.Null, "Title"); - Assert.False (a.Visible, "Visible"); + Assert.That (a.Visible, Is.False, "Visible"); - Assert.Null (a.WeakDelegate, "WeakDelegate"); + Assert.That (a.WeakDelegate, Is.Null, "WeakDelegate"); } [Test] @@ -68,10 +68,10 @@ public void CtorDelegate () using (var del = new MyActionSheetDelegate ()) using (var a = new UIActionSheet ("title", del, null, null, null)) { Assert.That (a.Title, Is.EqualTo ("title"), "Title"); - Assert.NotNull (typeof (UIActionSheet).GetField ("__mt_WeakDelegate_var", BindingFlags.Instance | BindingFlags.NonPublic).GetValue (a), "backing field"); + Assert.That (typeof (UIActionSheet).GetField ("__mt_WeakDelegate_var", BindingFlags.Instance | BindingFlags.NonPublic).GetValue (a), Is.Not.Null, "backing field"); // check properties after the field (so we're not setting it only when calling the properties) - Assert.NotNull (a.Delegate, "Delegate"); - Assert.NotNull (a.WeakDelegate, "WeakDelegate"); + Assert.That (a.Delegate, Is.Not.Null, "Delegate"); + Assert.That (a.WeakDelegate, Is.Not.Null, "WeakDelegate"); } } } diff --git a/tests/monotouch-test/UIKit/AlertViewTest.cs b/tests/monotouch-test/UIKit/AlertViewTest.cs index 9ff928951f86..e387ca22b1a9 100644 --- a/tests/monotouch-test/UIKit/AlertViewTest.cs +++ b/tests/monotouch-test/UIKit/AlertViewTest.cs @@ -57,10 +57,10 @@ public void CtorDelegate () using (var a = new UIAlertView ("title", "message", del, null, null)) { Assert.That (a.Title, Is.EqualTo ("title"), "Title"); Assert.That (a.Message, Is.EqualTo ("message"), "Message"); - Assert.NotNull (typeof (UIAlertView).GetField ("__mt_WeakDelegate_var", BindingFlags.Instance | BindingFlags.NonPublic).GetValue (a), "backing field"); + Assert.That (typeof (UIAlertView).GetField ("__mt_WeakDelegate_var", BindingFlags.Instance | BindingFlags.NonPublic).GetValue (a), Is.Not.Null, "backing field"); // check properties after the field (so we're not setting it only when calling the properties) - Assert.NotNull (a.Delegate, "Delegate"); - Assert.NotNull (a.WeakDelegate, "WeakDelegate"); + Assert.That (a.Delegate, Is.Not.Null, "Delegate"); + Assert.That (a.WeakDelegate, Is.Not.Null, "WeakDelegate"); } } diff --git a/tests/monotouch-test/UIKit/AppearanceTest.cs b/tests/monotouch-test/UIKit/AppearanceTest.cs index f5c17568aa8c..63e09dce8d6d 100644 --- a/tests/monotouch-test/UIKit/AppearanceTest.cs +++ b/tests/monotouch-test/UIKit/AppearanceTest.cs @@ -25,8 +25,8 @@ public void Equality () using (var a = UITableView.Appearance) using (var b = UITableView.Appearance) using (var c = UILabel.Appearance) { - Assert.True (a == b, "1"); - Assert.False (a == c, "2"); + Assert.That (a == b, Is.True, "1"); + Assert.That (a == c, Is.False, "2"); } } @@ -36,8 +36,8 @@ public void Inequality () using (var a = UITableView.Appearance) using (var b = UITableView.Appearance) using (var c = UILabel.Appearance) { - Assert.False (a != b, "1"); - Assert.True (a != c, "2"); + Assert.That (a != b, Is.False, "1"); + Assert.That (a != c, Is.True, "2"); } } @@ -51,22 +51,22 @@ public void Appearance () // Appearance // it can be set - Assert.IsNull (UILabel.Appearance.TextColor, "null 1"); + Assert.That (UILabel.Appearance.TextColor, Is.Null, "null 1"); UILabel.Appearance.TextColor = UIColor.Red; UILabel.Appearance.TextColor.GetRGBA (out r, out g, out b, out a); - Assert.AreEqual ((nfloat) 1, a, "a1"); - Assert.AreEqual ((nfloat) 1, r, "r1"); - Assert.AreEqual ((nfloat) 0, g, "g1"); - Assert.AreEqual ((nfloat) 0, b, "b1"); + Assert.That (a, Is.EqualTo ((nfloat) 1), "a1"); + Assert.That (r, Is.EqualTo ((nfloat) 1), "r1"); + Assert.That (g, Is.EqualTo ((nfloat) 0), "g1"); + Assert.That (b, Is.EqualTo ((nfloat) 0), "b1"); // check that other appearance instances didn't change - Assert.IsNull (UILabel.GetAppearance (traits).TextColor, "other null 2"); - Assert.IsNull (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, "other null 3"); - Assert.IsNull (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, "other null 4"); + Assert.That (UILabel.GetAppearance (traits).TextColor, Is.Null, "other null 2"); + Assert.That (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, Is.Null, "other null 3"); + Assert.That (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, Is.Null, "other null 4"); // it can be cleared UILabel.Appearance.TextColor = null; - Assert.IsNull (UILabel.Appearance.TextColor, "null 2"); + Assert.That (UILabel.Appearance.TextColor, Is.Null, "null 2"); } } @@ -79,22 +79,22 @@ public void AppearanceWhenContainedIn () nfloat r, g, b, a; // it can be set - Assert.IsNull (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, "null 1"); + Assert.That (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, Is.Null, "null 1"); UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor = UIColor.Blue; UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor.GetRGBA (out r, out g, out b, out a); - Assert.AreEqual ((nfloat) 1, a, "a1"); - Assert.AreEqual ((nfloat) 0, r, "r1"); - Assert.AreEqual ((nfloat) 0, g, "g1"); - Assert.AreEqual ((nfloat) 1, b, "b1"); + Assert.That (a, Is.EqualTo ((nfloat) 1), "a1"); + Assert.That (r, Is.EqualTo ((nfloat) 0), "r1"); + Assert.That (g, Is.EqualTo ((nfloat) 0), "g1"); + Assert.That (b, Is.EqualTo ((nfloat) 1), "b1"); // check that other appearance instances didn't change (bug 26353) - Assert.IsNull (UILabel.Appearance.TextColor, "other null 1"); - Assert.IsNull (UILabel.GetAppearance (traits).TextColor, "other null 2"); - Assert.IsNull (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, "other null 3"); + Assert.That (UILabel.Appearance.TextColor, Is.Null, "other null 1"); + Assert.That (UILabel.GetAppearance (traits).TextColor, Is.Null, "other null 2"); + Assert.That (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, Is.Null, "other null 3"); // it can be cleared UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor = null; - Assert.IsNull (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, "null 2"); + Assert.That (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, Is.Null, "null 2"); } } @@ -108,44 +108,44 @@ public void AppearanceWhenContainedIn_UITraitCollection () nfloat r, g, b, a; // it can be set - Assert.IsNull (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, "null 1"); + Assert.That (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, Is.Null, "null 1"); UILabel.GetAppearance (traits, typeof (UITextField)).TextColor = UIColor.Blue; UILabel.GetAppearance (traits, typeof (UITextField)).TextColor.GetRGBA (out r, out g, out b, out a); - Assert.AreEqual ((nfloat) 1, a, "a1"); - Assert.AreEqual ((nfloat) 0, r, "r1"); - Assert.AreEqual ((nfloat) 0, g, "g1"); - Assert.AreEqual ((nfloat) 1, b, "b1"); + Assert.That (a, Is.EqualTo ((nfloat) 1), "a1"); + Assert.That (r, Is.EqualTo ((nfloat) 0), "r1"); + Assert.That (g, Is.EqualTo ((nfloat) 0), "g1"); + Assert.That (b, Is.EqualTo ((nfloat) 1), "b1"); // check that other appearance instances didn't change - Assert.IsNull (UILabel.Appearance.TextColor, "other null 1"); - Assert.IsNull (UILabel.GetAppearance (traits).TextColor, "other null 2"); - Assert.IsNull (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, "other null 4"); + Assert.That (UILabel.Appearance.TextColor, Is.Null, "other null 1"); + Assert.That (UILabel.GetAppearance (traits).TextColor, Is.Null, "other null 2"); + Assert.That (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, Is.Null, "other null 4"); // it can be cleared UILabel.GetAppearance (traits, typeof (UITextField)).TextColor = null; - Assert.IsNull (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, "null 2"); + Assert.That (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, Is.Null, "null 2"); } using (var traits = new UITraitCollection ()) { nfloat r, g, b, a; // it can be set - Assert.IsNull (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, "g null 1"); + Assert.That (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, Is.Null, "g null 1"); UILabel.GetAppearance (traits, typeof (UITextField)).TextColor = UIColor.Blue; UILabel.GetAppearance (traits, typeof (UITextField)).TextColor.GetRGBA (out r, out g, out b, out a); - Assert.AreEqual ((nfloat) 1, a, "g a1"); - Assert.AreEqual ((nfloat) 0, r, "g r1"); - Assert.AreEqual ((nfloat) 0, g, "g g1"); - Assert.AreEqual ((nfloat) 1, b, "g b1"); + Assert.That (a, Is.EqualTo ((nfloat) 1), "g a1"); + Assert.That (r, Is.EqualTo ((nfloat) 0), "g r1"); + Assert.That (g, Is.EqualTo ((nfloat) 0), "g g1"); + Assert.That (b, Is.EqualTo ((nfloat) 1), "g b1"); // check that other appearance instances didn't change - Assert.IsNull (UILabel.Appearance.TextColor, "g other null 1"); - Assert.IsNull (UILabel.GetAppearance (traits).TextColor, "g other null 2"); - Assert.IsNull (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, "g other null 4"); + Assert.That (UILabel.Appearance.TextColor, Is.Null, "g other null 1"); + Assert.That (UILabel.GetAppearance (traits).TextColor, Is.Null, "g other null 2"); + Assert.That (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, Is.Null, "g other null 4"); // it can be cleared UILabel.GetAppearance (traits, typeof (UITextField)).TextColor = null; - Assert.IsNull (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, "g null 2"); + Assert.That (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, Is.Null, "g null 2"); } } @@ -158,22 +158,22 @@ public void Appearance_UITraitCollection () nfloat r, g, b, a; // it can be set - Assert.IsNull (UILabel.GetAppearance (traits).TextColor, "null 1"); + Assert.That (UILabel.GetAppearance (traits).TextColor, Is.Null, "null 1"); UILabel.GetAppearance (traits).TextColor = UIColor.Blue; UILabel.GetAppearance (traits).TextColor.GetRGBA (out r, out g, out b, out a); - Assert.AreEqual ((nfloat) 1, a, "a1"); - Assert.AreEqual ((nfloat) 0, r, "r1"); - Assert.AreEqual ((nfloat) 0, g, "g1"); - Assert.AreEqual ((nfloat) 1, b, "b1"); + Assert.That (a, Is.EqualTo ((nfloat) 1), "a1"); + Assert.That (r, Is.EqualTo ((nfloat) 0), "r1"); + Assert.That (g, Is.EqualTo ((nfloat) 0), "g1"); + Assert.That (b, Is.EqualTo ((nfloat) 1), "b1"); // check that other appearance instances didn't change - Assert.IsNull (UILabel.Appearance.TextColor, "other null 1"); - Assert.IsNull (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, "other null 3"); - Assert.IsNull (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, "other null 4"); + Assert.That (UILabel.Appearance.TextColor, Is.Null, "other null 1"); + Assert.That (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, Is.Null, "other null 3"); + Assert.That (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, Is.Null, "other null 4"); // it can be cleared UILabel.GetAppearance (traits).TextColor = null; - Assert.IsNull (UILabel.GetAppearance (traits).TextColor, "null 2"); + Assert.That (UILabel.GetAppearance (traits).TextColor, Is.Null, "null 2"); } // generic version @@ -181,22 +181,22 @@ public void Appearance_UITraitCollection () nfloat r, g, b, a; // it can be set - Assert.IsNull (UILabel.GetAppearance (traits).TextColor, "g null 1"); + Assert.That (UILabel.GetAppearance (traits).TextColor, Is.Null, "g null 1"); UILabel.GetAppearance (traits).TextColor = UIColor.Blue; UILabel.GetAppearance (traits).TextColor.GetRGBA (out r, out g, out b, out a); - Assert.AreEqual ((nfloat) 1, a, "g a1"); - Assert.AreEqual ((nfloat) 0, r, "g r1"); - Assert.AreEqual ((nfloat) 0, g, "g g1"); - Assert.AreEqual ((nfloat) 1, b, "g b1"); + Assert.That (a, Is.EqualTo ((nfloat) 1), "g a1"); + Assert.That (r, Is.EqualTo ((nfloat) 0), "g r1"); + Assert.That (g, Is.EqualTo ((nfloat) 0), "g g1"); + Assert.That (b, Is.EqualTo ((nfloat) 1), "g b1"); // check that other appearance instances didn't change - Assert.IsNull (UILabel.Appearance.TextColor, "g other null 1"); - Assert.IsNull (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, "g other null 3"); - Assert.IsNull (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, "g other null 4"); + Assert.That (UILabel.Appearance.TextColor, Is.Null, "g other null 1"); + Assert.That (UILabel.GetAppearance (traits, typeof (UITextField)).TextColor, Is.Null, "g other null 3"); + Assert.That (UILabel.AppearanceWhenContainedIn (typeof (UITextField)).TextColor, Is.Null, "g other null 4"); // it can be cleared UILabel.GetAppearance (traits).TextColor = null; - Assert.IsNull (UILabel.GetAppearance (traits).TextColor, "g null 2"); + Assert.That (UILabel.GetAppearance (traits).TextColor, Is.Null, "g null 2"); } } diff --git a/tests/monotouch-test/UIKit/ApplicationTest.cs b/tests/monotouch-test/UIKit/ApplicationTest.cs index 33a114d4eebc..087d572e69f0 100644 --- a/tests/monotouch-test/UIKit/ApplicationTest.cs +++ b/tests/monotouch-test/UIKit/ApplicationTest.cs @@ -22,7 +22,7 @@ public void BackgroundTaskInvalid () [Test] public void SetKeepAliveTimeout_Null () { - Assert.False (UIApplication.SharedApplication.SetKeepAliveTimeout (600, null), "SetKeepAliveTimeout"); + Assert.That (UIApplication.SharedApplication.SetKeepAliveTimeout (600, null), Is.False, "SetKeepAliveTimeout"); } #endif diff --git a/tests/monotouch-test/UIKit/BarButtonItemTest.cs b/tests/monotouch-test/UIKit/BarButtonItemTest.cs index 56e0d21e0ca0..289277d5057d 100644 --- a/tests/monotouch-test/UIKit/BarButtonItemTest.cs +++ b/tests/monotouch-test/UIKit/BarButtonItemTest.cs @@ -26,13 +26,13 @@ public void InitWithImage () { using (var img = new UIImage ()) using (var btn = new UIBarButtonItem (img, UIBarButtonItemStyle.Bordered, null, null)) { - Assert.Null (btn.Target, "Target"); - Assert.AreSame (img, btn.Image, "Image"); + Assert.That (btn.Target, Is.Null, "Target"); + Assert.That (btn.Image, Is.SameAs (img), "Image"); btn.Image = null; // nullable } using (var btn = new UIBarButtonItem ((UIImage) null, UIBarButtonItemStyle.Bordered, null, null)) { - Assert.Null (btn.Image, "Image-null"); + Assert.That (btn.Image, Is.Null, "Image-null"); } } @@ -41,13 +41,13 @@ public void InitWithImage2 () { using (var img = new UIImage ()) using (var btn = new UIBarButtonItem (img, img, UIBarButtonItemStyle.Bordered, null, null)) { - Assert.Null (btn.Target, "Target"); - Assert.AreSame (img, btn.Image, "Image"); + Assert.That (btn.Target, Is.Null, "Target"); + Assert.That (btn.Image, Is.SameAs (img), "Image"); btn.Image = null; // nullable } using (var btn = new UIBarButtonItem (null, null, UIBarButtonItemStyle.Bordered, null, null)) { - Assert.Null (btn.Image, "Image-null"); + Assert.That (btn.Image, Is.Null, "Image-null"); } } @@ -55,13 +55,13 @@ public void InitWithImage2 () public void InitWithText () { using (var btn = new UIBarButtonItem ("title", UIBarButtonItemStyle.Bordered, null, null)) { - Assert.Null (btn.Target, "Target"); + Assert.That (btn.Target, Is.Null, "Target"); Assert.That (btn.Title, Is.EqualTo ("title"), "Title"); btn.Title = null; // nullable } using (var btn = new UIBarButtonItem ((string) null, UIBarButtonItemStyle.Bordered, null, null)) { - Assert.Null (btn.Title, "Title-null"); + Assert.That (btn.Title, Is.Null, "Title-null"); } } @@ -69,7 +69,7 @@ public void InitWithText () public void CustomView_Null () { using (var btn = new UIBarButtonItem ("title", UIBarButtonItemStyle.Bordered, null, null)) { - Assert.Null (btn.CustomView, "default"); + Assert.That (btn.CustomView, Is.Null, "default"); btn.CustomView = null; // nullable } } @@ -78,11 +78,11 @@ public void CustomView_Null () public void TintColor_Null () { using (var btn = new UIBarButtonItem ("title", UIBarButtonItemStyle.Bordered, null, null)) { - Assert.Null (btn.TintColor, "default"); + Assert.That (btn.TintColor, Is.Null, "default"); btn.TintColor = UIColor.Blue; Assert.That (btn.TintColor == UIColor.Blue, "blue"); btn.TintColor = null; - Assert.Null (btn.TintColor, "null"); + Assert.That (btn.TintColor, Is.Null, "null"); } } @@ -100,10 +100,10 @@ public void Action_Set () public void BackgroundImage () { using (UIBarButtonItem btn = new UIBarButtonItem ()) { - Assert.Null (btn.GetBackgroundImage (UIControlState.Highlighted, UIBarMetrics.Default), "Get"); + Assert.That (btn.GetBackgroundImage (UIControlState.Highlighted, UIBarMetrics.Default), Is.Null, "Get"); btn.SetBackgroundImage (null, UIControlState.Highlighted, UIBarMetrics.Default); - Assert.Null (btn.GetBackgroundImage (UIControlState.Highlighted, UIBarButtonItemStyle.Plain, UIBarMetrics.Default), "Get2"); + Assert.That (btn.GetBackgroundImage (UIControlState.Highlighted, UIBarButtonItemStyle.Plain, UIBarMetrics.Default), Is.Null, "Get2"); btn.SetBackgroundImage (null, UIControlState.Highlighted, UIBarButtonItemStyle.Plain, UIBarMetrics.Default); } } @@ -113,7 +113,7 @@ public void BackButtonBackgroundImage () { using (UIBarButtonItem btn = new UIBarButtonItem ()) { #if !__TVOS__ - Assert.Null (btn.GetBackButtonBackgroundImage (UIControlState.Highlighted, UIBarMetrics.Default), "Get"); + Assert.That (btn.GetBackButtonBackgroundImage (UIControlState.Highlighted, UIBarMetrics.Default), Is.Null, "Get"); btn.SetBackButtonBackgroundImage (null, UIControlState.Highlighted, UIBarMetrics.Default); #endif } diff --git a/tests/monotouch-test/UIKit/ButtonTest.cs b/tests/monotouch-test/UIKit/ButtonTest.cs index 2f805b46e1b1..8144b0109879 100644 --- a/tests/monotouch-test/UIKit/ButtonTest.cs +++ b/tests/monotouch-test/UIKit/ButtonTest.cs @@ -27,7 +27,7 @@ public void NullAllowed () { using (var b = new UIButton ()) { b.SetTitle (null, UIControlState.Normal); - Assert.IsNull (b.Title (UIControlState.Normal), "title"); + Assert.That (b.Title (UIControlState.Normal), Is.Null, "title"); b.SetTitleColor (null, UIControlState.Normal); var hasTitleColor = true; @@ -38,10 +38,10 @@ public void NullAllowed () if (hasTitleColor) Assert.That (b.TitleColor (UIControlState.Normal), Is.EqualTo (UIColor.White), "titlecolor"); else - Assert.IsNull (b.TitleColor (UIControlState.Normal), "titlecolor"); + Assert.That (b.TitleColor (UIControlState.Normal), Is.Null, "titlecolor"); b.SetTitleShadowColor (null, UIControlState.Normal); - Assert.IsNull (b.TitleShadowColor (UIControlState.Normal), "titleshadowcolor"); + Assert.That (b.TitleShadowColor (UIControlState.Normal), Is.Null, "titleshadowcolor"); } } diff --git a/tests/monotouch-test/UIKit/CellAccessoryTest.cs b/tests/monotouch-test/UIKit/CellAccessoryTest.cs index baa7d7486776..fdcee5cc77ed 100644 --- a/tests/monotouch-test/UIKit/CellAccessoryTest.cs +++ b/tests/monotouch-test/UIKit/CellAccessoryTest.cs @@ -13,11 +13,11 @@ public void GetPositionBeforeAccessory () { TestRuntime.AssertXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch); var cap = UICellAccessory.GetPositionBeforeAccessory (new Class ("UIButton")); - Assert.NotNull (cap, "Class/cap"); + Assert.That (cap, Is.Not.Null, "Class/cap"); Assert.That (cap (new UICellAccessory [0]), Is.EqualTo ((nuint) 0), "Class/Invoke"); cap = UICellAccessory.GetPositionBeforeAccessory (typeof (UICellAccessory)); - Assert.NotNull (cap, "Type/cap"); + Assert.That (cap, Is.Not.Null, "Type/cap"); Assert.That (cap (new UICellAccessory [0]), Is.EqualTo ((nuint) 0), "Type/Invoke"); } @@ -26,11 +26,11 @@ public void GetPositionAfterAccessory () { TestRuntime.AssertXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch); var cap = UICellAccessory.GetPositionAfterAccessory (new Class ("UIButton")); - Assert.NotNull (cap, "Class/cap"); + Assert.That (cap, Is.Not.Null, "Class/cap"); Assert.That (cap (new UICellAccessory [0]), Is.EqualTo ((nuint) 0), "Class/Invoke"); cap = UICellAccessory.GetPositionAfterAccessory (typeof (UICellAccessory)); - Assert.NotNull (cap, "Type/cap"); + Assert.That (cap, Is.Not.Null, "Type/cap"); Assert.That (cap (new UICellAccessory [0]), Is.EqualTo ((nuint) 0), "Type/Invoke"); } } diff --git a/tests/monotouch-test/UIKit/CollectionViewControllerTest.cs b/tests/monotouch-test/UIKit/CollectionViewControllerTest.cs index b95d30e986db..5e4a5f6bae2d 100644 --- a/tests/monotouch-test/UIKit/CollectionViewControllerTest.cs +++ b/tests/monotouch-test/UIKit/CollectionViewControllerTest.cs @@ -19,7 +19,7 @@ public void Ctor () using (var c = new UICollectionViewController (l)) { // that's because Apple did not expose the init* argument as a property until 7.0 if (TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false)) - Assert.AreSame (l, c.Layout, "Layout"); + Assert.That (c.Layout, Is.SameAs (l), "Layout"); } } } diff --git a/tests/monotouch-test/UIKit/CollectionViewTransitionLayoutTest.cs b/tests/monotouch-test/UIKit/CollectionViewTransitionLayoutTest.cs index 6cf14f641201..6361e568dfe5 100644 --- a/tests/monotouch-test/UIKit/CollectionViewTransitionLayoutTest.cs +++ b/tests/monotouch-test/UIKit/CollectionViewTransitionLayoutTest.cs @@ -20,8 +20,8 @@ public void Ctor () using (var l2 = new UICollectionViewLayout ()) using (var tl = new UICollectionViewTransitionLayout (l1, l2)) { // interesting ctor for the linker (two [PostGet]) - Assert.AreSame (tl.CurrentLayout, l1, "CurrentLayout"); - Assert.AreSame (tl.NextLayout, l2, "NextLayout"); + Assert.That (l1, Is.SameAs (tl.CurrentLayout), "CurrentLayout"); + Assert.That (l2, Is.SameAs (tl.NextLayout), "NextLayout"); } } } diff --git a/tests/monotouch-test/UIKit/ColorTest.cs b/tests/monotouch-test/UIKit/ColorTest.cs index 1228268a795e..0a974f0206aa 100644 --- a/tests/monotouch-test/UIKit/ColorTest.cs +++ b/tests/monotouch-test/UIKit/ColorTest.cs @@ -296,7 +296,7 @@ public void UIConfigurationColorTransformerTest () var redColor = UIColor.Red; var transformer = UIConfigurationColorTransformer.Grayscale; var grayColor = transformer (redColor); - Assert.NotNull (grayColor, "Not null"); + Assert.That (grayColor, Is.Not.Null, "Not null"); } // nfloat red, nfloat green, nfloat blue, nfloat alpha, nfloat linearExposure @@ -323,13 +323,13 @@ public void ColorExposureCtorTest (double red, double green, double blue, double var c = UIColor.FromRgbaLinearExposure (nr, ng, nb, na, ne); var r = new UIColor (nr, ng, nb, na, ne, isLinearExposure); Assert.That (r.ToString (), Is.EqualTo (c.ToString ()), c.ToString ()); - Assert.AreEqual (c.LinearExposure, r.LinearExposure, $"LinearExposure: r:{nr}, g:{ng}, b:{nb}, a:{na}, e:{ne}"); + Assert.That (r.LinearExposure, Is.EqualTo (c.LinearExposure), $"LinearExposure: r:{nr}, g:{ng}, b:{nb}, a:{na}, e:{ne}"); } else { // Exponential exposure var c = UIColor.FromRgbaExposure (nr, ng, nb, na, ne); var r = new UIColor (nr, ng, nb, na, ne, isLinearExposure); Assert.That (r.ToString (), Is.EqualTo (c.ToString ()), c.ToString ()); - Assert.AreEqual (c.LinearExposure, r.LinearExposure, $"ExponentialExposure: r:{nr}, g:{ng}, b:{nb}, a:{na}, e:{ne}"); + Assert.That (r.LinearExposure, Is.EqualTo (c.LinearExposure), $"ExponentialExposure: r:{nr}, g:{ng}, b:{nb}, a:{na}, e:{ne}"); } } } diff --git a/tests/monotouch-test/UIKit/ControlTest.cs b/tests/monotouch-test/UIKit/ControlTest.cs index ad6679f38f82..93b499c62ec7 100644 --- a/tests/monotouch-test/UIKit/ControlTest.cs +++ b/tests/monotouch-test/UIKit/ControlTest.cs @@ -56,7 +56,7 @@ public void AddTargetTable () any_collected = true; handles [i].Free (); } - Assert.IsTrue (any_collected, "Nothing collected"); + Assert.That (any_collected, Is.True, "Nothing collected"); } [Test] @@ -64,7 +64,7 @@ public void AddTargetMakeDirty () { using (var ctrl = new UIControl ()) { ctrl.AddTarget ((a, b) => { }, UIControlEvent.EditingDidBegin); - Assert.IsTrue ((TestRuntime.GetFlags (ctrl) & 0x8) /* RegisteredToggleRef */ == 0x8, "RegisteredToggleRef"); + Assert.That (TestRuntime.GetFlags (ctrl) & 0x8, Is.EqualTo (0x8), "RegisteredToggleRef"); } } } diff --git a/tests/monotouch-test/UIKit/DatePickerTest.cs b/tests/monotouch-test/UIKit/DatePickerTest.cs index e5d1bece91d0..98f5e3679247 100644 --- a/tests/monotouch-test/UIKit/DatePickerTest.cs +++ b/tests/monotouch-test/UIKit/DatePickerTest.cs @@ -16,12 +16,12 @@ public class DatePickerTest { public void Defaults () { using (UIDatePicker dp = new UIDatePicker ()) { - Assert.Null (dp.MinimumDate, "MinimumDate"); - Assert.Null (dp.MaximumDate, "MaximumDate"); - Assert.Null (dp.TimeZone, "TimeZone"); + Assert.That (dp.MinimumDate, Is.Null, "MinimumDate"); + Assert.That (dp.MaximumDate, Is.Null, "MaximumDate"); + Assert.That (dp.TimeZone, Is.Null, "TimeZone"); - Assert.NotNull (dp.Calendar, "Calendar"); - Assert.NotNull (dp.Date, "Date"); + Assert.That (dp.Calendar, Is.Not.Null, "Calendar"); + Assert.That (dp.Date, Is.Not.Null, "Date"); } } @@ -29,7 +29,7 @@ public void Defaults () public void Locale () { using (UIDatePicker dp = new UIDatePicker ()) { - Assert.NotNull (dp.Locale, "Locale"); + Assert.That (dp.Locale, Is.Not.Null, "Locale"); } } [Test] diff --git a/tests/monotouch-test/UIKit/DeviceTest.cs b/tests/monotouch-test/UIKit/DeviceTest.cs index 44f5236d2000..2f952966685a 100644 --- a/tests/monotouch-test/UIKit/DeviceTest.cs +++ b/tests/monotouch-test/UIKit/DeviceTest.cs @@ -22,7 +22,7 @@ public class DeviceTest { public void Battery () { UIDevice device = UIDevice.CurrentDevice; - Assert.False (device.BatteryMonitoringEnabled, "false"); + Assert.That (device.BatteryMonitoringEnabled, Is.False, "false"); Assert.That (device.BatteryState, Is.EqualTo (UIDeviceBatteryState.Unknown), "false/Unknown"); Assert.That (device.BatteryLevel, Is.EqualTo (-1), "false/-1"); diff --git a/tests/monotouch-test/UIKit/DictationPhrase.cs b/tests/monotouch-test/UIKit/DictationPhrase.cs index 99f79761e292..a3aa89deeaf4 100644 --- a/tests/monotouch-test/UIKit/DictationPhrase.cs +++ b/tests/monotouch-test/UIKit/DictationPhrase.cs @@ -15,8 +15,8 @@ public class DictationPhraseTest { public void Defaults () { using (UIDictationPhrase dp = new UIDictationPhrase ()) { - Assert.Null (dp.AlternativeInterpretations, "AlternativeInterpretations"); - Assert.Null (dp.Text, "Text"); + Assert.That (dp.AlternativeInterpretations, Is.Null, "AlternativeInterpretations"); + Assert.That (dp.Text, Is.Null, "Text"); } } } diff --git a/tests/monotouch-test/UIKit/DirectionalEdgeInsetsTest.cs b/tests/monotouch-test/UIKit/DirectionalEdgeInsetsTest.cs index 1b963c354544..916ba5ccd6bd 100644 --- a/tests/monotouch-test/UIKit/DirectionalEdgeInsetsTest.cs +++ b/tests/monotouch-test/UIKit/DirectionalEdgeInsetsTest.cs @@ -46,10 +46,10 @@ public void Operators () var i2 = new NSDirectionalEdgeInsets (10, 10, 10, 10); #pragma warning disable CS1718 // warning CS1718: Comparison made to same variable; did you mean to compare something else? - Assert.True (i1 == i1, "i1 == i1"); - Assert.True (i2 == i2, "i1 == i1"); - Assert.True (i1 != i2, "i1 != i2"); - Assert.True (i2 != i1, "i2 != i1"); + Assert.That (i1 == i1, Is.True, "i1 == i1"); + Assert.That (i2 == i2, Is.True, "i1 == i1"); + Assert.That (i1 != i2, Is.True, "i1 != i2"); + Assert.That (i2 != i1, Is.True, "i2 != i1"); #pragma warning restore } } diff --git a/tests/monotouch-test/UIKit/EdgeInsetsTest.cs b/tests/monotouch-test/UIKit/EdgeInsetsTest.cs index 8b0948252c09..09b7a34adb24 100644 --- a/tests/monotouch-test/UIKit/EdgeInsetsTest.cs +++ b/tests/monotouch-test/UIKit/EdgeInsetsTest.cs @@ -51,8 +51,8 @@ public void InsetRect () Assert.That (r.Width, Is.EqualTo ((nfloat) (-57f)), "Width"); Assert.That (r.Height, Is.EqualTo ((nfloat) (-36f)), "Height"); - Assert.False (i.Equals (UIEdgeInsets.Zero), "Equals(UIEdgeInsets)"); - Assert.False (UIEdgeInsets.Zero.Equals ((object) i), "Equals(object)"); + Assert.That (i.Equals (UIEdgeInsets.Zero), Is.False, "Equals(UIEdgeInsets)"); + Assert.That (UIEdgeInsets.Zero.Equals ((object) i), Is.False, "Equals(object)"); } [Test] @@ -62,10 +62,10 @@ public void Operators () var i2 = new UIEdgeInsets (10, 10, 10, 10); #pragma warning disable CS1718 // warning CS1718: Comparison made to same variable; did you mean to compare something else? - Assert.True (i1 == i1, "i1 == i1"); - Assert.True (i2 == i2, "i1 == i1"); - Assert.True (i1 != i2, "i1 != i2"); - Assert.True (i2 != i1, "i2 != i1"); + Assert.That (i1 == i1, Is.True, "i1 == i1"); + Assert.That (i2 == i2, Is.True, "i1 == i1"); + Assert.That (i1 != i2, Is.True, "i1 != i2"); + Assert.That (i2 != i1, Is.True, "i2 != i1"); #pragma warning restore } } diff --git a/tests/monotouch-test/UIKit/FloatRangeTest.cs b/tests/monotouch-test/UIKit/FloatRangeTest.cs index e0296e92ae95..dbe945194923 100644 --- a/tests/monotouch-test/UIKit/FloatRangeTest.cs +++ b/tests/monotouch-test/UIKit/FloatRangeTest.cs @@ -24,12 +24,12 @@ public void ManagedVersusNative () try { var zero = Dlfcn.dlsym (uikit, "UIFloatRangeZero"); var Zero = Marshal.PtrToStructure (zero); - Assert.True (UIFloatRange.Zero.Equals (Zero), "Zero"); + Assert.That (UIFloatRange.Zero.Equals (Zero), Is.True, "Zero"); var infinite = Dlfcn.dlsym (uikit, "UIFloatRangeInfinite"); var Infinite = Marshal.PtrToStructure (infinite); - Assert.True (Infinite.IsInfinite, "IsInfinite"); - Assert.False (UIFloatRange.Infinite.Equals (Infinite), "Infinite"); + Assert.That (Infinite.IsInfinite, Is.True, "IsInfinite"); + Assert.That (UIFloatRange.Infinite.Equals (Infinite), Is.False, "Infinite"); } finally { Dlfcn.dlclose (uikit); } @@ -39,8 +39,8 @@ public void ManagedVersusNative () public void IsInfinite () { TestRuntime.AssertXcodeVersion (7, 0); - Assert.True (UIFloatRange.Infinite.IsInfinite, "Infinite"); - Assert.False (UIFloatRange.Zero.IsInfinite, "Zero"); + Assert.That (UIFloatRange.Infinite.IsInfinite, Is.True, "Infinite"); + Assert.That (UIFloatRange.Zero.IsInfinite, Is.False, "Zero"); } [Ignore ("https://github.com/xamarin/maccore/issues/1885")] @@ -48,15 +48,15 @@ public void IsInfinite () public void Equals () { TestRuntime.AssertXcodeVersion (7, 0); - Assert.True (UIFloatRange.Zero.Equals (UIFloatRange.Zero), "Zero-Zero"); + Assert.That (UIFloatRange.Zero.Equals (UIFloatRange.Zero), Is.True, "Zero-Zero"); var one = new UIFloatRange (1f, 1f); - Assert.False (one.Equals (UIFloatRange.Zero), "one-Zero"); - Assert.False (UIFloatRange.Zero.Equals ((object) one), "Zero-one"); - Assert.True (one.Equals (one), "one-one"); + Assert.That (one.Equals (UIFloatRange.Zero), Is.False, "one-Zero"); + Assert.That (UIFloatRange.Zero.Equals ((object) one), Is.False, "Zero-one"); + Assert.That (one.Equals (one), Is.True, "one-one"); - Assert.False (UIFloatRange.Infinite.Equals (UIFloatRange.Infinite), "Infinite-Infinite"); - Assert.False (UIFloatRange.Infinite.Equals (UIFloatRange.Zero), "Infinite-Zero"); - Assert.False (UIFloatRange.Zero.Equals (UIFloatRange.Infinite), "Zero-Infinite"); + Assert.That (UIFloatRange.Infinite.Equals (UIFloatRange.Infinite), Is.False, "Infinite-Infinite"); + Assert.That (UIFloatRange.Infinite.Equals (UIFloatRange.Zero), Is.False, "Infinite-Zero"); + Assert.That (UIFloatRange.Zero.Equals (UIFloatRange.Infinite), Is.False, "Zero-Infinite"); } } } diff --git a/tests/monotouch-test/UIKit/FontDescriptorTest.cs b/tests/monotouch-test/UIKit/FontDescriptorTest.cs index 925ee6eb1502..1e59a0c338e4 100644 --- a/tests/monotouch-test/UIKit/FontDescriptorTest.cs +++ b/tests/monotouch-test/UIKit/FontDescriptorTest.cs @@ -14,20 +14,20 @@ public class FontDescriptorTest { public void UIFontAttributes_DefaultConstructor () { var attrs = new UIFontAttributes (); - Assert.IsNull (attrs.Family, "Family"); - Assert.IsNull (attrs.Name, "Name"); - Assert.IsNull (attrs.Face, "Face"); - Assert.IsNull (attrs.Size, "Size"); - Assert.IsNull (attrs.VisibleName, "VisibleName"); - Assert.IsNull (attrs.TextStyle, "TextStyle"); - Assert.IsNull (attrs.Matrix, "Matrix"); - Assert.IsNull (attrs.CharacterSet, "CharacterSet"); - Assert.IsNull (attrs.CascadeList, "CascadeList"); - Assert.IsNull (attrs.Traits, "Traits"); - Assert.IsNull (attrs.FixedAdvance, "FixedAdvance"); - Assert.IsNull (attrs.WeakFeatureSettings, "WeakFeatureSettings"); - Assert.IsNotNull (attrs.FeatureSettings, "FeatureSettings"); - Assert.AreEqual (0, attrs.FeatureSettings.Length, "FeatureSettings.Length"); + Assert.That (attrs.Family, Is.Null, "Family"); + Assert.That (attrs.Name, Is.Null, "Name"); + Assert.That (attrs.Face, Is.Null, "Face"); + Assert.That (attrs.Size, Is.Null, "Size"); + Assert.That (attrs.VisibleName, Is.Null, "VisibleName"); + Assert.That (attrs.TextStyle, Is.Null, "TextStyle"); + Assert.That (attrs.Matrix, Is.Null, "Matrix"); + Assert.That (attrs.CharacterSet, Is.Null, "CharacterSet"); + Assert.That (attrs.CascadeList, Is.Null, "CascadeList"); + Assert.That (attrs.Traits, Is.Null, "Traits"); + Assert.That (attrs.FixedAdvance, Is.Null, "FixedAdvance"); + Assert.That (attrs.WeakFeatureSettings, Is.Null, "WeakFeatureSettings"); + Assert.That (attrs.FeatureSettings, Is.Not.Null, "FeatureSettings"); + Assert.That (attrs.FeatureSettings.Length, Is.EqualTo (0), "FeatureSettings.Length"); } [Test] @@ -36,20 +36,20 @@ public void UIFontAttributes_StringProperties () var attrs = new UIFontAttributes (); attrs.Family = "Helvetica"; - Assert.AreEqual ("Helvetica", attrs.Family, "Family set"); + Assert.That (attrs.Family, Is.EqualTo ("Helvetica"), "Family set"); attrs.Name = "Helvetica-Bold"; - Assert.AreEqual ("Helvetica-Bold", attrs.Name, "Name set"); + Assert.That (attrs.Name, Is.EqualTo ("Helvetica-Bold"), "Name set"); attrs.Face = "Bold"; - Assert.AreEqual ("Bold", attrs.Face, "Face set"); + Assert.That (attrs.Face, Is.EqualTo ("Bold"), "Face set"); attrs.VisibleName = "Helvetica Bold"; - Assert.AreEqual ("Helvetica Bold", attrs.VisibleName, "VisibleName set"); + Assert.That (attrs.VisibleName, Is.EqualTo ("Helvetica Bold"), "VisibleName set"); // Set back to null attrs.Family = null; - Assert.IsNull (attrs.Family, "Family cleared"); + Assert.That (attrs.Family, Is.Null, "Family cleared"); } [Test] @@ -58,11 +58,11 @@ public void UIFontAttributes_Size () var attrs = new UIFontAttributes (); attrs.Size = 14.0f; - Assert.IsTrue (attrs.Size.HasValue, "Size.HasValue"); - Assert.AreEqual (14.0f, attrs.Size.Value, "Size.Value"); + Assert.That (attrs.Size.HasValue, Is.True, "Size.HasValue"); + Assert.That (attrs.Size.Value, Is.EqualTo (14.0f), "Size.Value"); attrs.Size = null; - Assert.IsNull (attrs.Size, "Size cleared"); + Assert.That (attrs.Size, Is.Null, "Size cleared"); } [Test] @@ -71,10 +71,10 @@ public void UIFontAttributes_TextStyle_NullClears () var attrs = new UIFontAttributes (); attrs.TextStyle = UIFontTextStyle.Body.GetConstant (); - Assert.IsNotNull (attrs.TextStyle, "TextStyle set"); + Assert.That (attrs.TextStyle, Is.Not.Null, "TextStyle set"); attrs.TextStyle = null; - Assert.IsNull (attrs.TextStyle, "TextStyle cleared"); + Assert.That (attrs.TextStyle, Is.Null, "TextStyle cleared"); } [Test] @@ -84,11 +84,11 @@ public void UIFontAttributes_Matrix () var transform = CGAffineTransform.MakeScale (2, 2); attrs.Matrix = transform; - Assert.IsTrue (attrs.Matrix.HasValue, "Matrix.HasValue"); - Assert.AreEqual (transform, attrs.Matrix.Value, "Matrix.Value"); + Assert.That (attrs.Matrix.HasValue, Is.True, "Matrix.HasValue"); + Assert.That (attrs.Matrix.Value, Is.EqualTo (transform), "Matrix.Value"); attrs.Matrix = null; - Assert.IsNull (attrs.Matrix, "Matrix cleared"); + Assert.That (attrs.Matrix, Is.Null, "Matrix cleared"); } [Test] @@ -98,10 +98,10 @@ public void UIFontAttributes_CharacterSet_NullClears () var cs = NSCharacterSet.UppercaseLetters; attrs.CharacterSet = cs; - Assert.IsNotNull (attrs.CharacterSet, "CharacterSet set"); + Assert.That (attrs.CharacterSet, Is.Not.Null, "CharacterSet set"); attrs.CharacterSet = null; - Assert.IsNull (attrs.CharacterSet, "CharacterSet cleared"); + Assert.That (attrs.CharacterSet, Is.Null, "CharacterSet cleared"); } [Test] @@ -111,11 +111,11 @@ public void UIFontAttributes_CascadeList_NullClears () var desc = new UIFontDescriptor (); attrs.CascadeList = new [] { desc }; - Assert.IsNotNull (attrs.CascadeList, "CascadeList set"); - Assert.AreEqual (1, attrs.CascadeList.Length, "CascadeList.Length"); + Assert.That (attrs.CascadeList, Is.Not.Null, "CascadeList set"); + Assert.That (attrs.CascadeList.Length, Is.EqualTo (1), "CascadeList.Length"); attrs.CascadeList = null; - Assert.IsNull (attrs.CascadeList, "CascadeList cleared"); + Assert.That (attrs.CascadeList, Is.Null, "CascadeList cleared"); } [Test] @@ -126,11 +126,11 @@ public void UIFontAttributes_Traits_NullClears () traits.SymbolicTrait = UIFontDescriptorSymbolicTraits.Bold; attrs.Traits = traits; - Assert.IsNotNull (attrs.Traits, "Traits set"); - Assert.AreEqual (UIFontDescriptorSymbolicTraits.Bold, attrs.Traits.SymbolicTrait, "Traits.SymbolicTrait"); + Assert.That (attrs.Traits, Is.Not.Null, "Traits set"); + Assert.That (attrs.Traits.SymbolicTrait, Is.EqualTo (UIFontDescriptorSymbolicTraits.Bold), "Traits.SymbolicTrait"); attrs.Traits = null; - Assert.IsNull (attrs.Traits, "Traits cleared"); + Assert.That (attrs.Traits, Is.Null, "Traits cleared"); } [Test] @@ -139,11 +139,11 @@ public void UIFontAttributes_FixedAdvance () var attrs = new UIFontAttributes (); attrs.FixedAdvance = 10.0f; - Assert.IsTrue (attrs.FixedAdvance.HasValue, "FixedAdvance.HasValue"); - Assert.AreEqual (10.0f, attrs.FixedAdvance.Value, "FixedAdvance.Value"); + Assert.That (attrs.FixedAdvance.HasValue, Is.True, "FixedAdvance.HasValue"); + Assert.That (attrs.FixedAdvance.Value, Is.EqualTo (10.0f), "FixedAdvance.Value"); attrs.FixedAdvance = null; - Assert.IsNull (attrs.FixedAdvance, "FixedAdvance cleared"); + Assert.That (attrs.FixedAdvance, Is.Null, "FixedAdvance cleared"); } [Test] @@ -152,12 +152,12 @@ public void UIFontDescriptor_Properties_FromFont () var font = UIFont.BoldSystemFontOfSize (20); var descriptor = font.FontDescriptor; - Assert.IsNotNull (descriptor.Family, "Family"); - Assert.IsNotNull (descriptor.Name, "Name"); - Assert.IsNotNull (descriptor.Face, "Face"); - Assert.IsTrue (descriptor.Size.HasValue, "Size.HasValue"); - Assert.AreEqual (20.0f, descriptor.Size.Value, "Size.Value"); - Assert.IsNotNull (descriptor.CascadeList, "CascadeList"); + Assert.That (descriptor.Family, Is.Not.Null, "Family"); + Assert.That (descriptor.Name, Is.Not.Null, "Name"); + Assert.That (descriptor.Face, Is.Not.Null, "Face"); + Assert.That (descriptor.Size.HasValue, Is.True, "Size.HasValue"); + Assert.That (descriptor.Size.Value, Is.EqualTo (20.0f), "Size.Value"); + Assert.That (descriptor.CascadeList, Is.Not.Null, "CascadeList"); } [Test] @@ -180,36 +180,36 @@ public void UIFontDescriptor_EmptyDescriptor_NullableProperties () var weakFeature = descriptor.WeakFeatureSettings; var featureSettings = descriptor.FeatureSettings; - Assert.IsNotNull (cascadeList, "CascadeList never null"); - Assert.IsNotNull (featureSettings, "FeatureSettings never null"); + Assert.That (cascadeList, Is.Not.Null, "CascadeList never null"); + Assert.That (featureSettings, Is.Not.Null, "FeatureSettings never null"); } [Test] public void UIFontDescriptor_PreferredTitle1 () { var descriptor = UIFontDescriptor.PreferredTitle1; - Assert.IsNotNull (descriptor, "PreferredTitle1"); + Assert.That (descriptor, Is.Not.Null, "PreferredTitle1"); } [Test] public void UIFontDescriptor_PreferredTitle2 () { var descriptor = UIFontDescriptor.PreferredTitle2; - Assert.IsNotNull (descriptor, "PreferredTitle2"); + Assert.That (descriptor, Is.Not.Null, "PreferredTitle2"); } [Test] public void UIFontDescriptor_PreferredTitle3 () { var descriptor = UIFontDescriptor.PreferredTitle3; - Assert.IsNotNull (descriptor, "PreferredTitle3"); + Assert.That (descriptor, Is.Not.Null, "PreferredTitle3"); } [Test] public void UIFontDescriptor_PreferredCallout () { var descriptor = UIFontDescriptor.PreferredCallout; - Assert.IsNotNull (descriptor, "PreferredCallout"); + Assert.That (descriptor, Is.Not.Null, "PreferredCallout"); } [Test] @@ -219,7 +219,7 @@ public void UIFontDescriptor_GetMatchingFontDescriptors_Empty () var descriptor = font.FontDescriptor; var results = descriptor.GetMatchingFontDescriptors (); - Assert.IsNotNull (results, "empty mandatoryKeys"); + Assert.That (results, Is.Not.Null, "empty mandatoryKeys"); } [Test] @@ -229,17 +229,17 @@ public void UIFontDescriptor_GetMatchingFontDescriptors_WithKeys () var descriptor = font.FontDescriptor; var results = descriptor.GetMatchingFontDescriptors (UIFontDescriptorAttribute.Family); - Assert.IsNotNull (results, "with Family key"); + Assert.That (results, Is.Not.Null, "with Family key"); } [Test] public void UIFontTraits_DefaultConstructor () { var traits = new UIFontTraits (); - Assert.IsNull (traits.SymbolicTrait, "SymbolicTrait"); - Assert.IsNull (traits.Weight, "Weight"); - Assert.IsNull (traits.Width, "Width"); - Assert.IsNull (traits.Slant, "Slant"); + Assert.That (traits.SymbolicTrait, Is.Null, "SymbolicTrait"); + Assert.That (traits.Weight, Is.Null, "Weight"); + Assert.That (traits.Width, Is.Null, "Width"); + Assert.That (traits.Slant, Is.Null, "Slant"); } [Test] @@ -248,11 +248,11 @@ public void UIFontTraits_SymbolicTrait_SetAndClear () var traits = new UIFontTraits (); traits.SymbolicTrait = UIFontDescriptorSymbolicTraits.Bold; - Assert.IsTrue (traits.SymbolicTrait.HasValue, "SymbolicTrait.HasValue after set"); - Assert.AreEqual (UIFontDescriptorSymbolicTraits.Bold, traits.SymbolicTrait.Value, "SymbolicTrait.Value"); + Assert.That (traits.SymbolicTrait.HasValue, Is.True, "SymbolicTrait.HasValue after set"); + Assert.That (traits.SymbolicTrait.Value, Is.EqualTo (UIFontDescriptorSymbolicTraits.Bold), "SymbolicTrait.Value"); traits.SymbolicTrait = null; - Assert.IsNull (traits.SymbolicTrait, "SymbolicTrait after null"); + Assert.That (traits.SymbolicTrait, Is.Null, "SymbolicTrait after null"); } [Test] @@ -262,9 +262,9 @@ public void UIFontTraits_FromDescriptor () var descriptor = font.FontDescriptor; var traits = descriptor.Traits; - Assert.IsNotNull (traits, "Traits from bold font"); - Assert.IsTrue (traits.SymbolicTrait.HasValue, "SymbolicTrait.HasValue"); - Assert.IsTrue (traits.SymbolicTrait.Value.HasFlag (UIFontDescriptorSymbolicTraits.Bold), "Has Bold trait"); + Assert.That (traits, Is.Not.Null, "Traits from bold font"); + Assert.That (traits.SymbolicTrait.HasValue, Is.True, "SymbolicTrait.HasValue"); + Assert.That (traits.SymbolicTrait.Value.HasFlag (UIFontDescriptorSymbolicTraits.Bold), Is.True, "Has Bold trait"); } [Test] @@ -274,8 +274,8 @@ public void UIFontAttributes_FromDictionary () var descriptor = font.FontDescriptor; var fontAttrs = descriptor.FontAttributes; - Assert.IsTrue (fontAttrs.Size.HasValue, "Size.HasValue"); - Assert.AreEqual (14.0f, fontAttrs.Size.Value, "Size.Value"); + Assert.That (fontAttrs.Size.HasValue, Is.True, "Size.HasValue"); + Assert.That (fontAttrs.Size.Value, Is.EqualTo (14.0f), "Size.Value"); } [Test] @@ -283,10 +283,10 @@ public void UIFontAttributes_WeakFeatureSettings_NullClears () { var attrs = new UIFontAttributes (); - Assert.IsNull (attrs.WeakFeatureSettings, "WeakFeatureSettings initially null"); + Assert.That (attrs.WeakFeatureSettings, Is.Null, "WeakFeatureSettings initially null"); attrs.WeakFeatureSettings = null; - Assert.IsNull (attrs.WeakFeatureSettings, "WeakFeatureSettings after null set"); + Assert.That (attrs.WeakFeatureSettings, Is.Null, "WeakFeatureSettings after null set"); } } } diff --git a/tests/monotouch-test/UIKit/FontTest.cs b/tests/monotouch-test/UIKit/FontTest.cs index 68e642179ae3..cab0e8e66b6a 100644 --- a/tests/monotouch-test/UIKit/FontTest.cs +++ b/tests/monotouch-test/UIKit/FontTest.cs @@ -25,14 +25,14 @@ public void WithSize () { AssertNotBrokenFontWithSize (); var f1 = UIFont.SystemFontOfSize (10).WithSize (20); - Assert.AreEqual (f1.PointSize, (nfloat) 20, "#size"); + Assert.That ((nfloat) 20, Is.EqualTo (f1.PointSize), "#size"); } [Test] public void GetWeight () { var weight = UIFontWeight.Semibold; - Assert.AreEqual (weight.GetWeight (), UIFontWeightConstants.Semibold); + Assert.That (UIFontWeightConstants.Semibold, Is.EqualTo (weight.GetWeight ())); } [Test] @@ -48,8 +48,8 @@ public void TestDescriptors () // but make sure we dont regress if they fix it. var size = descriptor.FontAttributes.Size; - Assert.AreEqual (true, size.HasValue); - Assert.AreEqual (80.0f, size.Value); + Assert.That (size.HasValue, Is.EqualTo (true)); + Assert.That (size.Value, Is.EqualTo (80.0f)); } // ref: https://trello.com/c/wKZyugio/437-many-managed-peers-on-a-single-native-instance @@ -58,18 +58,18 @@ void SemiFactory_25511 (UIFont f1, UIFont f2, string api) { using (f1) { // the same instance will be returned (from an iOS cache) - Assert.That (f1.Handle, Is.EqualTo (f2.Handle), "{0} Handle", api); + Assert.That (f1.Handle, Is.EqualTo (f2.Handle), $"{api} Handle"); // using means f1 will be disposed and it's handle will be zero'ed // but f2 is the same (managed) instance and _normally_ would become unusable // to fix this we now return a different instance - but we must still match the existing behavior - Assert.True (f1 == f2, "{0} ==", api); - Assert.True (f1.Equals ((object) f2), "{0} Equals(object)", api); + Assert.That (f1 == f2, Is.True, $"{api} =="); + Assert.That (f1.Equals ((object) f2), Is.True, $"{api} Equals(object)"); // IEquatable is only in unified - otherwise it would be the same call as above - Assert.True (f1.Equals (f2), "{0} Equals", api); + Assert.That (f1.Equals (f2), Is.True, $"{api} Equals"); } - Assert.That (f1.Handle, Is.EqualTo (NativeHandle.Zero), "{0} 1", api); + Assert.That (f1.Handle, Is.EqualTo (NativeHandle.Zero), $"{api} 1"); // without our "fix" that would be the same managed instance (as f1) and the handle would be nil - Assert.That (f2.Handle, Is.Not.EqualTo (NativeHandle.Zero), "{0} 2", api); + Assert.That (f2.Handle, Is.Not.EqualTo (NativeHandle.Zero), $"{api} 2"); } [Test] @@ -163,25 +163,25 @@ public void NullFonts () { var invalidFontName = new NSString ("Invalid Font Name"); if (TestRuntime.CheckXcodeVersion (5, 0)) { - Assert.IsNotNull (UIFont.GetPreferredFontForTextStyle (invalidFontName), "GetPreferredFontForTextStyle"); - Assert.IsNotNull (UIFont.FromDescriptor (new UIFontDescriptor (), -2), "FromDescriptor (,)"); + Assert.That (UIFont.GetPreferredFontForTextStyle (invalidFontName), Is.Not.Null, "GetPreferredFontForTextStyle"); + Assert.That (UIFont.FromDescriptor (new UIFontDescriptor (), -2), Is.Not.Null, "FromDescriptor (,)"); } - Assert.IsNull (UIFont.FromName (invalidFontName, 1), "FromName"); + Assert.That (UIFont.FromName (invalidFontName, 1), Is.Null, "FromName"); - Assert.IsNotNull (UIFont.SystemFontOfSize (-3), "SystemFontOfSize()"); + Assert.That (UIFont.SystemFontOfSize (-3), Is.Not.Null, "SystemFontOfSize()"); if (TestRuntime.CheckXcodeVersion (6, 2)) { - Assert.IsNotNull (UIFont.SystemFontOfSize (0, UIFontWeight.Regular), "SystemFontOfSize (nfloat, UIFontWeight)"); - Assert.IsNotNull (UIFont.SystemFontOfSize (0, (nfloat) 0), "SystemFontOfSize (nfloat, nfloat)"); + Assert.That (UIFont.SystemFontOfSize (0, UIFontWeight.Regular), Is.Not.Null, "SystemFontOfSize (nfloat, UIFontWeight)"); + Assert.That (UIFont.SystemFontOfSize (0, (nfloat) 0), Is.Not.Null, "SystemFontOfSize (nfloat, nfloat)"); } - Assert.IsNotNull (UIFont.BoldSystemFontOfSize (-4), "BoldSystemFontOfSize"); - Assert.IsNotNull (UIFont.ItalicSystemFontOfSize (-5), "ItalicSystemFontOfSize"); + Assert.That (UIFont.BoldSystemFontOfSize (-4), Is.Not.Null, "BoldSystemFontOfSize"); + Assert.That (UIFont.ItalicSystemFontOfSize (-5), Is.Not.Null, "ItalicSystemFontOfSize"); AssertNotBrokenFontWithSize (); using (var font = UIFont.SystemFontOfSize (12)) { - Assert.IsNotNull (font.WithSize (-6), "WithSize"); + Assert.That (font.WithSize (-6), Is.Not.Null, "WithSize"); } } } diff --git a/tests/monotouch-test/UIKit/GestureRecognizerTest.cs b/tests/monotouch-test/UIKit/GestureRecognizerTest.cs index eb7f28064135..5a7547679513 100644 --- a/tests/monotouch-test/UIKit/GestureRecognizerTest.cs +++ b/tests/monotouch-test/UIKit/GestureRecognizerTest.cs @@ -79,9 +79,9 @@ public void NoStrongCycles () pool.Dispose (); TestRuntime.RunAsync (TimeSpan.FromSeconds (1), () => { GC.Collect (); }, () => finalizedAnyCtor && finalizedAnyAddTarget1 && finalizedAnyAddTarget2); - Assert.IsTrue (finalizedAnyCtor, "Any finalized"); - Assert.IsTrue (finalizedAnyAddTarget1, "AddTarget1 finalized"); - Assert.IsTrue (finalizedAnyAddTarget2, "AddTarget2 finalized"); + Assert.That (finalizedAnyCtor, Is.True, "Any finalized"); + Assert.That (finalizedAnyAddTarget1, Is.True, "AddTarget1 finalized"); + Assert.That (finalizedAnyAddTarget2, Is.True, "AddTarget2 finalized"); GC.KeepAlive (list); } @@ -109,7 +109,7 @@ public void GenericCallbackTest () // blocks main thread until event is trigerred callbackEvent.WaitOne (30000); - Assert.IsTrue (didRun, "didRun"); + Assert.That (didRun, Is.True, "didRun"); } class FinalizerNotifier { diff --git a/tests/monotouch-test/UIKit/GraphicsRendererTest.cs b/tests/monotouch-test/UIKit/GraphicsRendererTest.cs index 4519889bc5ed..96df4dffa2ef 100644 --- a/tests/monotouch-test/UIKit/GraphicsRendererTest.cs +++ b/tests/monotouch-test/UIKit/GraphicsRendererTest.cs @@ -28,7 +28,7 @@ public void Setup () public void BaseDefaultFormat () { var f = UIGraphicsRendererFormat.DefaultFormat; - Assert.True (f.Bounds.IsEmpty, "Bounds"); + Assert.That (f.Bounds.IsEmpty, Is.True, "Bounds"); Assert.That (f.GetType ().Name, Is.EqualTo ("UIGraphicsRendererFormat"), "Name"); } @@ -36,9 +36,9 @@ public void BaseDefaultFormat () public void ImageDefaultFormat () { var f = UIGraphicsImageRendererFormat.DefaultFormat; - Assert.True (f.Bounds.IsEmpty, "Bounds"); - Assert.False (f.Opaque, "Opaque"); - //Assert.False (f.PrefersExtendedRange, "PrefersExtendedRange"); // new iPhone (7/7+) returns True + Assert.That (f.Bounds.IsEmpty, Is.True, "Bounds"); + Assert.That (f.Opaque, Is.False, "Opaque"); + //Assert.That (f.PrefersExtendedRange, Is.False, "PrefersExtendedRange"); // new iPhone (7/7+) returns True Assert.That (f.Scale, Is.GreaterThan ((nfloat) 0), "Scale"); // varies on platform Assert.That (f.GetType ().Name, Is.EqualTo ("UIGraphicsImageRendererFormat"), "Name"); } @@ -47,8 +47,8 @@ public void ImageDefaultFormat () public void PdfDefaultFormat () { var f = UIGraphicsPdfRendererFormat.DefaultFormat; - Assert.True (f.Bounds.IsEmpty, "Bounds"); - Assert.Null (f.DocumentInfo, "DocumentInfo"); + Assert.That (f.Bounds.IsEmpty, Is.True, "Bounds"); + Assert.That (f.DocumentInfo, Is.Null, "DocumentInfo"); Assert.That (f.GetType ().Name, Is.EqualTo ("UIGraphicsPdfRendererFormat"), "Name"); } } diff --git a/tests/monotouch-test/UIKit/GuidedAccessRestrictionTest.cs b/tests/monotouch-test/UIKit/GuidedAccessRestrictionTest.cs index 46b0992379eb..72658b70538d 100644 --- a/tests/monotouch-test/UIKit/GuidedAccessRestrictionTest.cs +++ b/tests/monotouch-test/UIKit/GuidedAccessRestrictionTest.cs @@ -46,8 +46,8 @@ public void GuidedAccessConfigureAccessibilityFeaturesTest () } }, () => done); - Assert.NotNull (gotError, "Error was null."); - Assert.IsFalse (didSuccess, "Somehow this succeeded, are we running monotouch-tests app in kiosk mode?"); + Assert.That (gotError, Is.Not.Null, "Error was null."); + Assert.That (didSuccess, Is.False, "Somehow this succeeded, are we running monotouch-tests app in kiosk mode?"); } #endif // !__TVOS__ } diff --git a/tests/monotouch-test/UIKit/ImageTest.cs b/tests/monotouch-test/UIKit/ImageTest.cs index 1afc0dba0b32..cfbae71a78e6 100644 --- a/tests/monotouch-test/UIKit/ImageTest.cs +++ b/tests/monotouch-test/UIKit/ImageTest.cs @@ -53,10 +53,10 @@ public void CGImageBackend () Assert.That (resized.CGImage.Height, Is.EqualTo (resized.CGImage.Width), "Width-Height-identical"); // caching of the backing CGImage occurs on devices (but not always) if (TestRuntime.IsSimulatorOrDesktop) { - Assert.That ((nint) 16, Is.EqualTo (resized.CGImage.Width), "half"); + Assert.That (resized.CGImage.Width, Is.EqualTo ((nint) 16), "half"); } else { var h = resized.CGImage.Height; - Assert.True (h == 16 || h == 32, "mostly"); + Assert.That (h, Is.EqualTo (16).Or.EqualTo (32), "mostly"); } Assert.That (handle, Is.Not.EqualTo (resized.CGImage.Handle), "Handle"); } @@ -69,7 +69,7 @@ public void CreateAnimatedImage () using (var i = UIImage.CreateAnimatedImage ("xamarin", UIEdgeInsets.Zero, 1d)) { Assert.That (i.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); Assert.That (i.Images.Length, Is.EqualTo (3), "3 images"); - Assert.True (i.Description.Contains ("UIAnimatedImage"), "UIAnimatedImage"); + Assert.That (i.Description.Contains ("UIAnimatedImage"), Is.True, "UIAnimatedImage"); } } diff --git a/tests/monotouch-test/UIKit/ImageViewTest.cs b/tests/monotouch-test/UIKit/ImageViewTest.cs index 5b88d117629e..87ab793d779a 100644 --- a/tests/monotouch-test/UIKit/ImageViewTest.cs +++ b/tests/monotouch-test/UIKit/ImageViewTest.cs @@ -29,8 +29,8 @@ public void AnimationImages () using (var v = new UIImageView ()) { v.AnimationImages = new UIImage [] { i1, i2 }; // no need for [PostGet] since it does not change other properties - Assert.Null (v.Image, "Image"); - Assert.Null (v.HighlightedImage); + Assert.That (v.Image, Is.Null, "Image"); + Assert.That (v.HighlightedImage, Is.Null); } } @@ -42,8 +42,8 @@ public void HighlightedAnimationImages_BackingFields () using (var v = new UIImageView ()) { v.HighlightedAnimationImages = new UIImage [] { i1, i2 }; // no need for [PostGet] since it does not change other properties - Assert.Null (v.Image, "Image"); - Assert.Null (v.HighlightedImage); + Assert.That (v.Image, Is.Null, "Image"); + Assert.That (v.HighlightedImage, Is.Null); } } } diff --git a/tests/monotouch-test/UIKit/KeyCommandTest.cs b/tests/monotouch-test/UIKit/KeyCommandTest.cs index de8d9857c245..300fd6f1ee3f 100644 --- a/tests/monotouch-test/UIKit/KeyCommandTest.cs +++ b/tests/monotouch-test/UIKit/KeyCommandTest.cs @@ -12,7 +12,7 @@ public class KeyCommandTest { public void Create () { using (var key = new NSString ("a")) { - Assert.NotNull (UIKeyCommand.Create (key, UIKeyModifierFlags.Command, new Selector ("foo")), "Create"); + Assert.That (UIKeyCommand.Create (key, UIKeyModifierFlags.Command, new Selector ("foo")), Is.Not.Null, "Create"); } } } diff --git a/tests/monotouch-test/UIKit/LabelTest.cs b/tests/monotouch-test/UIKit/LabelTest.cs index 4cd20716be36..6c88fed122f6 100644 --- a/tests/monotouch-test/UIKit/LabelTest.cs +++ b/tests/monotouch-test/UIKit/LabelTest.cs @@ -25,11 +25,11 @@ public void InitWithFrame () public void HighlightedTextColor () { UILabel label = new UILabel (); - Assert.Null (label.HighlightedTextColor, "HighlightedTextColor/default"); + Assert.That (label.HighlightedTextColor, Is.Null, "HighlightedTextColor/default"); label.HighlightedTextColor = UIColor.Blue; Assert.That (label.HighlightedTextColor, Is.EqualTo (UIColor.Blue), "HighlightedTextColor/blue"); label.HighlightedTextColor = null; - Assert.Null (label.HighlightedTextColor, "HighlightedTextColor/null"); + Assert.That (label.HighlightedTextColor, Is.Null, "HighlightedTextColor/null"); } } } diff --git a/tests/monotouch-test/UIKit/LayoutConstraintTest.cs b/tests/monotouch-test/UIKit/LayoutConstraintTest.cs index b27bc28363c7..5020ba605286 100644 --- a/tests/monotouch-test/UIKit/LayoutConstraintTest.cs +++ b/tests/monotouch-test/UIKit/LayoutConstraintTest.cs @@ -42,7 +42,7 @@ public void FromVisualFormat () dict ["button0"] = b0; dict ["button1"] = b1; var constaints = NSLayoutConstraint.FromVisualFormat ("[button0]-20-[button1]", NSLayoutFormatOptions.AlignAllBaseline, metrics, dict); - Assert.NotNull (constaints); + Assert.That (constaints, Is.Not.Null); } } } diff --git a/tests/monotouch-test/UIKit/LayoutManagerTest.cs b/tests/monotouch-test/UIKit/LayoutManagerTest.cs index 199e03d07037..784198539e02 100644 --- a/tests/monotouch-test/UIKit/LayoutManagerTest.cs +++ b/tests/monotouch-test/UIKit/LayoutManagerTest.cs @@ -24,23 +24,23 @@ public void Defaults () TestRuntime.AssertSystemVersion (ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false); using (var lm = new NSLayoutManager ()) { - Assert.False (lm.AllowsNonContiguousLayout, "AllowsNonContiguousLayout"); - Assert.True (lm.ExtraLineFragmentRect.IsEmpty, "ExtraLineFragmentRect"); - Assert.Null (lm.ExtraLineFragmentTextContainer, "ExtraLineFragmentTextContainer"); - Assert.True (lm.ExtraLineFragmentUsedRect.IsEmpty, "ExtraLineFragmentUsedRect"); + Assert.That (lm.AllowsNonContiguousLayout, Is.False, "AllowsNonContiguousLayout"); + Assert.That (lm.ExtraLineFragmentRect.IsEmpty, Is.True, "ExtraLineFragmentRect"); + Assert.That (lm.ExtraLineFragmentTextContainer, Is.Null, "ExtraLineFragmentTextContainer"); + Assert.That (lm.ExtraLineFragmentUsedRect.IsEmpty, Is.True, "ExtraLineFragmentUsedRect"); Assert.That (lm.FirstUnlaidCharacterIndex, Is.EqualTo ((nuint) 0), "FirstUnlaidCharacterIndex"); Assert.That (lm.FirstUnlaidGlyphIndex, Is.EqualTo ((nuint) 0), "FirstUnlaidGlyphIndex"); - Assert.False (lm.HasNonContiguousLayout, "HasNonContiguousLayout"); + Assert.That (lm.HasNonContiguousLayout, Is.False, "HasNonContiguousLayout"); #if !__MACCATALYST__ Assert.That (lm.HyphenationFactor, Is.EqualTo ((nfloat) 0), "HyphenationFactor"); #endif Assert.That (lm.NumberOfGlyphs, Is.EqualTo ((nuint) 0), "NumberOfGlyphs"); - Assert.False (lm.ShowsControlCharacters, "ShowsControlCharacters"); - Assert.False (lm.ShowsInvisibleCharacters, "ShowsInvisibleCharacters"); - Assert.Null (lm.TextStorage, "TextStorage"); - Assert.True (lm.UsesFontLeading, "UsesFontLeading"); + Assert.That (lm.ShowsControlCharacters, Is.False, "ShowsControlCharacters"); + Assert.That (lm.ShowsInvisibleCharacters, Is.False, "ShowsInvisibleCharacters"); + Assert.That (lm.TextStorage, Is.Null, "TextStorage"); + Assert.That (lm.UsesFontLeading, Is.True, "UsesFontLeading"); if (TestRuntime.CheckXcodeVersion (10, 0)) - Assert.False (lm.LimitsLayoutForSuspiciousContents, "LimitsLayoutForSuspiciousContents"); + Assert.That (lm.LimitsLayoutForSuspiciousContents, Is.False, "LimitsLayoutForSuspiciousContents"); } } diff --git a/tests/monotouch-test/UIKit/LocalNotificationTest.cs b/tests/monotouch-test/UIKit/LocalNotificationTest.cs index 4e98f4d443e5..64f93fb3cc62 100644 --- a/tests/monotouch-test/UIKit/LocalNotificationTest.cs +++ b/tests/monotouch-test/UIKit/LocalNotificationTest.cs @@ -21,17 +21,17 @@ public class LocalNotificationTest { public void DefaultValues () { using (var def = new UILocalNotification ()) { - Assert.IsNull (def.FireDate, "FireDate"); - Assert.IsNull (def.TimeZone, "TimeZone"); + Assert.That (def.FireDate, Is.Null, "FireDate"); + Assert.That (def.TimeZone, Is.Null, "TimeZone"); Assert.That ((nuint) (ulong) def.RepeatInterval, Is.EqualTo ((nuint) 0), "RepeatInterval"); // documented to be 0, which is not in the enum. - Assert.IsNull (def.RepeatCalendar, "RepeatCalendar"); - Assert.IsNull (def.AlertBody, "AlertBody"); - Assert.IsTrue (def.HasAction, "HasAction"); - Assert.IsNull (def.AlertAction, "AlertAction"); - Assert.IsNull (def.AlertLaunchImage, "AlertLaunchImage"); - Assert.IsNull (def.SoundName, "SoundName"); + Assert.That (def.RepeatCalendar, Is.Null, "RepeatCalendar"); + Assert.That (def.AlertBody, Is.Null, "AlertBody"); + Assert.That (def.HasAction, Is.True, "HasAction"); + Assert.That (def.AlertAction, Is.Null, "AlertAction"); + Assert.That (def.AlertLaunchImage, Is.Null, "AlertLaunchImage"); + Assert.That (def.SoundName, Is.Null, "SoundName"); Assert.That (def.ApplicationIconBadgeNumber, Is.EqualTo ((nint) 0), "ApplicationIconBadgeNumber"); - Assert.IsNull (def.UserInfo, "UserInfo"); + Assert.That (def.UserInfo, Is.Null, "UserInfo"); } } @@ -41,15 +41,15 @@ public void NullValues () using (var def = new UILocalNotification ()) { def.FireDate = null; def.FireDate = new NSDate (); - Assert.IsNotNull (def.FireDate, "FireDate NN"); + Assert.That (def.FireDate, Is.Not.Null, "FireDate NN"); def.FireDate = null; - Assert.IsNull (def.FireDate, "FireDate N"); + Assert.That (def.FireDate, Is.Null, "FireDate N"); def.TimeZone = null; def.TimeZone = new NSTimeZone ("GMT"); - Assert.IsNotNull (def.TimeZone, "TimeZone NN"); + Assert.That (def.TimeZone, Is.Not.Null, "TimeZone NN"); def.TimeZone = null; - Assert.IsNull (def.TimeZone, "TimeZone N"); + Assert.That (def.TimeZone, Is.Null, "TimeZone N"); def.RepeatInterval = NSCalendarUnit.Calendar; Assert.That (def.RepeatInterval, Is.EqualTo (NSCalendarUnit.Calendar), "RepeatInterval 1"); @@ -58,39 +58,39 @@ public void NullValues () def.RepeatCalendar = null; def.RepeatCalendar = new NSCalendar (NSCalendarType.Hebrew); - Assert.IsNotNull (def.RepeatCalendar, "RepeatCalendar NN"); + Assert.That (def.RepeatCalendar, Is.Not.Null, "RepeatCalendar NN"); def.RepeatCalendar = null; - Assert.IsNull (def.RepeatCalendar, "RepeatCalendar N"); + Assert.That (def.RepeatCalendar, Is.Null, "RepeatCalendar N"); def.AlertBody = null; def.AlertBody = "body"; - Assert.AreEqual ("body", def.AlertBody, "AlertBody NN"); + Assert.That (def.AlertBody, Is.EqualTo ("body"), "AlertBody NN"); def.AlertBody = null; - Assert.IsNull (def.AlertBody, "AlertBody N"); + Assert.That (def.AlertBody, Is.Null, "AlertBody N"); def.AlertAction = null; def.AlertAction = "action"; - Assert.AreEqual ("action", def.AlertAction, "AlertAction NN"); + Assert.That (def.AlertAction, Is.EqualTo ("action"), "AlertAction NN"); def.AlertAction = null; - Assert.IsNull (def.AlertAction, "AlertAction N"); + Assert.That (def.AlertAction, Is.Null, "AlertAction N"); def.AlertLaunchImage = null; def.AlertLaunchImage = "image"; - Assert.AreEqual ("image", def.AlertLaunchImage, "AlertLaunchImage NN"); + Assert.That (def.AlertLaunchImage, Is.EqualTo ("image"), "AlertLaunchImage NN"); def.AlertLaunchImage = null; - Assert.IsNull (def.AlertLaunchImage, "AlertLaunchImage N"); + Assert.That (def.AlertLaunchImage, Is.Null, "AlertLaunchImage N"); def.SoundName = null; def.SoundName = "sound"; - Assert.AreEqual ("sound", def.SoundName, "SoundName NN"); + Assert.That (def.SoundName, Is.EqualTo ("sound"), "SoundName NN"); def.SoundName = null; - Assert.IsNull (def.SoundName, "SoundName N"); + Assert.That (def.SoundName, Is.Null, "SoundName N"); def.UserInfo = null; def.UserInfo = new NSDictionary (); - Assert.IsNotNull (def.UserInfo, "UserInfo NN"); + Assert.That (def.UserInfo, Is.Not.Null, "UserInfo NN"); def.UserInfo = null; - Assert.IsNull (def.UserInfo, "UserInfo N"); + Assert.That (def.UserInfo, Is.Null, "UserInfo N"); } } } diff --git a/tests/monotouch-test/UIKit/NSDiffableDataSourceSnapshotTest.cs b/tests/monotouch-test/UIKit/NSDiffableDataSourceSnapshotTest.cs index 512d32658478..65ca64653451 100644 --- a/tests/monotouch-test/UIKit/NSDiffableDataSourceSnapshotTest.cs +++ b/tests/monotouch-test/UIKit/NSDiffableDataSourceSnapshotTest.cs @@ -27,11 +27,11 @@ public void Setup () public void GHIssue6567Test () { var type = typeof (UICollectionViewDiffableDataSource<,>); - Assert.NotNull (type, $"{nameof (type)} was null;"); + Assert.That (type, Is.Not.Null, $"{nameof (type)} was null;"); Class cls = null; Assert.DoesNotThrow (() => cls = new Class (type), "Should not throw"); - Assert.NotNull (cls, $"{nameof (cls)} was null"); + Assert.That (cls, Is.Not.Null, $"{nameof (cls)} was null"); } [Test] diff --git a/tests/monotouch-test/UIKit/NavigationBarTest.cs b/tests/monotouch-test/UIKit/NavigationBarTest.cs index 6064a1f90e47..5236fb428df8 100644 --- a/tests/monotouch-test/UIKit/NavigationBarTest.cs +++ b/tests/monotouch-test/UIKit/NavigationBarTest.cs @@ -26,7 +26,7 @@ public void BackgroundImage () { // http://stackoverflow.com/q/10504966/220643 using (UINavigationBar nb = new UINavigationBar ()) { - Assert.Null (nb.GetBackgroundImage (UIBarMetrics.Default), "Get"); + Assert.That (nb.GetBackgroundImage (UIBarMetrics.Default), Is.Null, "Get"); nb.SetBackgroundImage (null, UIBarMetrics.Default); } } diff --git a/tests/monotouch-test/UIKit/NibTest.cs b/tests/monotouch-test/UIKit/NibTest.cs index e2fec0f03346..4b17859d0b76 100644 --- a/tests/monotouch-test/UIKit/NibTest.cs +++ b/tests/monotouch-test/UIKit/NibTest.cs @@ -23,7 +23,7 @@ public void FromName_DoesNotExists () using (UINib n = UINib.FromName ("does-not-exists", null)) { // note: it's not really loaded until `instantiateWithOwner:options:` is called // so the result is not null - Assert.NotNull (n, "created with null options"); + Assert.That (n, Is.Not.Null, "created with null options"); } } @@ -32,7 +32,7 @@ public void FromName_DoesNotExists () public void FromName () { using (UINib n = UINib.FromName ("EmptyNib", null)) { - Assert.NotNull (n, "created with null options"); + Assert.That (n, Is.Not.Null, "created with null options"); // newer version (same selector) var result2 = n.Instantiate (null, null); Assert.That (result2.Length, Is.EqualTo (0), "Instantiate"); @@ -44,7 +44,7 @@ public void FromData () { using (NSData data = NSData.FromFile ("EmptyNib.nib")) using (UINib n = UINib.FromData (data, null)) { - Assert.NotNull (n, "created with null options"); + Assert.That (n, Is.Not.Null, "created with null options"); // newer version (same selector) var result2 = n.Instantiate (null, null); Assert.That (result2.Length, Is.EqualTo (0), "Instantiate"); diff --git a/tests/monotouch-test/UIKit/PageViewControllerTest.cs b/tests/monotouch-test/UIKit/PageViewControllerTest.cs index 7c6692f55d7d..fc6d9675d684 100644 --- a/tests/monotouch-test/UIKit/PageViewControllerTest.cs +++ b/tests/monotouch-test/UIKit/PageViewControllerTest.cs @@ -21,14 +21,14 @@ public class PageViewControllerTest { public void Defaults () { UIPageViewController pvc = new UIPageViewController (); - Assert.Null (pvc.DataSource, "DataSource"); - Assert.Null (pvc.Delegate, "Delegate"); - Assert.False (pvc.DoubleSided, "DoubleSided"); + Assert.That (pvc.DataSource, Is.Null, "DataSource"); + Assert.That (pvc.Delegate, Is.Null, "Delegate"); + Assert.That (pvc.DoubleSided, Is.False, "DoubleSided"); Assert.That (pvc.GestureRecognizers.Length, Is.EqualTo (2), "GestureRecognizers"); - Assert.Null (pvc.GetNextViewController, "GetNextViewController"); - Assert.Null (pvc.GetPreviousViewController, "GetPreviousViewController"); + Assert.That (pvc.GetNextViewController, Is.Null, "GetNextViewController"); + Assert.That (pvc.GetPreviousViewController, Is.Null, "GetPreviousViewController"); #if !__TVOS__ - Assert.Null (pvc.GetSpineLocation, "GetSpineLocation"); + Assert.That (pvc.GetSpineLocation, Is.Null, "GetSpineLocation"); #endif Assert.That (pvc.NavigationOrientation, Is.EqualTo (UIPageViewControllerNavigationOrientation.Horizontal), "NavigationOrientation"); Assert.That (pvc.SpineLocation, Is.EqualTo (UIPageViewControllerSpineLocation.Min), "SpineLocation"); @@ -44,12 +44,12 @@ public void SetViewControllers () pvc = new UIPageViewController (); // note: Complete is called synchronously pvc.SetViewControllers (pvc.ViewControllers, UIPageViewControllerNavigationDirection.Forward, false, Complete); - Assert.Null (pvc, "pvc"); + Assert.That (pvc, Is.Null, "pvc"); } void Complete (bool finished) { - Assert.True (finished, "finished"); + Assert.That (finished, Is.True, "finished"); pvc = null; } } diff --git a/tests/monotouch-test/UIKit/PasteboardTest.cs b/tests/monotouch-test/UIKit/PasteboardTest.cs index 7063bdcb0952..a5646973bbc8 100644 --- a/tests/monotouch-test/UIKit/PasteboardTest.cs +++ b/tests/monotouch-test/UIKit/PasteboardTest.cs @@ -25,14 +25,14 @@ public void ImagesTest () using (var img = new UIImage (cgimg)) { UIPasteboard.General.Images = new UIImage [] { img }; if (TestRuntime.CheckXcodeVersion (8, 0)) - Assert.True (UIPasteboard.General.HasImages, "HasImages"); + Assert.That (UIPasteboard.General.HasImages, Is.True, "HasImages"); - Assert.AreEqual (1, UIPasteboard.General.Images.Length, "a - length"); + Assert.That (UIPasteboard.General.Images.Length, Is.EqualTo (1), "a - length"); UIPasteboard.General.Images = new UIImage [] { img, img }; - Assert.AreEqual (2, UIPasteboard.General.Images.Length, "b - length"); - Assert.IsNotNull (UIPasteboard.General.Images [0], "b - nonnull[0]"); - Assert.IsNotNull (UIPasteboard.General.Images [1], "b - nonnull[0]"); + Assert.That (UIPasteboard.General.Images.Length, Is.EqualTo (2), "b - length"); + Assert.That (UIPasteboard.General.Images [0], Is.Not.Null, "b - nonnull[0]"); + Assert.That (UIPasteboard.General.Images [1], Is.Not.Null, "b - nonnull[0]"); } } } diff --git a/tests/monotouch-test/UIKit/PickerViewTest.cs b/tests/monotouch-test/UIKit/PickerViewTest.cs index 38ed5f708b65..7e09a89acb83 100644 --- a/tests/monotouch-test/UIKit/PickerViewTest.cs +++ b/tests/monotouch-test/UIKit/PickerViewTest.cs @@ -28,7 +28,7 @@ public void InitWithFrame () public void ConformsTo () { using (UIPickerView pv = new UIPickerView ()) { - Assert.True (pv.ConformsToProtocol (Protocol.GetHandle ("UITableViewDataSource")), "UITableViewDataSource"); + Assert.That (pv.ConformsToProtocol (Protocol.GetHandle ("UITableViewDataSource")), Is.True, "UITableViewDataSource"); } } } diff --git a/tests/monotouch-test/UIKit/PopoverControllerTest.cs b/tests/monotouch-test/UIKit/PopoverControllerTest.cs index eed1f37db61d..c34a7b4e924c 100644 --- a/tests/monotouch-test/UIKit/PopoverControllerTest.cs +++ b/tests/monotouch-test/UIKit/PopoverControllerTest.cs @@ -27,12 +27,12 @@ public void Defaults () using (var vc = new UIViewController ()) using (var pc = new UIPopoverController (vc)) { Assert.That (pc.ContentViewController, Is.SameAs (vc), "ContentViewController"); - Assert.Null (pc.PassthroughViews, "PassthroughViews"); + Assert.That (pc.PassthroughViews, Is.Null, "PassthroughViews"); Assert.That (pc.PopoverArrowDirection, Is.EqualTo (UIPopoverArrowDirection.Unknown), "PopoverArrowDirection"); Assert.That (pc.PopoverContentSize.IsEmpty, Is.EqualTo (ios8), "PopoverContentSize"); Assert.That (pc.PopoverLayoutMargins.ToString (), Is.EqualTo (ios8 ? "{0, 0, 0, 0}" : "{30, 10, 10, 10}"), "PopoverLayoutMargins"); - Assert.False (pc.PopoverVisible, "PopoverVisible"); - Assert.Null (pc.ShouldDismiss, "ShouldDismiss"); + Assert.That (pc.PopoverVisible, Is.False, "PopoverVisible"); + Assert.That (pc.ShouldDismiss, Is.Null, "ShouldDismiss"); } } @@ -110,7 +110,7 @@ public void PopoverBackgroundViewType () using (var vc = new UIViewController ()) using (var pc = new UIPopoverController (vc)) { - Assert.Null (pc.PopoverBackgroundViewType, "PopoverBackgroundViewType"); + Assert.That (pc.PopoverBackgroundViewType, Is.Null, "PopoverBackgroundViewType"); Type my = typeof (MyPopoverBackgroundView); pc.PopoverBackgroundViewType = my; Assert.That (pc.PopoverBackgroundViewType, Is.SameAs (my), "MyPopoverBackgroundView"); diff --git a/tests/monotouch-test/UIKit/PopoverPresentationControllerTest.cs b/tests/monotouch-test/UIKit/PopoverPresentationControllerTest.cs index d1c03c47cf54..7886956c7fe2 100644 --- a/tests/monotouch-test/UIKit/PopoverPresentationControllerTest.cs +++ b/tests/monotouch-test/UIKit/PopoverPresentationControllerTest.cs @@ -21,7 +21,7 @@ public void PopoverBackgroundViewType () using (var vc = new UIViewController ()) using (var pc = new UIPopoverPresentationController (vc, null)) { - Assert.Null (pc.PopoverBackgroundViewType, "PopoverBackgroundViewType"); + Assert.That (pc.PopoverBackgroundViewType, Is.Null, "PopoverBackgroundViewType"); Type my = typeof (MyPopoverBackgroundView); pc.PopoverBackgroundViewType = my; Assert.That (pc.PopoverBackgroundViewType, Is.SameAs (my), "MyPopoverBackgroundView"); diff --git a/tests/monotouch-test/UIKit/ReferenceLibraryViewControllerTest.cs b/tests/monotouch-test/UIKit/ReferenceLibraryViewControllerTest.cs index 03c011cd72dd..3c3a54ecf077 100644 --- a/tests/monotouch-test/UIKit/ReferenceLibraryViewControllerTest.cs +++ b/tests/monotouch-test/UIKit/ReferenceLibraryViewControllerTest.cs @@ -32,8 +32,8 @@ public void DictionaryHasDefinitionForTerm () { // note: iOS 6 beta 3 fails with: +[_UIDictionaryWrapper _availableDictionaryAssets] returned failed - retrying. Error: Error Domain=ASError Code=4 "The operation couldn’t be completed. (ASError error 4 - Unable to copy asset information)" UserInfo=0x16ac81a0 {NSDescription=Unable to copy asset information} // beta 3 always return true, beta 4 false ... - Assert.True (UIReferenceLibraryViewController.DictionaryHasDefinitionForTerm ("Mono"), "Mono"); - Assert.False (UIReferenceLibraryViewController.DictionaryHasDefinitionForTerm ("zozo"), "zozo"); + Assert.That (UIReferenceLibraryViewController.DictionaryHasDefinitionForTerm ("Mono"), Is.True, "Mono"); + Assert.That (UIReferenceLibraryViewController.DictionaryHasDefinitionForTerm ("zozo"), Is.False, "zozo"); } } } diff --git a/tests/monotouch-test/UIKit/SegmentedControlTest.cs b/tests/monotouch-test/UIKit/SegmentedControlTest.cs index dd4ef58077b7..d3190059d25e 100644 --- a/tests/monotouch-test/UIKit/SegmentedControlTest.cs +++ b/tests/monotouch-test/UIKit/SegmentedControlTest.cs @@ -26,7 +26,7 @@ public void InitWithFrame () public void BackgroundImage () { using (UISegmentedControl sc = new UISegmentedControl ()) { - Assert.Null (sc.GetBackgroundImage (UIControlState.Application, UIBarMetrics.Default), "Get"); + Assert.That (sc.GetBackgroundImage (UIControlState.Application, UIBarMetrics.Default), Is.Null, "Get"); sc.SetBackgroundImage (null, UIControlState.Application, UIBarMetrics.Default); } } @@ -111,9 +111,9 @@ public void TitleTextAttributes () using var sc = new UISegmentedControl ("one", "two"); sc.SetTitleTextAttributes (new UIStringAttributes () { ForegroundColor = UIColor.Gray }, UIControlState.Selected); var attrib = sc.GetTitleTextAttributes (UIControlState.Selected); - Assert.AreEqual (UIColor.Gray, attrib?.ForegroundColor, "ForegroundColor"); - Assert.IsNotNull (attrib?.Dictionary, "Dictionary"); - Assert.AreNotEqual (NativeHandle.Zero, attrib.Dictionary.Handle, "Dictionary.Handle"); + Assert.That (attrib?.ForegroundColor, Is.EqualTo (UIColor.Gray), "ForegroundColor"); + Assert.That (attrib?.Dictionary, Is.Not.Null, "Dictionary"); + Assert.That (attrib.Dictionary.Handle, Is.Not.EqualTo (NativeHandle.Zero), "Dictionary.Handle"); } } } diff --git a/tests/monotouch-test/UIKit/SimpleTextPrintFormatterTest.cs b/tests/monotouch-test/UIKit/SimpleTextPrintFormatterTest.cs index aecc939203d4..1fe5d453be43 100644 --- a/tests/monotouch-test/UIKit/SimpleTextPrintFormatterTest.cs +++ b/tests/monotouch-test/UIKit/SimpleTextPrintFormatterTest.cs @@ -24,19 +24,19 @@ public void StringCtor () { using (var stpf = new UISimpleTextPrintFormatter ("Xamarin")) { if (TestRuntime.CheckXcodeVersion (11, 0)) { - Assert.NotNull (stpf.Color, "Color"); + Assert.That (stpf.Color, Is.Not.Null, "Color"); Assert.That (stpf.TextAlignment, Is.EqualTo (UITextAlignment.Natural), "TextAlignment"); } else if (TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false)) { - Assert.Null (stpf.Color, "Color"); + Assert.That (stpf.Color, Is.Null, "Color"); Assert.That (stpf.TextAlignment, Is.EqualTo (UITextAlignment.Natural), "TextAlignment"); } else { Assert.That (stpf.Color, Is.EqualTo (UIColor.Black), "Color"); Assert.That (stpf.TextAlignment, Is.EqualTo (UITextAlignment.Left), "TextAlignment"); } if (TestRuntime.CheckXcodeVersion (14, 0)) { - Assert.Null (stpf.Font, "Font"); + Assert.That (stpf.Font, Is.Null, "Font"); } else { - Assert.NotNull (stpf.Font, "Font"); + Assert.That (stpf.Font, Is.Not.Null, "Font"); } Assert.That (stpf.Text, Is.EqualTo ("Xamarin"), "Text"); } diff --git a/tests/monotouch-test/UIKit/SplitViewControllerTest.cs b/tests/monotouch-test/UIKit/SplitViewControllerTest.cs index b523a8000d37..2f8457fecab4 100644 --- a/tests/monotouch-test/UIKit/SplitViewControllerTest.cs +++ b/tests/monotouch-test/UIKit/SplitViewControllerTest.cs @@ -26,13 +26,13 @@ public void Defaults () svc.ViewControllers = new UIViewController [] { v1, v2 }; - Assert.AreSame (v1, svc.ViewControllers [0], "vc0"); - Assert.AreSame (v2, svc.ViewControllers [1], "vc1"); + Assert.That (svc.ViewControllers [0], Is.SameAs (v1), "vc0"); + Assert.That (svc.ViewControllers [1], Is.SameAs (v2), "vc1"); if (!TestRuntime.CheckXcodeVersion (26, 0)) { Assert.That (svc.ChildViewControllers.Length, Is.AtLeast (2), "cvc.Length"); - Assert.AreSame (v1, svc.ChildViewControllers [0], "cvc0"); - Assert.AreSame (v2, svc.ChildViewControllers [1], "cvc1"); + Assert.That (svc.ChildViewControllers [0], Is.SameAs (v1), "cvc0"); + Assert.That (svc.ChildViewControllers [1], Is.SameAs (v2), "cvc1"); } } } @@ -48,7 +48,7 @@ public void PresentsWithGesture () TestRuntime.IgnoreOnTVOS (); using (UISplitViewController svc = new UISplitViewController ()) { - Assert.True (svc.PresentsWithGesture, "PresentsWithGesture/default"); + Assert.That (svc.PresentsWithGesture, Is.True, "PresentsWithGesture/default"); } } } diff --git a/tests/monotouch-test/UIKit/StringAttributesTest.cs b/tests/monotouch-test/UIKit/StringAttributesTest.cs index dcdd7490f245..0d59a8ca9f64 100644 --- a/tests/monotouch-test/UIKit/StringAttributesTest.cs +++ b/tests/monotouch-test/UIKit/StringAttributesTest.cs @@ -51,10 +51,10 @@ public void RetainCount () Assert.That (ps.RetainCount, Is.EqualTo ((nuint) 2), "ParagraphStyle-set"); for (int i = 0; i < 16; i++) { - Assert.NotNull (sa.BackgroundColor, "BackgroundColor-get"); - Assert.NotNull (sa.ForegroundColor, "ForegroundColor-get"); - Assert.NotNull (sa.Font, "Font-get"); - Assert.NotNull (sa.ParagraphStyle, "ParagraphStyle-get"); + Assert.That (sa.BackgroundColor, Is.Not.Null, "BackgroundColor-get"); + Assert.That (sa.ForegroundColor, Is.Not.Null, "ForegroundColor-get"); + Assert.That (sa.Font, Is.Not.Null, "Font-get"); + Assert.That (sa.ParagraphStyle, Is.Not.Null, "ParagraphStyle-get"); } Assert.That (sa.BackgroundColor.RetainCount, Is.EqualTo ((nuint) 3), "BackgroundColor"); @@ -97,10 +97,10 @@ public void RetainCount_7 () Assert.That (ta.RetainCount, Is.EqualTo ((nuint) 2), "TextAttachment-set"); for (int i = 0; i < 16; i++) { - Assert.NotNull (sa.UnderlineColor, "UnderlineColor-get"); - Assert.NotNull (sa.StrikethroughColor, "StrikethroughColor-get"); - Assert.NotNull (sa.Link, "Link-get"); - Assert.NotNull (sa.TextAttachment, "TextAttachment-get"); + Assert.That (sa.UnderlineColor, Is.Not.Null, "UnderlineColor-get"); + Assert.That (sa.StrikethroughColor, Is.Not.Null, "StrikethroughColor-get"); + Assert.That (sa.Link, Is.Not.Null, "Link-get"); + Assert.That (sa.TextAttachment, Is.Not.Null, "TextAttachment-get"); } Assert.That (sa.UnderlineColor.RetainCount, Is.EqualTo ((nuint) 3), "UnderlineColor"); @@ -122,14 +122,14 @@ public void MutableStringAttributesTest () // This test proves that the bug is fixed using (var nb = new UINavigationBar ()) { - Assert.Null (nb.TitleTextAttributes, "TitleTextAttributes should be null"); + Assert.That (nb.TitleTextAttributes, Is.Null, "TitleTextAttributes should be null"); nb.TitleTextAttributes = new UIStringAttributes { ForegroundColor = UIColor.Green }; - Assert.AreSame (UIColor.Green, nb.TitleTextAttributes.ForegroundColor, "TitleTextAttributes.ForegroundColor should match"); + Assert.That (nb.TitleTextAttributes.ForegroundColor, Is.SameAs (UIColor.Green), "TitleTextAttributes.ForegroundColor should match"); var titleAttribtues = nb.TitleTextAttributes; // we now get a mutable dictionary for this DictionaryContainer titleAttribtues.ForegroundColor = UIColor.Red; // this used to throw unrecognized selector before fixing bug 28158 nb.TitleTextAttributes = titleAttribtues; - Assert.AreSame (UIColor.Red, nb.TitleTextAttributes.ForegroundColor, "TitleTextAttributes.ForegroundColor should match"); + Assert.That (nb.TitleTextAttributes.ForegroundColor, Is.SameAs (UIColor.Red), "TitleTextAttributes.ForegroundColor should match"); } } diff --git a/tests/monotouch-test/UIKit/TabBarControllerTest.cs b/tests/monotouch-test/UIKit/TabBarControllerTest.cs index bbbbdad9d909..4600f2ac988b 100644 --- a/tests/monotouch-test/UIKit/TabBarControllerTest.cs +++ b/tests/monotouch-test/UIKit/TabBarControllerTest.cs @@ -21,14 +21,14 @@ public class TabBarControllerTest { void CheckDefault (UITabBarController c) { #if !__TVOS__ - Assert.Null (c.CustomizableViewControllers, "CustomizableViewControllers"); - Assert.NotNull (c.MoreNavigationController, "MoreNavigationController"); + Assert.That (c.CustomizableViewControllers, Is.Null, "CustomizableViewControllers"); + Assert.That (c.MoreNavigationController, Is.Not.Null, "MoreNavigationController"); #endif Assert.That (c.SelectedIndex, Is.EqualTo (nint.MaxValue), "SelectedIndex"); - Assert.Null (c.SelectedViewController, "SelectedViewController"); - Assert.Null (c.ShouldSelectViewController, "ShouldSelectViewController"); - Assert.NotNull (c.TabBar, "TabBar"); - Assert.Null (c.ViewControllers, "ViewControllers"); + Assert.That (c.SelectedViewController, Is.Null, "SelectedViewController"); + Assert.That (c.ShouldSelectViewController, Is.Null, "ShouldSelectViewController"); + Assert.That (c.TabBar, Is.Not.Null, "TabBar"); + Assert.That (c.ViewControllers, Is.Null, "ViewControllers"); } [Test] diff --git a/tests/monotouch-test/UIKit/TabBarTest.cs b/tests/monotouch-test/UIKit/TabBarTest.cs index bef1c6990d6d..83b42f519041 100644 --- a/tests/monotouch-test/UIKit/TabBarTest.cs +++ b/tests/monotouch-test/UIKit/TabBarTest.cs @@ -27,15 +27,15 @@ public void SelectedItem () { using (UITabBarItem item = new UITabBarItem ()) using (UITabBar tb = new UITabBar ()) { - Assert.Null (tb.SelectedItem, "1a"); + Assert.That (tb.SelectedItem, Is.Null, "1a"); tb.SelectedItem = item; // setter did not work because 'item' is not in Items - Assert.Null (tb.SelectedItem, "2a"); - Assert.Null (tb.Items, "2b"); + Assert.That (tb.SelectedItem, Is.Null, "2a"); + Assert.That (tb.Items, Is.Null, "2b"); tb.SelectedItem = null; - Assert.Null (tb.SelectedItem, "3a"); + Assert.That (tb.SelectedItem, Is.Null, "3a"); } } @@ -44,18 +44,18 @@ public void Items () { using (UITabBarItem item = new UITabBarItem ()) using (UITabBar tb = new UITabBar ()) { - Assert.Null (tb.Items, "1a"); - Assert.Null (tb.SelectedItem, "1b"); + Assert.That (tb.Items, Is.Null, "1a"); + Assert.That (tb.SelectedItem, Is.Null, "1b"); tb.Items = new UITabBarItem [] { item }; - Assert.NotNull (tb.Items, "2a"); + Assert.That (tb.Items, Is.Not.Null, "2a"); tb.SelectedItem = item; - Assert.NotNull (tb.SelectedItem, "2b"); + Assert.That (tb.SelectedItem, Is.Not.Null, "2b"); tb.Items = null; - Assert.Null (tb.Items, "3a"); + Assert.That (tb.Items, Is.Null, "3a"); // Interaction between Items and SelectedItems -> backing fields! - Assert.Null (tb.SelectedItem, "3b"); + Assert.That (tb.SelectedItem, Is.Null, "3b"); } } @@ -65,16 +65,16 @@ public void Customizing () { using (UITabBarItem item = new UITabBarItem ()) using (UITabBar tb = new UITabBar ()) { - Assert.False (tb.IsCustomizing, "IsCustomizing-1"); + Assert.That (tb.IsCustomizing, Is.False, "IsCustomizing-1"); tb.BeginCustomizingItems (new UITabBarItem [] { item }); - Assert.True (tb.IsCustomizing, "IsCustomizing-2"); - Assert.False (tb.EndCustomizing (false), "End-1"); + Assert.That (tb.IsCustomizing, Is.True, "IsCustomizing-2"); + Assert.That (tb.EndCustomizing (false), Is.False, "End-1"); tb.BeginCustomizingItems (null); - Assert.False (tb.EndCustomizing (false), "End-2"); + Assert.That (tb.EndCustomizing (false), Is.False, "End-2"); - Assert.False (tb.IsCustomizing, "IsCustomizing-3"); + Assert.That (tb.IsCustomizing, Is.False, "IsCustomizing-3"); } } #endif @@ -84,13 +84,13 @@ public void BackgroundImage () { using (UIImage i = new UIImage ()) using (UITabBar tb = new UITabBar ()) { - Assert.Null (tb.BackgroundImage, "1"); + Assert.That (tb.BackgroundImage, Is.Null, "1"); tb.BackgroundImage = i; - Assert.NotNull (tb.BackgroundImage, "2"); + Assert.That (tb.BackgroundImage, Is.Not.Null, "2"); tb.BackgroundImage = null; - Assert.Null (tb.BackgroundImage, "3"); + Assert.That (tb.BackgroundImage, Is.Null, "3"); } } @@ -99,13 +99,13 @@ public void SelectionIndicatorImage () { using (UIImage i = new UIImage ()) using (UITabBar tb = new UITabBar ()) { - Assert.Null (tb.SelectionIndicatorImage, "1"); + Assert.That (tb.SelectionIndicatorImage, Is.Null, "1"); tb.SelectionIndicatorImage = i; - Assert.NotNull (tb.SelectionIndicatorImage, "2"); + Assert.That (tb.SelectionIndicatorImage, Is.Not.Null, "2"); tb.SelectionIndicatorImage = null; - Assert.Null (tb.SelectionIndicatorImage, "3"); + Assert.That (tb.SelectionIndicatorImage, Is.Null, "3"); } } @@ -115,9 +115,9 @@ public void TintColor () using (UITabBar tb = new UITabBar ()) { // TintColor is inherited in iOS7 so it won't be null by default if (TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false)) - Assert.NotNull (tb.TintColor, "1"); + Assert.That (tb.TintColor, Is.Not.Null, "1"); else - Assert.Null (tb.TintColor, "1"); + Assert.That (tb.TintColor, Is.Null, "1"); tb.TintColor = UIColor.White; Assert.That (tb.TintColor, Is.EqualTo (UIColor.White), "2"); @@ -125,11 +125,11 @@ public void TintColor () tb.TintColor = null; if (TestRuntime.IsTVOS) { // we only care that setting `null` gives us back some default OS value - Assert.NotNull (tb.TintColor, "3"); + Assert.That (tb.TintColor, Is.Not.Null, "3"); } else if (TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false)) { Assert.That (tb.TintColor, Is.Not.EqualTo (UIColor.White), "3"); } else - Assert.Null (tb.TintColor, "3"); + Assert.That (tb.TintColor, Is.Null, "3"); } } @@ -138,16 +138,16 @@ public void TintColor () public void SelectedImageTintColor () { using (UITabBar tb = new UITabBar ()) { - Assert.Null (tb.SelectedImageTintColor, "1"); + Assert.That (tb.SelectedImageTintColor, Is.Null, "1"); tb.SelectedImageTintColor = UIColor.Black; if (!TestRuntime.CheckSystemVersion (ApplePlatform.iOS, 7, 1)) { // before 7.1 the tintColor would have been accepted - Assert.NotNull (tb.SelectedImageTintColor, "2"); + Assert.That (tb.SelectedImageTintColor, Is.Not.Null, "2"); tb.SelectedImageTintColor = null; } - Assert.Null (tb.SelectedImageTintColor, "3"); + Assert.That (tb.SelectedImageTintColor, Is.Null, "3"); } } #endif diff --git a/tests/monotouch-test/UIKit/TableViewControllerTest.cs b/tests/monotouch-test/UIKit/TableViewControllerTest.cs index 3c88a06076ca..052b949b3a0e 100644 --- a/tests/monotouch-test/UIKit/TableViewControllerTest.cs +++ b/tests/monotouch-test/UIKit/TableViewControllerTest.cs @@ -24,11 +24,11 @@ public void RefreshControl_18744 () { using (var rc = new UIRefreshControl ()) using (var tvc = new UITableViewController ()) { - Assert.Null (tvc.RefreshControl, "default"); + Assert.That (tvc.RefreshControl, Is.Null, "default"); tvc.RefreshControl = rc; - Assert.AreSame (tvc.RefreshControl, rc, "same"); + Assert.That (rc, Is.SameAs (tvc.RefreshControl), "same"); tvc.RefreshControl = null; - Assert.Null (tvc.RefreshControl, "nullable"); + Assert.That (tvc.RefreshControl, Is.Null, "nullable"); } } #endif // !__TVOS__ diff --git a/tests/monotouch-test/UIKit/TarBarItemTest.cs b/tests/monotouch-test/UIKit/TarBarItemTest.cs index ba7d632a7e78..f4f5a41c0908 100644 --- a/tests/monotouch-test/UIKit/TarBarItemTest.cs +++ b/tests/monotouch-test/UIKit/TarBarItemTest.cs @@ -22,16 +22,16 @@ public class TabBarItemTest { public void Ctor_Defaults () { using (UITabBarItem tbi = new UITabBarItem ()) { - Assert.Null (tbi.BadgeValue, "BadgeValue"); - Assert.True (tbi.Enabled, "Enabled"); + Assert.That (tbi.BadgeValue, Is.Null, "BadgeValue"); + Assert.That (tbi.Enabled, Is.True, "Enabled"); #if !__TVOS__ - Assert.Null (tbi.FinishedSelectedImage, "FinishedSelectedImage"); - Assert.Null (tbi.FinishedUnselectedImage, "FinishedUnselectedImage"); + Assert.That (tbi.FinishedSelectedImage, Is.Null, "FinishedSelectedImage"); + Assert.That (tbi.FinishedUnselectedImage, Is.Null, "FinishedUnselectedImage"); #endif - Assert.Null (tbi.Image, "Image"); + Assert.That (tbi.Image, Is.Null, "Image"); Assert.That (tbi.ImageInsets, Is.EqualTo (UIEdgeInsets.Zero), "ImageInsets"); Assert.That (tbi.Tag, Is.EqualTo ((nint) 0), "Tag"); - Assert.Null (tbi.Title, "Title"); + Assert.That (tbi.Title, Is.Null, "Title"); Assert.That (tbi.TitlePositionAdjustment.Horizontal, Is.EqualTo ((nfloat) 0f), "TitlePositionAdjustment.Horizontal"); Assert.That (tbi.TitlePositionAdjustment.Vertical, Is.EqualTo ((nfloat) 0f), "TitlePositionAdjustment.Vertical"); } @@ -42,16 +42,16 @@ public void Ctor_2 () { Assert.Multiple (() => { using (UITabBarItem tbi = new UITabBarItem (UITabBarSystemItem.Bookmarks, nint.MaxValue)) { - Assert.Null (tbi.BadgeValue, "BadgeValue"); - Assert.True (tbi.Enabled, "Enabled"); + Assert.That (tbi.BadgeValue, Is.Null, "BadgeValue"); + Assert.That (tbi.Enabled, Is.True, "Enabled"); #if !__TVOS__ - Assert.Null (tbi.FinishedSelectedImage, "FinishedSelectedImage"); - Assert.Null (tbi.FinishedUnselectedImage, "FinishedUnselectedImage"); + Assert.That (tbi.FinishedSelectedImage, Is.Null, "FinishedSelectedImage"); + Assert.That (tbi.FinishedUnselectedImage, Is.Null, "FinishedUnselectedImage"); #endif if (TestRuntime.CheckXcodeVersion (16, 0)) { - Assert.NotNull (tbi.Image, "Image"); + Assert.That (tbi.Image, Is.Not.Null, "Image"); } else { - Assert.Null (tbi.Image, "Image"); + Assert.That (tbi.Image, Is.Null, "Image"); } Assert.That (tbi.ImageInsets, Is.EqualTo (UIEdgeInsets.Zero), "ImageInsets"); Assert.That (tbi.Tag, Is.EqualTo (nint.MaxValue), "Tag"); @@ -67,13 +67,13 @@ public void Ctor_3 () { using (UIImage img = new UIImage ()) using (UITabBarItem tbi = new UITabBarItem ("title", img, nint.MinValue)) { - Assert.Null (tbi.BadgeValue, "BadgeValue"); - Assert.True (tbi.Enabled, "Enabled"); + Assert.That (tbi.BadgeValue, Is.Null, "BadgeValue"); + Assert.That (tbi.Enabled, Is.True, "Enabled"); #if !__TVOS__ - Assert.Null (tbi.FinishedSelectedImage, "FinishedSelectedImage"); - Assert.Null (tbi.FinishedUnselectedImage, "FinishedUnselectedImage"); + Assert.That (tbi.FinishedSelectedImage, Is.Null, "FinishedSelectedImage"); + Assert.That (tbi.FinishedUnselectedImage, Is.Null, "FinishedUnselectedImage"); #endif - Assert.AreSame (tbi.Image, img, "Image"); + Assert.That (img, Is.SameAs (tbi.Image), "Image"); Assert.That (tbi.ImageInsets, Is.EqualTo (UIEdgeInsets.Zero), "ImageInsets"); Assert.That (tbi.Tag, Is.EqualTo (nint.MinValue), "Tag"); Assert.That (tbi.Title, Is.EqualTo ("title"), "Title"); @@ -87,28 +87,28 @@ public void Ctor_3a_Null () { using (UIImage img = new UIImage ()) { using (UITabBarItem tbi1 = new UITabBarItem (null, img, nint.MinValue)) { - Assert.Null (tbi1.Title, "Title-1a"); - Assert.AreSame (tbi1.Image, img, "Image-1a"); + Assert.That (tbi1.Title, Is.Null, "Title-1a"); + Assert.That (img, Is.SameAs (tbi1.Image), "Image-1a"); tbi1.Title = "title"; tbi1.Image = null; Assert.That (tbi1.Title, Is.EqualTo ("title"), "Title-1b"); - Assert.IsNull (tbi1.Image, "Image-1b"); + Assert.That (tbi1.Image, Is.Null, "Image-1b"); } using (UITabBarItem tbi2 = new UITabBarItem ("title", null, nint.MaxValue)) { Assert.That (tbi2.Title, Is.EqualTo ("title"), "Title-2a"); - Assert.Null (tbi2.Image, "Image-2a"); + Assert.That (tbi2.Image, Is.Null, "Image-2a"); tbi2.Title = null; tbi2.Image = img; - Assert.Null (tbi2.Title, "Title-2b"); - Assert.AreSame (tbi2.Image, img, "Image-2b"); + Assert.That (tbi2.Title, Is.Null, "Title-2b"); + Assert.That (img, Is.SameAs (tbi2.Image), "Image-2b"); } using (UITabBarItem tbi3 = new UITabBarItem (null, null, 0)) { - Assert.Null (tbi3.Title, "Title-3a"); - Assert.Null (tbi3.Image, "Image-3a"); + Assert.That (tbi3.Title, Is.Null, "Title-3a"); + Assert.That (tbi3.Image, Is.Null, "Image-3a"); tbi3.Title = "title"; tbi3.Image = img; Assert.That (tbi3.Title, Is.EqualTo ("title"), "Title-3b"); - Assert.AreSame (tbi3.Image, img, "Image-3b"); + Assert.That (img, Is.SameAs (tbi3.Image), "Image-3b"); } } } @@ -120,19 +120,19 @@ public void Ctor_3b_Null () using (UIImage img = new UIImage ()) { using (UITabBarItem tbi1 = new UITabBarItem (null, null, null)) { - Assert.Null (tbi1.Title, "Title-1a"); - Assert.Null (tbi1.Image, "Image-1a"); - Assert.Null (tbi1.SelectedImage, "SelectedImage-1a"); + Assert.That (tbi1.Title, Is.Null, "Title-1a"); + Assert.That (tbi1.Image, Is.Null, "Image-1a"); + Assert.That (tbi1.SelectedImage, Is.Null, "SelectedImage-1a"); } using (UITabBarItem tbi2 = new UITabBarItem ("title", img, null)) { Assert.That (tbi2.Title, Is.EqualTo ("title"), "Title-2a"); - Assert.AreSame (tbi2.Image, img, "Image-2a"); + Assert.That (img, Is.SameAs (tbi2.Image), "Image-2a"); // if not supplied Image is reused - Assert.AreSame (tbi2.SelectedImage, img, "SelectedImage-2a"); + Assert.That (img, Is.SameAs (tbi2.SelectedImage), "SelectedImage-2a"); } using (UITabBarItem tbi3 = new UITabBarItem (null, null, img)) { - Assert.Null (tbi3.Title, "Title-3a"); - Assert.Null (tbi3.Image, "Image-3a"); + Assert.That (tbi3.Title, Is.Null, "Title-3a"); + Assert.That (tbi3.Image, Is.Null, "Image-3a"); // looks like a select-only image is not something allowed on 7.1 var hasSelectedImage = true; @@ -141,9 +141,9 @@ public void Ctor_3b_Null () hasSelectedImage = false; #endif if (hasSelectedImage) - Assert.Null (tbi3.SelectedImage, "SelectedImage-3a"); + Assert.That (tbi3.SelectedImage, Is.Null, "SelectedImage-3a"); else - Assert.AreSame (tbi3.SelectedImage, img, "SelectedImage-3a"); + Assert.That (img, Is.SameAs (tbi3.SelectedImage), "SelectedImage-3a"); } } } @@ -155,15 +155,15 @@ public void SelectedImage_7a () using (UIImage i1 = new UIImage ()) using (UITabBarItem tbi = new UITabBarItem ("title", i1, null)) { - Assert.AreSame (i1, tbi.Image, "Image"); - Assert.AreSame (i1, tbi.SelectedImage, "SelectedImage"); + Assert.That (tbi.Image, Is.SameAs (i1), "Image"); + Assert.That (tbi.SelectedImage, Is.SameAs (i1), "SelectedImage"); #if !__TVOS__ - Assert.Null (tbi.FinishedSelectedImage, "FinishedSelectedImage"); - Assert.Null (tbi.FinishedUnselectedImage, "FinishedSelectedImage"); + Assert.That (tbi.FinishedSelectedImage, Is.Null, "FinishedSelectedImage"); + Assert.That (tbi.FinishedUnselectedImage, Is.Null, "FinishedSelectedImage"); #endif // null does a reset, in this case i1 can be reused tbi.SelectedImage = null; - Assert.AreSame (i1, tbi.SelectedImage, "SelectedImage2"); + Assert.That (tbi.SelectedImage, Is.SameAs (i1), "SelectedImage2"); } } @@ -175,15 +175,15 @@ public void SelectedImage_7b () using (UIImage i1 = new UIImage ()) using (UIImage i2 = new UIImage ()) using (UITabBarItem tbi = new UITabBarItem ("title", i1, i2)) { - Assert.AreSame (i1, tbi.Image, "Image"); - Assert.AreSame (i2, tbi.SelectedImage, "SelectedImage"); + Assert.That (tbi.Image, Is.SameAs (i1), "Image"); + Assert.That (tbi.SelectedImage, Is.SameAs (i2), "SelectedImage"); #if !__TVOS__ - Assert.Null (tbi.FinishedSelectedImage, "FinishedSelectedImage"); - Assert.Null (tbi.FinishedUnselectedImage, "FinishedSelectedImage"); + Assert.That (tbi.FinishedSelectedImage, Is.Null, "FinishedSelectedImage"); + Assert.That (tbi.FinishedUnselectedImage, Is.Null, "FinishedSelectedImage"); #endif tbi.SelectedImage = null; // null does a reset, in this case i2 is removed and i1 gets used - Assert.AreSame (i1, tbi.SelectedImage, "SelectedImage2"); + Assert.That (tbi.SelectedImage, Is.SameAs (i1), "SelectedImage2"); } } } diff --git a/tests/monotouch-test/UIKit/TextAttachmentTest.cs b/tests/monotouch-test/UIKit/TextAttachmentTest.cs index cf71035f9b7d..df0367efc7fd 100644 --- a/tests/monotouch-test/UIKit/TextAttachmentTest.cs +++ b/tests/monotouch-test/UIKit/TextAttachmentTest.cs @@ -24,11 +24,11 @@ public void CtorNull () TestRuntime.AssertSystemVersion (ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false); using (var ta = new NSTextAttachment (null, null)) { - Assert.IsTrue (ta.Bounds.IsEmpty, "Bounds"); - Assert.Null (ta.Contents, "Contents"); - Assert.Null (ta.FileType, "FileType"); - Assert.Null (ta.FileWrapper, "FileWrapper"); - Assert.Null (ta.Image, "Image"); + Assert.That (ta.Bounds.IsEmpty, Is.True, "Bounds"); + Assert.That (ta.Contents, Is.Null, "Contents"); + Assert.That (ta.FileType, Is.Null, "FileType"); + Assert.That (ta.FileWrapper, Is.Null, "FileWrapper"); + Assert.That (ta.Image, Is.Null, "Image"); } } } diff --git a/tests/monotouch-test/UIKit/TextContainerTest.cs b/tests/monotouch-test/UIKit/TextContainerTest.cs index c905704dac61..11337712abd0 100644 --- a/tests/monotouch-test/UIKit/TextContainerTest.cs +++ b/tests/monotouch-test/UIKit/TextContainerTest.cs @@ -24,7 +24,7 @@ public void Layout () TestRuntime.AssertSystemVersion (ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false); using (var tc = new NSTextContainer ()) { - Assert.Null (tc.LayoutManager, "LayoutManager"); + Assert.That (tc.LayoutManager, Is.Null, "LayoutManager"); } } } diff --git a/tests/monotouch-test/UIKit/TextFieldTest.cs b/tests/monotouch-test/UIKit/TextFieldTest.cs index 7dc62eccb94c..bfb593c72c22 100644 --- a/tests/monotouch-test/UIKit/TextFieldTest.cs +++ b/tests/monotouch-test/UIKit/TextFieldTest.cs @@ -38,9 +38,9 @@ public void EmptySelection () { using (var tf = new UITextField ()) { if (TestRuntime.CheckXcodeVersion (9, 0)) { - Assert.IsNotNull (tf.SelectedTextRange, "SelectedTextRange 1"); + Assert.That (tf.SelectedTextRange, Is.Not.Null, "SelectedTextRange 1"); } else { - Assert.IsNull (tf.SelectedTextRange, "SelectedTextRange"); + Assert.That (tf.SelectedTextRange, Is.Null, "SelectedTextRange"); } if (TestRuntime.CheckXcodeVersion (13, 0)) { #if !__TVOS__ @@ -57,7 +57,7 @@ public void EmptySelection () else Assert.That (tf.TypingAttributes, Is.Empty, "default"); } else { - Assert.IsNull (tf.TypingAttributes, "default"); + Assert.That (tf.TypingAttributes, Is.Null, "default"); } // ^ calling TypingAttributes does not crash like UITextView does, it simply returns null tf.TypingAttributes = new NSDictionary (); @@ -77,7 +77,7 @@ public void EmptySelection () else Assert.That (tf.TypingAttributes, Is.Empty, "empty"); } else { - Assert.IsNull (tf.TypingAttributes, "empty not xcode 11"); + Assert.That (tf.TypingAttributes, Is.Null, "empty not xcode 11"); } // and it stays null, even if assigned, since there's not selection } @@ -88,9 +88,9 @@ public void LeftRight () { // https://bugzilla.xamarin.com/show_bug.cgi?id=15004 using (UITextField tf = new UITextField ()) { - Assert.IsNull (tf.LeftView, "LeftView"); + Assert.That (tf.LeftView, Is.Null, "LeftView"); tf.LeftView = null; - Assert.IsNull (tf.RightView, "RightView"); + Assert.That (tf.RightView, Is.Null, "RightView"); tf.RightView = null; } } diff --git a/tests/monotouch-test/UIKit/TextViewTest.cs b/tests/monotouch-test/UIKit/TextViewTest.cs index f74c6be945dd..81013571e160 100644 --- a/tests/monotouch-test/UIKit/TextViewTest.cs +++ b/tests/monotouch-test/UIKit/TextViewTest.cs @@ -28,18 +28,18 @@ public void EmptySelection () using (UITextView tv = new UITextView ()) { Assert.That (tv.SelectedRange.Length, Is.EqualTo ((nint) 0), "SelectedRange"); #if XAMCORE_5_0 - Assert.IsNotNull (tv.TypingAttributes, "default"); + Assert.That (tv.TypingAttributes, Is.Not.Null, "default"); tv.TypingAttributes = new NSDictionary (); - Assert.IsNotNull (tv.TypingAttributes, "assigned"); + Assert.That (tv.TypingAttributes, Is.Not.Null, "assigned"); #else - Assert.IsNull (tv.TypingAttributes, "default"); + Assert.That (tv.TypingAttributes, Is.Null, "default"); // ^ without a [PreSnippet] attribute this would crash like: // 7 monotouchtest 0x00006340 mono_sigill_signal_handler + 64 // 8 WebKit 0x06b6afa5 -[WebView(WebPrivate) styleAtSelectionStart] + 53 // 9 UIKit 0x028daa8a -[UIWebDocumentView typingAttributes] + 50 // 10 UIKit 0x0285de57 -[UITextView typingAttributes] + 42 tv.TypingAttributes = new NSDictionary (); - // Assert.IsNotNull (tv.TypingAttributes, "assigned"); + // Assert.That (tv.TypingAttributes, Is.Not.Null, "assigned"); // ^ this would still crash #endif } @@ -51,9 +51,9 @@ public void EmptySelection2 () { using (UITextView tv = new UITextView ()) { Assert.That (tv.SelectedRange.Length, Is.EqualTo ((nint) 0), "SelectedRange"); - Assert.IsNotNull (tv.TypingAttributes2, "default"); + Assert.That (tv.TypingAttributes2, Is.Not.Null, "default"); tv.TypingAttributes = new NSDictionary (); - Assert.IsNotNull (tv.TypingAttributes2, "assigned"); + Assert.That (tv.TypingAttributes2, Is.Not.Null, "assigned"); } } #endif // !XAMCORE_6_0 @@ -65,7 +65,7 @@ public void NonEmptySelection () tv.Text = "Bla bla bla"; tv.SelectAll (tv); Assert.That (tv.SelectedRange.Length, Is.Not.EqualTo (0), "SelectedRange"); - Assert.IsNotNull (tv.TypingAttributes, "TypingAttributes"); + Assert.That (tv.TypingAttributes, Is.Not.Null, "TypingAttributes"); } } @@ -77,21 +77,21 @@ public void LayoutManager () using (UITextView tv = new UITextView ()) { var lm = tv.LayoutManager; - Assert.True (lm.AllowsNonContiguousLayout, "AllowsNonContiguousLayout"); + Assert.That (lm.AllowsNonContiguousLayout, Is.True, "AllowsNonContiguousLayout"); Assert.That (lm.ExtraLineFragmentRect.IsEmpty, Is.True.Or.False, "ExtraLineFragmentRect"); - Assert.NotNull (lm.ExtraLineFragmentTextContainer, "ExtraLineFragmentTextContainer"); + Assert.That (lm.ExtraLineFragmentTextContainer, Is.Not.Null, "ExtraLineFragmentTextContainer"); Assert.That (lm.ExtraLineFragmentUsedRect.IsEmpty, Is.True.Or.False, "ExtraLineFragmentUsedRect"); Assert.That (lm.FirstUnlaidCharacterIndex, Is.EqualTo ((nuint) 0), "FirstUnlaidCharacterIndex"); Assert.That (lm.FirstUnlaidGlyphIndex, Is.EqualTo ((nuint) 0), "FirstUnlaidGlyphIndex"); - Assert.False (lm.HasNonContiguousLayout, "HasNonContiguousLayout"); + Assert.That (lm.HasNonContiguousLayout, Is.False, "HasNonContiguousLayout"); #if !__MACCATALYST__ Assert.That (lm.HyphenationFactor, Is.EqualTo ((nfloat) 0), "HyphenationFactor"); #endif Assert.That (lm.NumberOfGlyphs, Is.EqualTo ((nuint) 0), "NumberOfGlyphs"); - Assert.False (lm.ShowsControlCharacters, "ShowsControlCharacters"); - Assert.False (lm.ShowsInvisibleCharacters, "ShowsInvisibleCharacters"); - Assert.NotNull (lm.TextStorage, "TextStorage"); - Assert.True (lm.UsesFontLeading, "UsesFontLeading"); + Assert.That (lm.ShowsControlCharacters, Is.False, "ShowsControlCharacters"); + Assert.That (lm.ShowsInvisibleCharacters, Is.False, "ShowsInvisibleCharacters"); + Assert.That (lm.TextStorage, Is.Not.Null, "TextStorage"); + Assert.That (lm.UsesFontLeading, Is.True, "UsesFontLeading"); } } diff --git a/tests/monotouch-test/UIKit/ToolbarTest.cs b/tests/monotouch-test/UIKit/ToolbarTest.cs index 5bb2a795976c..9912f33a58d1 100644 --- a/tests/monotouch-test/UIKit/ToolbarTest.cs +++ b/tests/monotouch-test/UIKit/ToolbarTest.cs @@ -25,7 +25,7 @@ public void InitWithFrame () public void BackgroundImage () { using (UIToolbar tb = new UIToolbar ()) { - Assert.Null (tb.GetBackgroundImage (UIToolbarPosition.Any, UIBarMetrics.Default), "Get"); + Assert.That (tb.GetBackgroundImage (UIToolbarPosition.Any, UIBarMetrics.Default), Is.Null, "Get"); tb.SetBackgroundImage (null, UIToolbarPosition.Any, UIBarMetrics.Default); } } diff --git a/tests/monotouch-test/UIKit/UIAlertControllerTest.cs b/tests/monotouch-test/UIKit/UIAlertControllerTest.cs index 1d461611c4ff..c5a837d362ee 100644 --- a/tests/monotouch-test/UIKit/UIAlertControllerTest.cs +++ b/tests/monotouch-test/UIKit/UIAlertControllerTest.cs @@ -25,7 +25,7 @@ public void InitWithNibNameTest () TestRuntime.AssertSystemVersion (ApplePlatform.iOS, 8, 0, throwIfOtherPlatform: false); UIAlertController ctrl = new UIAlertController (null, null); - Assert.NotNull (ctrl, "UIAlertController ctor(String, NSBundle)"); + Assert.That (ctrl, Is.Not.Null, "UIAlertController ctor(String, NSBundle)"); ctrl.AddAction (new UIAlertAction ()); ctrl.AddAction (new UIAlertAction ()); diff --git a/tests/monotouch-test/UIKit/UIContentSizeCategoryTest.cs b/tests/monotouch-test/UIKit/UIContentSizeCategoryTest.cs index 52af97cde3dc..3512a7ef36d1 100644 --- a/tests/monotouch-test/UIKit/UIContentSizeCategoryTest.cs +++ b/tests/monotouch-test/UIKit/UIContentSizeCategoryTest.cs @@ -27,9 +27,9 @@ public void Setup () public void IsAccessibilityCategory () { var isAccessible = UIContentSizeCategory.AccessibilityMedium.IsAccessibilityCategory (); - Assert.IsTrue (isAccessible, "AccessibilityMedium"); + Assert.That (isAccessible, Is.True, "AccessibilityMedium"); isAccessible = UIContentSizeCategory.Medium.IsAccessibilityCategory (); - Assert.IsFalse (isAccessible, "Medium"); + Assert.That (isAccessible, Is.False, "Medium"); } [Test] @@ -37,7 +37,7 @@ public void Compare () { var small = UIContentSizeCategory.Small; var large = UIContentSizeCategory.Large; - Assert.True (UIContentSizeCategoryExtensions.Compare (small, large) == NSComparisonResult.Ascending, "small < large"); + Assert.That (UIContentSizeCategoryExtensions.Compare (small, large), Is.EqualTo (NSComparisonResult.Ascending), "small < large"); Assert.Throws (() => UIContentSizeCategoryExtensions.Compare ((UIContentSizeCategory) 31415, large)); Assert.Throws (() => UIContentSizeCategoryExtensions.Compare (small, (UIContentSizeCategory) 271828)); Assert.Throws (() => ((UIContentSizeCategory) 1234).IsAccessibilityCategory ()); @@ -49,9 +49,9 @@ public void GetPreferredContentSizeCategoryTest () var sizeNSString = UIApplication.SharedApplication.PreferredContentSizeCategory; var sizeEnum = UIContentSizeCategoryExtensions.GetValue (sizeNSString); var size = UIApplication.SharedApplication.GetPreferredContentSizeCategory (); - Assert.AreEqual (sizeEnum, size, "String"); + Assert.That (size, Is.EqualTo (sizeEnum), "String"); var sizeReverse = size.GetConstant (); - Assert.AreEqual (sizeNSString, sizeReverse, "NSString"); + Assert.That (sizeReverse, Is.EqualTo (sizeNSString), "NSString"); } } } diff --git a/tests/monotouch-test/UIKit/UIDocumentTest.cs b/tests/monotouch-test/UIKit/UIDocumentTest.cs index 88b74df4194f..be2e2ae6f928 100644 --- a/tests/monotouch-test/UIKit/UIDocumentTest.cs +++ b/tests/monotouch-test/UIKit/UIDocumentTest.cs @@ -77,7 +77,7 @@ public void Save () void OperationHandler (bool success) { - Assert.True (success); + Assert.That (success, Is.True); } [Test] diff --git a/tests/monotouch-test/UIKit/UIPasteConfigurationSupportingTest.cs b/tests/monotouch-test/UIKit/UIPasteConfigurationSupportingTest.cs index 41a8277aa384..00712f80ea6f 100644 --- a/tests/monotouch-test/UIKit/UIPasteConfigurationSupportingTest.cs +++ b/tests/monotouch-test/UIKit/UIPasteConfigurationSupportingTest.cs @@ -53,7 +53,7 @@ class ViewControllerPoker : UIViewController { public override void Paste (NSItemProvider [] itemProviders) { - Assert.IsTrue (itemProviders [0].CanLoadObject (typeof (UIImage))); + Assert.That (itemProviders [0].CanLoadObject (typeof (UIImage)), Is.True); } } @@ -61,7 +61,7 @@ class ViewPoker : UIView { public override void Paste (NSItemProvider [] itemProviders) { - Assert.IsTrue (itemProviders [0].CanLoadObject (typeof (UIImage))); + Assert.That (itemProviders [0].CanLoadObject (typeof (UIImage)), Is.True); } } @@ -69,7 +69,7 @@ class NodePoker : SKNode { public override void Paste (NSItemProvider [] itemProviders) { - Assert.IsTrue (itemProviders [0].CanLoadObject (typeof (UIImage))); + Assert.That (itemProviders [0].CanLoadObject (typeof (UIImage)), Is.True); } } } diff --git a/tests/monotouch-test/UIKit/UIPointerAccessory.cs b/tests/monotouch-test/UIKit/UIPointerAccessory.cs index 18b95fc79939..e1c0b0093849 100644 --- a/tests/monotouch-test/UIKit/UIPointerAccessory.cs +++ b/tests/monotouch-test/UIKit/UIPointerAccessory.cs @@ -27,9 +27,9 @@ public void UIPointerAccessoryPositionTopTest () { UIPointerAccessory acc = null; Assert.DoesNotThrow (() => acc = UIPointerAccessory.CreateArrow (UIPointerAccessoryPosition.Top), "Should not throw"); - Assert.NotNull (acc, $"{nameof (acc)} was null"); - Assert.AreEqual (acc.Position.Offset, UIPointerAccessoryPosition.Top.Offset, "Offset"); - Assert.AreEqual (acc.Position.Angle, UIPointerAccessoryPosition.Top.Angle, "Angle"); + Assert.That (acc, Is.Not.Null, $"{nameof (acc)} was null"); + Assert.That (UIPointerAccessoryPosition.Top.Offset, Is.EqualTo (acc.Position.Offset), "Offset"); + Assert.That (UIPointerAccessoryPosition.Top.Angle, Is.EqualTo (acc.Position.Angle), "Angle"); } [Test] @@ -37,9 +37,9 @@ public void UIPointerAccessoryPositionTopRightTest () { UIPointerAccessory acc = null; Assert.DoesNotThrow (() => acc = UIPointerAccessory.CreateArrow (UIPointerAccessoryPosition.TopRight), "Should not throw"); - Assert.NotNull (acc, $"{nameof (acc)} was null"); - Assert.AreEqual (acc.Position.Offset, UIPointerAccessoryPosition.TopRight.Offset, "Offset"); - Assert.AreEqual (acc.Position.Angle, UIPointerAccessoryPosition.TopRight.Angle, "Angle"); + Assert.That (acc, Is.Not.Null, $"{nameof (acc)} was null"); + Assert.That (UIPointerAccessoryPosition.TopRight.Offset, Is.EqualTo (acc.Position.Offset), "Offset"); + Assert.That (UIPointerAccessoryPosition.TopRight.Angle, Is.EqualTo (acc.Position.Angle), "Angle"); } [Test] @@ -47,9 +47,9 @@ public void UIPointerAccessoryPositionRightTest () { UIPointerAccessory acc = null; Assert.DoesNotThrow (() => acc = UIPointerAccessory.CreateArrow (UIPointerAccessoryPosition.Right), "Should not throw"); - Assert.NotNull (acc, $"{nameof (acc)} was null"); - Assert.AreEqual (acc.Position.Offset, UIPointerAccessoryPosition.Right.Offset, "Offset"); - Assert.AreEqual (acc.Position.Angle, UIPointerAccessoryPosition.Right.Angle, "Angle"); + Assert.That (acc, Is.Not.Null, $"{nameof (acc)} was null"); + Assert.That (UIPointerAccessoryPosition.Right.Offset, Is.EqualTo (acc.Position.Offset), "Offset"); + Assert.That (UIPointerAccessoryPosition.Right.Angle, Is.EqualTo (acc.Position.Angle), "Angle"); } [Test] @@ -57,9 +57,9 @@ public void UIPointerAccessoryPositionBottomRightTest () { UIPointerAccessory acc = null; Assert.DoesNotThrow (() => acc = UIPointerAccessory.CreateArrow (UIPointerAccessoryPosition.BottomRight), "Should not throw"); - Assert.NotNull (acc, $"{nameof (acc)} was null"); - Assert.AreEqual (acc.Position.Offset, UIPointerAccessoryPosition.BottomRight.Offset, "Offset"); - Assert.AreEqual (acc.Position.Angle, UIPointerAccessoryPosition.BottomRight.Angle, "Angle"); + Assert.That (acc, Is.Not.Null, $"{nameof (acc)} was null"); + Assert.That (UIPointerAccessoryPosition.BottomRight.Offset, Is.EqualTo (acc.Position.Offset), "Offset"); + Assert.That (UIPointerAccessoryPosition.BottomRight.Angle, Is.EqualTo (acc.Position.Angle), "Angle"); } [Test] @@ -67,9 +67,9 @@ public void UIPointerAccessoryPositionBottomTest () { UIPointerAccessory acc = null; Assert.DoesNotThrow (() => acc = UIPointerAccessory.CreateArrow (UIPointerAccessoryPosition.Bottom), "Should not throw"); - Assert.NotNull (acc, $"{nameof (acc)} was null"); - Assert.AreEqual (acc.Position.Offset, UIPointerAccessoryPosition.Bottom.Offset, "Offset"); - Assert.AreEqual (acc.Position.Angle, UIPointerAccessoryPosition.Bottom.Angle, "Angle"); + Assert.That (acc, Is.Not.Null, $"{nameof (acc)} was null"); + Assert.That (UIPointerAccessoryPosition.Bottom.Offset, Is.EqualTo (acc.Position.Offset), "Offset"); + Assert.That (UIPointerAccessoryPosition.Bottom.Angle, Is.EqualTo (acc.Position.Angle), "Angle"); } [Test] @@ -77,9 +77,9 @@ public void UIPointerAccessoryPositionBottomLeftTest () { UIPointerAccessory acc = null; Assert.DoesNotThrow (() => acc = UIPointerAccessory.CreateArrow (UIPointerAccessoryPosition.BottomLeft), "Should not throw"); - Assert.NotNull (acc, $"{nameof (acc)} was null"); - Assert.AreEqual (acc.Position.Offset, UIPointerAccessoryPosition.BottomLeft.Offset, "Offset"); - Assert.AreEqual (acc.Position.Angle, UIPointerAccessoryPosition.BottomLeft.Angle, "Angle"); + Assert.That (acc, Is.Not.Null, $"{nameof (acc)} was null"); + Assert.That (UIPointerAccessoryPosition.BottomLeft.Offset, Is.EqualTo (acc.Position.Offset), "Offset"); + Assert.That (UIPointerAccessoryPosition.BottomLeft.Angle, Is.EqualTo (acc.Position.Angle), "Angle"); } [Test] @@ -87,9 +87,9 @@ public void UIPointerAccessoryPositionLeftTest () { UIPointerAccessory acc = null; Assert.DoesNotThrow (() => acc = UIPointerAccessory.CreateArrow (UIPointerAccessoryPosition.Left), "Should not throw"); - Assert.NotNull (acc, $"{nameof (acc)} was null"); - Assert.AreEqual (acc.Position.Offset, UIPointerAccessoryPosition.Left.Offset, "Offset"); - Assert.AreEqual (acc.Position.Angle, UIPointerAccessoryPosition.Left.Angle, "Angle"); + Assert.That (acc, Is.Not.Null, $"{nameof (acc)} was null"); + Assert.That (UIPointerAccessoryPosition.Left.Offset, Is.EqualTo (acc.Position.Offset), "Offset"); + Assert.That (UIPointerAccessoryPosition.Left.Angle, Is.EqualTo (acc.Position.Angle), "Angle"); } [Test] @@ -97,9 +97,9 @@ public void UIPointerAccessoryPositionTopLeftTest () { UIPointerAccessory acc = null; Assert.DoesNotThrow (() => acc = UIPointerAccessory.CreateArrow (UIPointerAccessoryPosition.TopLeft), "Should not throw"); - Assert.NotNull (acc, $"{nameof (acc)} was null"); - Assert.AreEqual (acc.Position.Offset, UIPointerAccessoryPosition.TopLeft.Offset, "Offset"); - Assert.AreEqual (acc.Position.Angle, UIPointerAccessoryPosition.TopLeft.Angle, "Angle"); + Assert.That (acc, Is.Not.Null, $"{nameof (acc)} was null"); + Assert.That (UIPointerAccessoryPosition.TopLeft.Offset, Is.EqualTo (acc.Position.Offset), "Offset"); + Assert.That (UIPointerAccessoryPosition.TopLeft.Angle, Is.EqualTo (acc.Position.Angle), "Angle"); } } } diff --git a/tests/monotouch-test/UIKit/UISearchControllerTest.cs b/tests/monotouch-test/UIKit/UISearchControllerTest.cs index e95fa4a9e3e7..bc696a21c9ff 100644 --- a/tests/monotouch-test/UIKit/UISearchControllerTest.cs +++ b/tests/monotouch-test/UIKit/UISearchControllerTest.cs @@ -25,10 +25,10 @@ public void InitWithNibNameTest () TestRuntime.AssertSystemVersion (ApplePlatform.iOS, 8, 0, throwIfOtherPlatform: false); UISearchController ctrl = new UISearchController (null, null); - Assert.NotNull (ctrl, "UISearchController ctor(String, NSBundle)"); + Assert.That (ctrl, Is.Not.Null, "UISearchController ctor(String, NSBundle)"); ctrl.Delegate = new UISearchControllerDelegate (); - Assert.NotNull (ctrl.Delegate, "UISearchController instance is not usable "); + Assert.That (ctrl.Delegate, Is.Not.Null, "UISearchController instance is not usable "); } } } diff --git a/tests/monotouch-test/UIKit/UISpringLoadedInteractionSupportingTest.cs b/tests/monotouch-test/UIKit/UISpringLoadedInteractionSupportingTest.cs index 32228ed2e231..cda621dc81de 100644 --- a/tests/monotouch-test/UIKit/UISpringLoadedInteractionSupportingTest.cs +++ b/tests/monotouch-test/UIKit/UISpringLoadedInteractionSupportingTest.cs @@ -32,7 +32,7 @@ public void UIAlertControllerSpringLoadTest () { var alertController = new UIAlertController (); alertController.SpringLoaded = true; - Assert.IsTrue (alertController.SpringLoaded); + Assert.That (alertController.SpringLoaded, Is.True); } [Test] @@ -40,7 +40,7 @@ public void UIBarButtonItemSpringLoadTest () { var barButtonItem = new UIBarButtonItem (); barButtonItem.SpringLoaded = true; - Assert.IsTrue (barButtonItem.SpringLoaded); + Assert.That (barButtonItem.SpringLoaded, Is.True); } [Test] @@ -48,7 +48,7 @@ public void UIButtonSpringLoadTest () { var button = new UIButton (); button.SpringLoaded = true; - Assert.IsTrue (button.SpringLoaded); + Assert.That (button.SpringLoaded, Is.True); } [Test] @@ -56,7 +56,7 @@ public void UICollectionViewSpringLoadTest () { var collectionView = new UICollectionView (new CGRect (0, 0, 100, 100), new UICollectionViewLayout ()); collectionView.SpringLoaded = true; - Assert.IsTrue (collectionView.SpringLoaded); + Assert.That (collectionView.SpringLoaded, Is.True); } [Test] @@ -64,7 +64,7 @@ public void UISegmentedControlSpringLoadTest () { var segmentedControl = new UISegmentedControl (); segmentedControl.SpringLoaded = true; - Assert.IsTrue (segmentedControl.SpringLoaded); + Assert.That (segmentedControl.SpringLoaded, Is.True); } [Test] @@ -72,7 +72,7 @@ public void UITabBarItemSpringLoadTest () { var tabBarItem = new UITabBarItem (); tabBarItem.SpringLoaded = true; - Assert.IsTrue (tabBarItem.SpringLoaded); + Assert.That (tabBarItem.SpringLoaded, Is.True); } [Test] @@ -80,7 +80,7 @@ public void UITabBarSpringLoadTest () { var tabBar = new UITabBar (); tabBar.SpringLoaded = true; - Assert.IsTrue (tabBar.SpringLoaded); + Assert.That (tabBar.SpringLoaded, Is.True); } [Test] @@ -88,7 +88,7 @@ public void UITableViewSpringLoadTest () { var tableView = new UITableView (); tableView.SpringLoaded = true; - Assert.IsTrue (tableView.SpringLoaded); + Assert.That (tableView.SpringLoaded, Is.True); } [Test] @@ -97,7 +97,7 @@ public void UISearchTabSpringLoadTest () TestRuntime.AssertXcodeVersion (16, 0); using var instance = new UISearchTab (null); instance.SpringLoaded = true; - Assert.IsTrue (instance.SpringLoaded); + Assert.That (instance.SpringLoaded, Is.True); } [Test] @@ -106,7 +106,7 @@ public void UITabSpringLoadTest () TestRuntime.AssertXcodeVersion (16, 0); using var instance = new UITab ("title", null, "identifier", null); instance.SpringLoaded = true; - Assert.IsTrue (instance.SpringLoaded); + Assert.That (instance.SpringLoaded, Is.True); } [Test] @@ -115,7 +115,7 @@ public void UITabGroupSpringLoadTest () TestRuntime.AssertXcodeVersion (16, 0); using var instance = new UITabGroup ("title", null, "identifier", new UITab [0], null); instance.SpringLoaded = true; - Assert.IsTrue (instance.SpringLoaded); + Assert.That (instance.SpringLoaded, Is.True); } #if HAS_INTENTUI @@ -126,7 +126,7 @@ public void INUIAddVoiceShortcutButtonTest () TestRuntime.AssertDevice (); var shortcutButton = new INUIAddVoiceShortcutButton (INUIAddVoiceShortcutButtonStyle.Black); shortcutButton.SpringLoaded = true; - Assert.IsTrue (shortcutButton.SpringLoaded); + Assert.That (shortcutButton.SpringLoaded, Is.True); } #endif } diff --git a/tests/monotouch-test/UIKit/UIStackViewTest.cs b/tests/monotouch-test/UIKit/UIStackViewTest.cs index 2a2065b573dd..c481ff5d1a7c 100644 --- a/tests/monotouch-test/UIKit/UIStackViewTest.cs +++ b/tests/monotouch-test/UIKit/UIStackViewTest.cs @@ -26,7 +26,7 @@ public void InitWithFrameTest () TestRuntime.AssertSystemVersion (ApplePlatform.iOS, 9, 0, throwIfOtherPlatform: false); UIStackView stack = new UIStackView (new CGRect (0, 0, 10, 10)); - Assert.NotNull (stack, "UIStackView ctor(CGRect)"); + Assert.That (stack, Is.Not.Null, "UIStackView ctor(CGRect)"); stack.AddArrangedSubview (new UIImageView ()); stack.AddArrangedSubview (new UIView ()); diff --git a/tests/monotouch-test/UIKit/UITextFormattingViewControllerFormattingDescriptorTest.cs b/tests/monotouch-test/UIKit/UITextFormattingViewControllerFormattingDescriptorTest.cs index 5cab73b1463c..e216595a140a 100644 --- a/tests/monotouch-test/UIKit/UITextFormattingViewControllerFormattingDescriptorTest.cs +++ b/tests/monotouch-test/UIKit/UITextFormattingViewControllerFormattingDescriptorTest.cs @@ -21,26 +21,26 @@ public void SetProperties () var textAlignments = UITextFormattingViewControllerTextAlignment.Left | UITextFormattingViewControllerTextAlignment.Center; obj.TextAlignments = textAlignments; var weakTestAlignments = ((IEnumerable) obj.WeakTextAlignments).Select (v => v.ToString ()).ToArray (); - Assert.AreEqual (2, weakTestAlignments.Length, "WeakTextAlignments.Length"); + Assert.That (weakTestAlignments.Length, Is.EqualTo (2), "WeakTextAlignments.Length"); Assert.That (weakTestAlignments, Does.Contain ((string) UITextFormattingViewControllerTextAlignment.Left.GetConstant ()), "WeakTextAlignments #1"); Assert.That (weakTestAlignments, Does.Contain ((string) UITextFormattingViewControllerTextAlignment.Center.GetConstant ()), "WeakTextAlignments #2"); - Assert.AreEqual (textAlignments, obj.TextAlignments, "TextAlignments"); + Assert.That (obj.TextAlignments, Is.EqualTo (textAlignments), "TextAlignments"); var textLists = UITextFormattingViewControllerTextList.Hyphen | UITextFormattingViewControllerTextList.Decimal; obj.TextLists = textLists; var weakTextLists = ((IEnumerable) obj.WeakTextLists).Select (v => v.ToString ()).ToArray (); - Assert.AreEqual (2, weakTextLists.Length, "WeakTextLists.Length"); + Assert.That (weakTextLists.Length, Is.EqualTo (2), "WeakTextLists.Length"); Assert.That (weakTextLists, Does.Contain ((string) UITextFormattingViewControllerTextList.Hyphen.GetConstant ()), "WeakTextLists #1"); Assert.That (weakTextLists, Does.Contain ((string) UITextFormattingViewControllerTextList.Decimal.GetConstant ()), "WeakTextLists #2"); - Assert.AreEqual (textLists, obj.TextLists, "TextLists"); + Assert.That (obj.TextLists, Is.EqualTo (textLists), "TextLists"); var highlights = UITextFormattingViewControllerHighlight.Purple | UITextFormattingViewControllerHighlight.Pink; obj.Highlights = highlights; var weakHighlights = ((IEnumerable) obj.WeakHighlights).Select (v => v.ToString ()).ToArray (); - Assert.AreEqual (2, weakHighlights.Length, "WeakHighlights.Length"); + Assert.That (weakHighlights.Length, Is.EqualTo (2), "WeakHighlights.Length"); Assert.That (weakHighlights, Does.Contain ((string) UITextFormattingViewControllerHighlight.Purple.GetConstant ()), "WeakHighlights #1"); Assert.That (weakHighlights, Does.Contain ((string) UITextFormattingViewControllerHighlight.Pink.GetConstant ()), "WeakHighlights #2"); - Assert.AreEqual (highlights, obj.Highlights, "Highlights"); + Assert.That (obj.Highlights, Is.EqualTo (highlights), "Highlights"); }); } @@ -59,7 +59,7 @@ public void Convert_Null () public void IsKeyWindow_5199 () { using (UIWindow w = new UIWindow ()) { - Assert.False (w.IsKeyWindow, "IsKeyWindow"); + Assert.That (w.IsKeyWindow, Is.False, "IsKeyWindow"); } } diff --git a/tests/monotouch-test/UIKit/UITraitOverrides.cs b/tests/monotouch-test/UIKit/UITraitOverrides.cs index 93cbb0fc6bb9..1e6f90f20581 100644 --- a/tests/monotouch-test/UIKit/UITraitOverrides.cs +++ b/tests/monotouch-test/UIKit/UITraitOverrides.cs @@ -306,17 +306,17 @@ void CallbackTest (Func callback = (env, coll) => { try { - Assert.AreEqual (horizontal is not null, vc.TraitOverrides.ContainsTrait (), $"{prefix}{msgPrefix} Horizontal A"); - Assert.AreEqual (horizontal is not null, vc.TraitOverrides.ContainsTrait (typeof (UITraitHorizontalSizeClass)), $"{prefix}{msgPrefix} Horizontal B"); - Assert.AreEqual (horizontal is not null, vc.TraitOverrides.ContainsTrait (new Class (typeof (UITraitHorizontalSizeClass))), $"{prefix}{msgPrefix} Horizontal C"); - Assert.AreEqual (vertical is not null, vc.TraitOverrides.ContainsTrait (), $"{prefix}{msgPrefix} Vertical A"); - Assert.AreEqual (vertical is not null, vc.TraitOverrides.ContainsTrait (typeof (UITraitVerticalSizeClass)), $"{prefix}{msgPrefix} Vertical B"); - Assert.AreEqual (vertical is not null, vc.TraitOverrides.ContainsTrait (new Class (typeof (UITraitVerticalSizeClass))), $"{prefix}{msgPrefix} Vertical C"); + Assert.That (vc.TraitOverrides.ContainsTrait (), Is.EqualTo (horizontal is not null), $"{prefix}{msgPrefix} Horizontal A"); + Assert.That (vc.TraitOverrides.ContainsTrait (typeof (UITraitHorizontalSizeClass)), Is.EqualTo (horizontal is not null), $"{prefix}{msgPrefix} Horizontal B"); + Assert.That (vc.TraitOverrides.ContainsTrait (new Class (typeof (UITraitHorizontalSizeClass))), Is.EqualTo (horizontal is not null), $"{prefix}{msgPrefix} Horizontal C"); + Assert.That (vc.TraitOverrides.ContainsTrait (), Is.EqualTo (vertical is not null), $"{prefix}{msgPrefix} Vertical A"); + Assert.That (vc.TraitOverrides.ContainsTrait (typeof (UITraitVerticalSizeClass)), Is.EqualTo (vertical is not null), $"{prefix}{msgPrefix} Vertical B"); + Assert.That (vc.TraitOverrides.ContainsTrait (new Class (typeof (UITraitVerticalSizeClass))), Is.EqualTo (vertical is not null), $"{prefix}{msgPrefix} Vertical C"); if (horizontal is not null) { - Assert.AreEqual (horizontal.Value, vc.TraitOverrides.HorizontalSizeClass, $"{prefix}{msgPrefix} Horizontal Value"); + Assert.That (vc.TraitOverrides.HorizontalSizeClass, Is.EqualTo (horizontal.Value), $"{prefix}{msgPrefix} Horizontal Value"); } if (vertical is not null) { - Assert.AreEqual (vertical.Value, vc.TraitOverrides.VerticalSizeClass, $"{prefix}{msgPrefix} Vertical Value"); + Assert.That (vc.TraitOverrides.VerticalSizeClass, Is.EqualTo (vertical.Value), $"{prefix}{msgPrefix} Vertical Value"); } callbackCounter++; } catch (Exception e) { @@ -342,43 +342,43 @@ void CallbackTest (Func (); - Assert.AreEqual (4, callbackCounter, $"{prefix}CallbackCounter 6"); - Assert.IsNull (ex, $"{prefix}Exception 6"); + Assert.That (callbackCounter, Is.EqualTo (4), $"{prefix}CallbackCounter 6"); + Assert.That (ex, Is.Null, $"{prefix}Exception 6"); horizontal = firstHorizontal; vc.TraitOverrides.HorizontalSizeClass = horizontal.Value; - Assert.AreEqual (5, callbackCounter, $"{prefix}CallbackCounter 7"); - Assert.IsNull (ex, $"{prefix}Exception 7"); + Assert.That (callbackCounter, Is.EqualTo (5), $"{prefix}CallbackCounter 7"); + Assert.That (ex, Is.Null, $"{prefix}Exception 7"); horizontal = null; vc.TraitOverrides.RemoveTrait (new Class (typeof (UITraitHorizontalSizeClass))); - Assert.AreEqual (5, callbackCounter, $"{prefix}CallbackCounter 8"); - Assert.IsNull (ex, $"{prefix}Exception 8"); + Assert.That (callbackCounter, Is.EqualTo (5), $"{prefix}CallbackCounter 8"); + Assert.That (ex, Is.Null, $"{prefix}Exception 8"); vc.UnregisterForTraitChanges (token); } diff --git a/tests/monotouch-test/UIKit/ViewControllerTest.cs b/tests/monotouch-test/UIKit/ViewControllerTest.cs index 8f5bb6a03337..609c25bb7c10 100644 --- a/tests/monotouch-test/UIKit/ViewControllerTest.cs +++ b/tests/monotouch-test/UIKit/ViewControllerTest.cs @@ -84,40 +84,40 @@ public void Defaults () using (var vc = new UIViewController ()) { Assert.Multiple (() => { Assert.That (vc.ChildViewControllers, Is.Empty, "ChildViewControllers"); - Assert.False (vc.DefinesPresentationContext, "DefinesPresentationContext"); + Assert.That (vc.DefinesPresentationContext, Is.False, "DefinesPresentationContext"); Assert.That (vc.DisablesAutomaticKeyboardDismissal, Is.EqualTo (true).Or.EqualTo (false), "DisablesAutomaticKeyboardDismissal"); - Assert.False (vc.Editing, "Editing"); - Assert.False (vc.IsBeingDismissed, "IsBeingDismissed"); - Assert.False (vc.IsBeingPresented, "IsBeingPresented"); - Assert.False (vc.IsMovingFromParentViewController, "IsMovingFromParentViewController"); - Assert.False (vc.IsMovingToParentViewController, "IsMovingToParentViewController"); - Assert.False (vc.IsViewLoaded, "IsViewLoaded"); - Assert.False (vc.ModalInPopover, "ModalInPopover"); - Assert.Null (vc.NavigationController, "NavigationController"); - Assert.NotNull (vc.NibBundle, "NibBundle"); - Assert.Null (vc.NibName, "NibName"); - Assert.Null (vc.ParentViewController, "ParentViewController"); - Assert.Null (vc.PresentedViewController, "PresentedViewController"); - Assert.Null (vc.PresentingViewController, "PresentingViewController"); - Assert.False (vc.ProvidesPresentationContextTransitionStyle, "ProvidesPresentationContextTransitionStyle"); + Assert.That (vc.Editing, Is.False, "Editing"); + Assert.That (vc.IsBeingDismissed, Is.False, "IsBeingDismissed"); + Assert.That (vc.IsBeingPresented, Is.False, "IsBeingPresented"); + Assert.That (vc.IsMovingFromParentViewController, Is.False, "IsMovingFromParentViewController"); + Assert.That (vc.IsMovingToParentViewController, Is.False, "IsMovingToParentViewController"); + Assert.That (vc.IsViewLoaded, Is.False, "IsViewLoaded"); + Assert.That (vc.ModalInPopover, Is.False, "ModalInPopover"); + Assert.That (vc.NavigationController, Is.Null, "NavigationController"); + Assert.That (vc.NibBundle, Is.Not.Null, "NibBundle"); + Assert.That (vc.NibName, Is.Null, "NibName"); + Assert.That (vc.ParentViewController, Is.Null, "ParentViewController"); + Assert.That (vc.PresentedViewController, Is.Null, "PresentedViewController"); + Assert.That (vc.PresentingViewController, Is.Null, "PresentingViewController"); + Assert.That (vc.ProvidesPresentationContextTransitionStyle, Is.False, "ProvidesPresentationContextTransitionStyle"); #if !__TVOS__ - Assert.True (vc.AutomaticallyForwardAppearanceAndRotationMethodsToChildViewControllers, "AutomaticallyForwardAppearanceAndRotationMethodsToChildViewControllers"); - Assert.False (vc.HidesBottomBarWhenPushed, "HidesBottomBarWhenPushed"); - Assert.Null (vc.ModalViewController, "ModalViewController"); - Assert.Null (vc.RotatingFooterView, "RotatingFooterView"); - Assert.Null (vc.RotatingHeaderView, "RotatingHeaderView"); + Assert.That (vc.AutomaticallyForwardAppearanceAndRotationMethodsToChildViewControllers, Is.True, "AutomaticallyForwardAppearanceAndRotationMethodsToChildViewControllers"); + Assert.That (vc.HidesBottomBarWhenPushed, Is.False, "HidesBottomBarWhenPushed"); + Assert.That (vc.ModalViewController, Is.Null, "ModalViewController"); + Assert.That (vc.RotatingFooterView, Is.Null, "RotatingFooterView"); + Assert.That (vc.RotatingHeaderView, Is.Null, "RotatingHeaderView"); #if !__MACCATALYST__ - Assert.Null (vc.SearchDisplayController, "SearchDisplayController"); + Assert.That (vc.SearchDisplayController, Is.Null, "SearchDisplayController"); #endif - Assert.False (vc.WantsFullScreenLayout, "WantsFullScreenLayout"); + Assert.That (vc.WantsFullScreenLayout, Is.False, "WantsFullScreenLayout"); #endif - Assert.Null (vc.SplitViewController, "SplitViewController"); - Assert.Null (vc.Storyboard, "Storyboard"); - Assert.Null (vc.TabBarController, "TabBarController"); - Assert.NotNull (vc.TabBarItem, "TabBarItem"); - Assert.Null (vc.Title, "Title"); - Assert.Null (vc.ToolbarItems, "ToolbarItems"); - Assert.NotNull (vc.View, "View"); + Assert.That (vc.SplitViewController, Is.Null, "SplitViewController"); + Assert.That (vc.Storyboard, Is.Null, "Storyboard"); + Assert.That (vc.TabBarController, Is.Null, "TabBarController"); + Assert.That (vc.TabBarItem, Is.Not.Null, "TabBarItem"); + Assert.That (vc.Title, Is.Null, "Title"); + Assert.That (vc.ToolbarItems, Is.Null, "ToolbarItems"); + Assert.That (vc.View, Is.Not.Null, "View"); }); } } @@ -132,12 +132,12 @@ public void Toolbars_Null () vc.ToolbarItems = buttons; Assert.That (vc.ToolbarItems.Length, Is.EqualTo (2), "1"); vc.ToolbarItems = null; - Assert.Null (vc.ToolbarItems, "2"); + Assert.That (vc.ToolbarItems, Is.Null, "2"); #if !__TVOS__ vc.SetToolbarItems (buttons, true); Assert.That (vc.ToolbarItems.Length, Is.EqualTo (2), "3"); vc.SetToolbarItems (null, false); - Assert.Null (vc.ToolbarItems, "4"); + Assert.That (vc.ToolbarItems, Is.Null, "4"); #endif } } @@ -148,12 +148,12 @@ public void View_Null () using (var vc = new UIViewController ()) { // even if the default is null The default value of this property is nil. // we'll never see it as such as it will be loaded (loadView) - Assert.NotNull (vc.View, "View-a"); + Assert.That (vc.View, Is.Not.Null, "View-a"); // OTOH we can set it to null ourself // or the controller can do it if iOS runs out of memory vc.View = null; // but again, accessing it will load the view - Assert.NotNull (vc.View, "View-b"); + Assert.That (vc.View, Is.Not.Null, "View-b"); } } diff --git a/tests/monotouch-test/UIKit/ViewTest.cs b/tests/monotouch-test/UIKit/ViewTest.cs index 4ab645a06a2a..8a1d6e9ea228 100644 --- a/tests/monotouch-test/UIKit/ViewTest.cs +++ b/tests/monotouch-test/UIKit/ViewTest.cs @@ -28,7 +28,7 @@ public void HitTest_Null () var frame = new CGRect (10, 10, 100, 100); using (UIView v = new UIView (frame)) { UIView result = v.HitTest (new CGPoint (-10, -10), null); - Assert.Null (result, "outside"); + Assert.That (result, Is.Null, "outside"); result = v.HitTest (new CGPoint (50, 50), null); Assert.That (result.Handle, Is.EqualTo (v.Handle), "inside"); } @@ -39,8 +39,8 @@ public void PointInside_Null () { var frame = new CGRect (10, 10, 100, 100); using (UIView v = new UIView (frame)) { - Assert.False (v.PointInside (new CGPoint (-10, -10), null), "outside"); - Assert.True (v.PointInside (new CGPoint (50, 50), null), "inside"); + Assert.That (v.PointInside (new CGPoint (-10, -10), null), Is.False, "outside"); + Assert.That (v.PointInside (new CGPoint (50, 50), null), Is.True, "inside"); } } @@ -50,7 +50,7 @@ public void SizeThatFits () // same as LinkerTest in 'linksdk' project - but won't be linked here (for simulator) var empty = CGSize.Empty; using (UIView v = new UIView ()) { - Assert.True (v.SizeThatFits (empty).IsEmpty, "Empty"); + Assert.That (v.SizeThatFits (empty).IsEmpty, Is.True, "Empty"); } } @@ -205,37 +205,37 @@ public override UIColor BackgroundColor { public void TraitTest () { using (var view = new UIView ()) { - Assert.AreEqual (UIAccessibilityTrait.None, view.AccessibilityTraits, "a"); + Assert.That (view.AccessibilityTraits, Is.EqualTo (UIAccessibilityTrait.None), "a"); view.AccessibilityTraits = UIAccessibilityTrait.None; - Assert.AreEqual (UIAccessibilityTrait.None, view.AccessibilityTraits, "b"); + Assert.That (view.AccessibilityTraits, Is.EqualTo (UIAccessibilityTrait.None), "b"); view.AccessibilityTraits = UIAccessibilityTrait.Adjustable; - Assert.AreEqual (UIAccessibilityTrait.Adjustable, view.AccessibilityTraits, "c"); + Assert.That (view.AccessibilityTraits, Is.EqualTo (UIAccessibilityTrait.Adjustable), "c"); view.AccessibilityTraits = UIAccessibilityTrait.Adjustable | UIAccessibilityTrait.Button; - Assert.AreEqual (UIAccessibilityTrait.Adjustable | UIAccessibilityTrait.Button, view.AccessibilityTraits, "e"); + Assert.That (view.AccessibilityTraits, Is.EqualTo (UIAccessibilityTrait.Adjustable | UIAccessibilityTrait.Button), "e"); } } [Test] public void TraitMatch () { - Assert.AreEqual ((int) UIAccessibilityTrait.Adjustable, UIView.TraitAdjustable, "Adjustable"); - Assert.AreEqual ((int) UIAccessibilityTrait.AllowsDirectInteraction, UIView.TraitAllowsDirectInteraction, "AllowsDirectInteraction"); - Assert.AreEqual ((int) UIAccessibilityTrait.Button, UIView.TraitButton, "Button"); - Assert.AreEqual ((int) UIAccessibilityTrait.CausesPageTurn, UIView.TraitCausesPageTurn, "CausesPageTurn"); - Assert.AreEqual ((int) UIAccessibilityTrait.Image, UIView.TraitImage, "Image"); - Assert.AreEqual ((int) UIAccessibilityTrait.KeyboardKey, UIView.TraitKeyboardKey, "KeyboardKey"); - Assert.AreEqual ((int) UIAccessibilityTrait.Link, UIView.TraitLink, "Link"); - Assert.AreEqual ((int) UIAccessibilityTrait.None, UIView.TraitNone, "None"); - Assert.AreEqual ((int) UIAccessibilityTrait.NotEnabled, UIView.TraitNotEnabled, "NotEnabled"); - Assert.AreEqual ((int) UIAccessibilityTrait.PlaysSound, UIView.TraitPlaysSound, "PlaysSound"); - Assert.AreEqual ((int) UIAccessibilityTrait.SearchField, UIView.TraitSearchField, "SearchField"); - Assert.AreEqual ((int) UIAccessibilityTrait.Selected, UIView.TraitSelected, "Selected"); - Assert.AreEqual ((int) UIAccessibilityTrait.StartsMediaSession, UIView.TraitStartsMediaSession, "StartsMediaSession"); - Assert.AreEqual ((int) UIAccessibilityTrait.StaticText, UIView.TraitStaticText, "StaticText"); - Assert.AreEqual ((int) UIAccessibilityTrait.SummaryElement, UIView.TraitSummaryElement, "SummaryElement"); - Assert.AreEqual ((int) UIAccessibilityTrait.UpdatesFrequently, UIView.TraitUpdatesFrequently, "UpdatesFrequently"); - - Assert.AreEqual ((int) UIAccessibilityTrait.Header, UIView.TraitHeader, "Header"); + Assert.That (UIView.TraitAdjustable, Is.EqualTo ((int) UIAccessibilityTrait.Adjustable), "Adjustable"); + Assert.That (UIView.TraitAllowsDirectInteraction, Is.EqualTo ((int) UIAccessibilityTrait.AllowsDirectInteraction), "AllowsDirectInteraction"); + Assert.That (UIView.TraitButton, Is.EqualTo ((int) UIAccessibilityTrait.Button), "Button"); + Assert.That (UIView.TraitCausesPageTurn, Is.EqualTo ((int) UIAccessibilityTrait.CausesPageTurn), "CausesPageTurn"); + Assert.That (UIView.TraitImage, Is.EqualTo ((int) UIAccessibilityTrait.Image), "Image"); + Assert.That (UIView.TraitKeyboardKey, Is.EqualTo ((int) UIAccessibilityTrait.KeyboardKey), "KeyboardKey"); + Assert.That (UIView.TraitLink, Is.EqualTo ((int) UIAccessibilityTrait.Link), "Link"); + Assert.That (UIView.TraitNone, Is.EqualTo ((int) UIAccessibilityTrait.None), "None"); + Assert.That (UIView.TraitNotEnabled, Is.EqualTo ((int) UIAccessibilityTrait.NotEnabled), "NotEnabled"); + Assert.That (UIView.TraitPlaysSound, Is.EqualTo ((int) UIAccessibilityTrait.PlaysSound), "PlaysSound"); + Assert.That (UIView.TraitSearchField, Is.EqualTo ((int) UIAccessibilityTrait.SearchField), "SearchField"); + Assert.That (UIView.TraitSelected, Is.EqualTo ((int) UIAccessibilityTrait.Selected), "Selected"); + Assert.That (UIView.TraitStartsMediaSession, Is.EqualTo ((int) UIAccessibilityTrait.StartsMediaSession), "StartsMediaSession"); + Assert.That (UIView.TraitStaticText, Is.EqualTo ((int) UIAccessibilityTrait.StaticText), "StaticText"); + Assert.That (UIView.TraitSummaryElement, Is.EqualTo ((int) UIAccessibilityTrait.SummaryElement), "SummaryElement"); + Assert.That (UIView.TraitUpdatesFrequently, Is.EqualTo ((int) UIAccessibilityTrait.UpdatesFrequently), "UpdatesFrequently"); + + Assert.That (UIView.TraitHeader, Is.EqualTo ((int) UIAccessibilityTrait.Header), "Header"); } [Test] @@ -247,7 +247,7 @@ public void Subviews () // even if null we want to ensure we can use UIView.GetEnumarator to iterate subviews int n = 0; foreach (var sv in v) - Assert.NotNull (sv, n++.ToString ()); + Assert.That (sv, Is.Not.Null, n++.ToString ()); } } @@ -258,11 +258,11 @@ public void TintColor () using (var v = new UIView ()) { var tc = v.TintColor; - Assert.NotNull (tc, "TintColor-1"); + Assert.That (tc, Is.Not.Null, "TintColor-1"); v.TintColor = UIColor.Red; v.TintColor = null; // setting to null returns to default (i.e. not the last non-null value) - Assert.NotNull (v.TintColor, "TintColor-2"); + Assert.That (v.TintColor, Is.Not.Null, "TintColor-2"); } } @@ -275,7 +275,7 @@ public void Equality () Assert.That (v1.Handle, Is.Not.EqualTo (v2.Handle), "Handle"); // and that's enough to make them totally different (natively in objc for both `hash` and `isEqual:`) Assert.That (v1.GetHashCode (), Is.Not.EqualTo (v2.GetHashCode ()), "GetHashCode"); - Assert.False (v1.Equals (v2.Handle), "Equals"); + Assert.That (v1.Equals (v2.Handle), Is.False, "Equals"); } } } diff --git a/tests/monotouch-test/UIKit/WebViewTest.cs b/tests/monotouch-test/UIKit/WebViewTest.cs index 3a5d997e650f..66bb488df70a 100644 --- a/tests/monotouch-test/UIKit/WebViewTest.cs +++ b/tests/monotouch-test/UIKit/WebViewTest.cs @@ -25,7 +25,7 @@ public void InitWithFrame () var frame = new CGRect (10, 10, 100, 100); using (UIWebView wv = new UIWebView (frame)) { Assert.That (wv.Frame, Is.EqualTo (frame), "Frame"); - Assert.Null (wv.Request, "Request"); + Assert.That (wv.Request, Is.Null, "Request"); } } diff --git a/tests/monotouch-test/UIKit/WindowTest.cs b/tests/monotouch-test/UIKit/WindowTest.cs index efaa6ae54bcf..7ddd4d4363f3 100644 --- a/tests/monotouch-test/UIKit/WindowTest.cs +++ b/tests/monotouch-test/UIKit/WindowTest.cs @@ -36,7 +36,7 @@ public void Convert_Null () public void IsKeyWindow_5199 () { using (UIWindow w = new UIWindow ()) { - Assert.False (w.IsKeyWindow, "IsKeyWindow"); + Assert.That (w.IsKeyWindow, Is.False, "IsKeyWindow"); } } diff --git a/tests/monotouch-test/UniformTypeIdentifiers/TypeTest.cs b/tests/monotouch-test/UniformTypeIdentifiers/TypeTest.cs index 9d60f48568e6..aba01dbc13cc 100644 --- a/tests/monotouch-test/UniformTypeIdentifiers/TypeTest.cs +++ b/tests/monotouch-test/UniformTypeIdentifiers/TypeTest.cs @@ -21,10 +21,10 @@ public void Archive () TestRuntime.AssertIfSimulatorThenARM64 (); var a = UTTypes.Archive; - Assert.False (a.Dynamic, "Dynamic"); + Assert.That (a.Dynamic, Is.False, "Dynamic"); var z = UTTypes.Zip; - Assert.True (z.IsSubtypeOf (a), "IsSubtypeOf"); - Assert.True (a.IsSupertypeOf (z), "IsSupertypeOf"); + Assert.That (z.IsSubtypeOf (a), Is.True, "IsSubtypeOf"); + Assert.That (a.IsSupertypeOf (z), Is.True, "IsSupertypeOf"); } } } diff --git a/tests/monotouch-test/UserNotifications/NotificationInterruptionLevel.cs b/tests/monotouch-test/UserNotifications/NotificationInterruptionLevel.cs index b4d07e3454b0..e47f120eb4a2 100644 --- a/tests/monotouch-test/UserNotifications/NotificationInterruptionLevel.cs +++ b/tests/monotouch-test/UserNotifications/NotificationInterruptionLevel.cs @@ -19,10 +19,10 @@ typedef NS_ENUM (NSUInteger, UNNotificationInterruptionLevel) UNNotificationInterruptionLevelTimeSensitive, UNNotificationInterruptionLevelCritical, } */ - Assert.AreEqual ((int) UNNotificationInterruptionLevel.Passive2, 0); - Assert.AreEqual ((int) UNNotificationInterruptionLevel.Active2, 1); - Assert.AreEqual ((int) UNNotificationInterruptionLevel.TimeSensitive2, 2); - Assert.AreEqual ((int) UNNotificationInterruptionLevel.Critical2, 3); + Assert.That ((int) UNNotificationInterruptionLevel.Passive2, Is.EqualTo (0)); + Assert.That ((int) UNNotificationInterruptionLevel.Active2, Is.EqualTo (1)); + Assert.That ((int) UNNotificationInterruptionLevel.TimeSensitive2, Is.EqualTo (2)); + Assert.That ((int) UNNotificationInterruptionLevel.Critical2, Is.EqualTo (3)); #endif } } diff --git a/tests/monotouch-test/VideoToolbox/VTCompressionPropertyCameraCalibrationTest.cs b/tests/monotouch-test/VideoToolbox/VTCompressionPropertyCameraCalibrationTest.cs index 4bfc0b15ca9e..742f9362ef03 100644 --- a/tests/monotouch-test/VideoToolbox/VTCompressionPropertyCameraCalibrationTest.cs +++ b/tests/monotouch-test/VideoToolbox/VTCompressionPropertyCameraCalibrationTest.cs @@ -23,19 +23,19 @@ public void DefaultValues () Assert.Multiple (() => { var dict = new VTCompressionPropertyCameraCalibration (); - Assert.IsNull (dict.LensAlgorithmKind, "LensAlgorithmKind"); - Assert.IsNull (dict.LensDomain, "LensDomain"); - Assert.IsNull (dict.LensIdentifier, "LensIdentifier"); - Assert.IsNull (dict.LensRole, "LensRole"); - Assert.IsNull (dict.LensDistortions, "LensDistortions"); - Assert.IsNull (dict.RadialAngleLimit, "RadialAngleLimit"); - Assert.IsNull (dict.LensFrameAdjustmentsPolynomialX, "LensFrameAdjustmentsPolynomialX"); - Assert.IsNull (dict.LensFrameAdjustmentsPolynomialY, "LensFrameAdjustmentsPolynomialY"); - Assert.IsNull (dict.IntrinsicMatrix, "IntrinsicMatrix"); - Assert.IsNull (dict.IntrinsicMatrixProjectionOffset, "IntrinsicMatrixProjectionOffset"); - Assert.IsNull (dict.IntrinsicMatrixReferenceDimensions, "IntrinsicMatrixReferenceDimensions"); - Assert.IsNull (dict.ExtrinsicOriginSource, "ExtrinsicOriginSource"); - Assert.IsNull (dict.ExtrinsicOrientationQuaternion, "ExtrinsicOrientationQuaternion"); + Assert.That (dict.LensAlgorithmKind, Is.Null, "LensAlgorithmKind"); + Assert.That (dict.LensDomain, Is.Null, "LensDomain"); + Assert.That (dict.LensIdentifier, Is.Null, "LensIdentifier"); + Assert.That (dict.LensRole, Is.Null, "LensRole"); + Assert.That (dict.LensDistortions, Is.Null, "LensDistortions"); + Assert.That (dict.RadialAngleLimit, Is.Null, "RadialAngleLimit"); + Assert.That (dict.LensFrameAdjustmentsPolynomialX, Is.Null, "LensFrameAdjustmentsPolynomialX"); + Assert.That (dict.LensFrameAdjustmentsPolynomialY, Is.Null, "LensFrameAdjustmentsPolynomialY"); + Assert.That (dict.IntrinsicMatrix, Is.Null, "IntrinsicMatrix"); + Assert.That (dict.IntrinsicMatrixProjectionOffset, Is.Null, "IntrinsicMatrixProjectionOffset"); + Assert.That (dict.IntrinsicMatrixReferenceDimensions, Is.Null, "IntrinsicMatrixReferenceDimensions"); + Assert.That (dict.ExtrinsicOriginSource, Is.Null, "ExtrinsicOriginSource"); + Assert.That (dict.ExtrinsicOrientationQuaternion, Is.Null, "ExtrinsicOrientationQuaternion"); Assert.That (dict.ToString (), Is.EqualTo ("VideoToolbox.VTCompressionPropertyCameraCalibration"), "ToString"); Assert.That (dict.Dictionary.ToString (), Is.EqualTo ("{\n}"), "ToString"); }); diff --git a/tests/monotouch-test/VideoToolbox/VTCompressionSessionTests.cs b/tests/monotouch-test/VideoToolbox/VTCompressionSessionTests.cs index 09c9300dfe77..d72f372a878a 100644 --- a/tests/monotouch-test/VideoToolbox/VTCompressionSessionTests.cs +++ b/tests/monotouch-test/VideoToolbox/VTCompressionSessionTests.cs @@ -37,7 +37,7 @@ public void CompressionSessionCreateTest () TestRuntime.AssertSystemVersion (ApplePlatform.TVOS, 10, 2, throwIfOtherPlatform: false); using (var session = CreateSession ()) { - Assert.IsNotNull (session, "Session should not be null"); + Assert.That (session, Is.Not.Null, "Session should not be null"); } } @@ -107,7 +107,7 @@ public void CompressionSessionGetSupportedPropertiesTest () using (var session = CreateSession ()) { var supportedProps = session.GetSupportedProperties (); - Assert.NotNull (supportedProps, "GetSupportedProperties IsNull"); + Assert.That (supportedProps, Is.Not.Null, "GetSupportedProperties IsNull"); var key = new NSString ("ShouldBeSerialized"); foreach (var item in supportedProps) { @@ -117,7 +117,7 @@ public void CompressionSessionGetSupportedPropertiesTest () NSObject value; if (dict.TryGetValue (key, out value) && value is not null) { var number = (NSNumber) value; - Assert.IsFalse (number.BoolValue, "CompressionSession GetSupportedPropertiesTest ShouldBeSerialized is True"); + Assert.That (number.BoolValue, Is.False, "CompressionSession GetSupportedPropertiesTest ShouldBeSerialized is True"); } } } @@ -137,7 +137,7 @@ public void CompressionSessionGetSerializablePropertiesTest () using (var session = CreateSession ()) { var supportedProps = session.GetSerializableProperties (); - Assert.IsNull (supportedProps, "CompressionSession GetSerializableProperties is not null"); + Assert.That (supportedProps, Is.Null, "CompressionSession GetSerializableProperties is not null"); } } @@ -187,10 +187,10 @@ public void TestCallback (bool stronglyTyped) thread.IsBackground = true; thread.Start (); var completed = thread.Join (TimeSpan.FromSeconds (30)); - Assert.IsNull (ex); // We check for this before the completion assert, to show any other assertion failures that may occur in CI. + Assert.That (ex, Is.Null); // We check for this before the completion assert, to show any other assertion failures that may occur in CI. if (!completed) TestRuntime.IgnoreInCI ("This test fails occasionally in CI"); - Assert.IsTrue (completed, "timed out"); + Assert.That (completed, Is.True, "timed out"); } public void TestCallbackBackground (bool stronglyTyped) @@ -217,14 +217,14 @@ public void TestCallbackBackground (bool stronglyTyped) using var imageBuffer = new CVPixelBuffer (width, height, CVPixelFormatType.CV420YpCbCr8BiPlanarFullRange); var pts = new CMTime (40 * i, 1); status = session.EncodeFrame (imageBuffer, pts, duration, null, sourceFrameValue, out var infoFlags); - Assert.AreEqual (VTStatus.Ok, status, $"status #{i}"); + Assert.That (status, Is.EqualTo (VTStatus.Ok), $"status #{i}"); // This looks weird, but it seems the video encoder can become overwhelmed otherwise, and it // will start failing (and taking a long time to do so, eventually timing out the test). Thread.Sleep (10); } status = session.CompleteFrames (new CMTime (40 * frameCount, 1)); - Assert.AreEqual (VTStatus.Ok, status, "status finished"); - Assert.AreEqual (frameCount, callbackCounter, "frame count"); + Assert.That (status, Is.EqualTo (VTStatus.Ok), "status finished"); + Assert.That (callbackCounter, Is.EqualTo (frameCount), "frame count"); Assert.That (failures, Is.Empty, "no callback failures"); } @@ -254,11 +254,11 @@ public void TestMultiImage (bool stronglyTyped, bool customCallback) if (ex is NUnit.Framework.Internal.NUnitException) throw ex; - Assert.IsNull (ex); // We check for this before the completion assert, to show any other assertion failures that may occur in CI. + Assert.That (ex, Is.Null); // We check for this before the completion assert, to show any other assertion failures that may occur in CI. if (!completed) TestRuntime.IgnoreInCI ("This test fails occasionally in CI"); - Assert.IsTrue (completed, "timed out"); + Assert.That (completed, Is.True, "timed out"); } void TestMultiImageCallbackBackground (bool stronglyTyped, bool customCallback) @@ -321,7 +321,7 @@ void TestMultiImageCallbackBackground (bool stronglyTyped, bool customCallback) } else { status = session.EncodeMultiImageFrame (taggedBufferGroup, pts, duration, null, sourceFrameValue, out infoFlags); } - Assert.AreEqual (VTStatus.Ok, status, $"status #{i}"); + Assert.That (status, Is.EqualTo (VTStatus.Ok), $"status #{i}"); Assert.That (infoFlags, Is.EqualTo (VTEncodeInfoFlags.Asynchronous), $"infoFlags #{i}"); foreach (var img in buffers) @@ -329,13 +329,13 @@ void TestMultiImageCallbackBackground (bool stronglyTyped, bool customCallback) } status = session.CompleteFrames (new CMTime (40 * frameCount * chunks, 1)); GC.KeepAlive (session); - Assert.AreEqual (VTStatus.Ok, status, "status finished"); + Assert.That (status, Is.EqualTo (VTStatus.Ok), "status finished"); if (customCallback) { - Assert.AreEqual (0, callbackCounter, "frame count A"); - Assert.AreEqual (frameCount, callbackCounter2, "frame count A2"); + Assert.That (callbackCounter, Is.EqualTo (0), "frame count A"); + Assert.That (callbackCounter2, Is.EqualTo (frameCount), "frame count A2"); } else { - Assert.AreEqual (frameCount, callbackCounter, "frame count B"); - Assert.AreEqual (0, callbackCounter2, "frame count B2"); + Assert.That (callbackCounter, Is.EqualTo (frameCount), "frame count B"); + Assert.That (callbackCounter2, Is.EqualTo (0), "frame count B2"); } Assert.That (failures, Is.Empty, "no callback failures"); } diff --git a/tests/monotouch-test/VideoToolbox/VTDecompressionSessionTests.cs b/tests/monotouch-test/VideoToolbox/VTDecompressionSessionTests.cs index f6dae5da90b9..bfb8d2fdb344 100644 --- a/tests/monotouch-test/VideoToolbox/VTDecompressionSessionTests.cs +++ b/tests/monotouch-test/VideoToolbox/VTDecompressionSessionTests.cs @@ -40,7 +40,7 @@ public void DecompressionSessionCreateTest () using (var asset = AVAsset.FromUrl (NSBundle.MainBundle.GetUrlForResource ("xamvideotest", "mp4"))) using (var session = CreateSession (asset)) { - Assert.IsNotNull (session, "Session should not be null"); + Assert.That (session, Is.Not.Null, "Session should not be null"); } } @@ -59,7 +59,7 @@ public void DecompressionSessionSetDecompressionPropertiesTest () OnlyTheseFrames = VTOnlyTheseFrames.AllFrames }); - Assert.AreEqual (VTStatus.Ok, result, "SetDecompressionProperties"); + Assert.That (result, Is.EqualTo (VTStatus.Ok), "SetDecompressionProperties"); } } @@ -78,7 +78,7 @@ public void DecompressionSessionSetPropertiesTest () ShouldBeSerialized = true }); - Assert.AreEqual (VTStatus.Ok, result, "SetProperties"); + Assert.That (result, Is.EqualTo (VTStatus.Ok), "SetProperties"); } } @@ -92,7 +92,7 @@ public void DecompressionSessionGetSupportedPropertiesTest () using (var asset = AVAsset.FromUrl (NSBundle.MainBundle.GetUrlForResource ("xamvideotest", "mp4"))) using (var session = CreateSession (asset)) { var supportedProps = session.GetSupportedProperties (); - Assert.NotNull (supportedProps, "GetSupportedProperties"); + Assert.That (supportedProps, Is.Not.Null, "GetSupportedProperties"); Assert.That (supportedProps.Count, Is.GreaterThan ((nuint) 0), "GetSupportedProperties should be more than zero"); } } @@ -128,7 +128,7 @@ public SampleBufferEnumerator (NSUrl url, AVMediaCharacteristics characteristic asset.LoadTrackWithMediaCharacteristics (characteristic.GetConstant (), (tracks, error) => { try { - Assert.Null (error, "Failed to load track"); + Assert.That (error, Is.Null, "Failed to load track"); videoTrack = (AVAssetTrack) tracks.ToArray ().First (); @@ -139,7 +139,7 @@ public SampleBufferEnumerator (NSUrl url, AVMediaCharacteristics characteristic } }); - Assert.IsTrue (loaded.Task.Wait (TimeSpan.FromSeconds (15)), "Timed out waiting for track to load"); + Assert.That (loaded.Task.Wait (TimeSpan.FromSeconds (15)), Is.True, "Timed out waiting for track to load"); FormatDescription = loaded.Task.Result; } @@ -152,8 +152,8 @@ public void Enumerate (Action iterator) do { using var buffer = sampleBufferGenerator.CreateSampleBuffer (request, out var sampleBufferError); - Assert.NotNull (buffer, "Sample Buffer"); - Assert.Null (sampleBufferError, "Sample Buffer Error"); + Assert.That (buffer, Is.Not.Null, "Sample Buffer"); + Assert.That (sampleBufferError, Is.Null, "Sample Buffer Error"); iterator (buffer); diff --git a/tests/monotouch-test/VideoToolbox/VTFrameRateConversionConfigurationTest.cs b/tests/monotouch-test/VideoToolbox/VTFrameRateConversionConfigurationTest.cs index f2a0164b0f32..67a426f32de1 100644 --- a/tests/monotouch-test/VideoToolbox/VTFrameRateConversionConfigurationTest.cs +++ b/tests/monotouch-test/VideoToolbox/VTFrameRateConversionConfigurationTest.cs @@ -51,10 +51,10 @@ public void Properties () Assert.That (VTFrameRateConversionConfiguration.ProcessorSupported, Is.True, "ProcessorSupported"); Assert.That (VTFrameRateConversionConfiguration.SupportedRevisions, Is.Not.Null, "SupportedRevisions"); - Assert.That (VTFrameRateConversionConfiguration.SupportedRevisions, Does.Contain (VTFrameRateConversionConfigurationRevision.Revision1), "SupportedRevisions.Contains"); + Assert.That (VTFrameRateConversionConfiguration.SupportedRevisions.Contains (VTFrameRateConversionConfigurationRevision.Revision1), "SupportedRevisions.Contains"); Assert.That (VTFrameRateConversionConfiguration.WeakSupportedRevisions, Is.Not.Null, "WeakSupportedRevisions"); - Assert.That (VTFrameRateConversionConfiguration.WeakSupportedRevisions, Does.Contain ((nuint) 1), "WeakSupportedRevisions.Contains"); - Assert.That (Enum.GetValues (), Does.Contain (VTFrameRateConversionConfiguration.DefaultRevision), "DefaultRevision"); + Assert.That (VTFrameRateConversionConfiguration.WeakSupportedRevisions.Contains ((nuint) 1), "WeakSupportedRevisions.Contains"); + Assert.That (Enum.GetValues ().Contains (VTFrameRateConversionConfiguration.DefaultRevision), "DefaultRevision"); }); } } diff --git a/tests/monotouch-test/VideoToolbox/VTFrameSiloTests.cs b/tests/monotouch-test/VideoToolbox/VTFrameSiloTests.cs index 466325079c78..50c692dae0d0 100644 --- a/tests/monotouch-test/VideoToolbox/VTFrameSiloTests.cs +++ b/tests/monotouch-test/VideoToolbox/VTFrameSiloTests.cs @@ -26,7 +26,7 @@ public void FrameSiloCreateTest () TestRuntime.AssertSystemVersion (ApplePlatform.TVOS, 10, 2, throwIfOtherPlatform: false); using (var silo = VTFrameSilo.Create ()) { - Assert.IsNotNull (silo, "Silo should not be null"); + Assert.That (silo, Is.Not.Null, "Silo should not be null"); } } @@ -39,7 +39,7 @@ public void SetTimeRangesTest () using (var silo = VTFrameSilo.Create ()) { var result = silo.SetTimeRangesForNextPass (new CMTimeRange [0]); - Assert.IsTrue (result == VTStatus.FrameSiloInvalidTimeRange, "SetTimeRangesForNextPass"); + Assert.That (result == VTStatus.FrameSiloInvalidTimeRange, Is.True, "SetTimeRangesForNextPass"); } } @@ -55,17 +55,17 @@ public void ForEachTest () var result = silo.ForEach ((arg) => { return VTStatus.Ok; }); - Assert.IsTrue (result == VTStatus.Ok, "VTFrameSilo ForEach"); + Assert.That (result == VTStatus.Ok, Is.True, "VTFrameSilo ForEach"); result = silo.ForEach ((arg) => { return VTStatus.Ok; }); - Assert.IsTrue (result == VTStatus.Ok, "VTFrameSilo ForEach"); + Assert.That (result == VTStatus.Ok, Is.True, "VTFrameSilo ForEach"); result = silo.ForEach ((arg) => { return VTStatus.Ok; }); - Assert.IsTrue (result == VTStatus.Ok, "VTFrameSilo ForEach"); + Assert.That (result == VTStatus.Ok, Is.True, "VTFrameSilo ForEach"); } } } diff --git a/tests/monotouch-test/VideoToolbox/VTHdrPerFrameMetadataGenerationSessionTest.cs b/tests/monotouch-test/VideoToolbox/VTHdrPerFrameMetadataGenerationSessionTest.cs index 26210fbf3a94..6b5c71c3515f 100644 --- a/tests/monotouch-test/VideoToolbox/VTHdrPerFrameMetadataGenerationSessionTest.cs +++ b/tests/monotouch-test/VideoToolbox/VTHdrPerFrameMetadataGenerationSessionTest.cs @@ -28,8 +28,8 @@ public void Create_NSDictionary_Test () TestRuntime.AssertXcodeVersion (16, 0); using var session = VTHdrPerFrameMetadataGenerationSession.Create (30, (NSDictionary) null, out var vtStatus); - Assert.IsNotNull (session, "session"); - Assert.AreEqual (VTStatus.Ok, vtStatus, "status"); + Assert.That (session, Is.Not.Null, "session"); + Assert.That (vtStatus, Is.EqualTo (VTStatus.Ok), "status"); } [Test] @@ -38,8 +38,8 @@ public void Create_VTHdrPerFrameMetadataGenerationOptions_Test () TestRuntime.AssertXcodeVersion (16, 0); using var session = VTHdrPerFrameMetadataGenerationSession.Create (30, (VTHdrPerFrameMetadataGenerationOptions) null, out var vtStatus); - Assert.IsNotNull (session, "session"); - Assert.AreEqual (VTStatus.Ok, vtStatus, "status"); + Assert.That (session, Is.Not.Null, "session"); + Assert.That (vtStatus, Is.EqualTo (VTStatus.Ok), "status"); } [Test] @@ -51,8 +51,8 @@ public void AttachMetadataTest () TestRuntime.AssertXcodeVersion (16, 0); using var session = VTHdrPerFrameMetadataGenerationSession.Create (30, (VTHdrPerFrameMetadataGenerationOptions) null, out var vtStatus); - Assert.IsNotNull (session, "session"); - Assert.AreEqual (VTStatus.Ok, vtStatus, "status"); + Assert.That (session, Is.Not.Null, "session"); + Assert.That (vtStatus, Is.EqualTo (VTStatus.Ok), "status"); using var pixelBuffer = new CVPixelBuffer (width, height, CVPixelFormatType.CV420YpCbCr8BiPlanarFullRange); vtStatus = session.AttachMetadata (pixelBuffer, false); #if __TVOS__ || __IOS__ @@ -60,7 +60,7 @@ public void AttachMetadataTest () // It works on other platforms though, so the API (and the bindings) seem to work fine. Assert.That (vtStatus, Is.EqualTo (VTStatus.Ok).Or.EqualTo (VTStatus.PropertyNotSupported), "status AttachMetadata"); #else - Assert.AreEqual (VTStatus.Ok, vtStatus, "status AttachMetadata"); + Assert.That (vtStatus, Is.EqualTo (VTStatus.Ok), "status AttachMetadata"); #endif } @@ -69,7 +69,7 @@ public void GetTypeId () { TestRuntime.AssertXcodeVersion (16, 0); - Assert.AreNotEqual (0, VTHdrPerFrameMetadataGenerationSession.GetTypeId (), "GetTypeId"); + Assert.That (VTHdrPerFrameMetadataGenerationSession.GetTypeId (), Is.Not.EqualTo (0), "GetTypeId"); } } } diff --git a/tests/monotouch-test/VideoToolbox/VTMotionBlurConfigurationTest.cs b/tests/monotouch-test/VideoToolbox/VTMotionBlurConfigurationTest.cs index b760f1114222..56fc4049401d 100644 --- a/tests/monotouch-test/VideoToolbox/VTMotionBlurConfigurationTest.cs +++ b/tests/monotouch-test/VideoToolbox/VTMotionBlurConfigurationTest.cs @@ -3,6 +3,8 @@ #if __MACOS__ +using System.Linq; + using AVFoundation; using CoreMedia; using CoreVideo; @@ -34,10 +36,10 @@ public void Properties () Assert.That (VTMotionBlurConfiguration.ProcessorSupported, Is.True, "ProcessorSupported"); Assert.That (VTMotionBlurConfiguration.SupportedRevisions, Is.Not.Null, "SupportedRevisions"); - Assert.That (VTMotionBlurConfiguration.SupportedRevisions, Does.Contain (VTMotionBlurConfigurationRevision.Revision1), "SupportedRevisions.Contains"); + Assert.That (VTMotionBlurConfiguration.SupportedRevisions.Contains (VTMotionBlurConfigurationRevision.Revision1), "SupportedRevisions.Contains"); Assert.That (VTMotionBlurConfiguration.WeakSupportedRevisions, Is.Not.Null, "WeakSupportedRevisions"); - Assert.That (VTMotionBlurConfiguration.WeakSupportedRevisions, Does.Contain ((nuint) 1), "WeakSupportedRevisions.Contains"); - Assert.That (Enum.GetValues (), Does.Contain (VTMotionBlurConfiguration.DefaultRevision), "DefaultRevision"); + Assert.That (VTMotionBlurConfiguration.WeakSupportedRevisions.Contains ((nuint) 1), "WeakSupportedRevisions.Contains"); + Assert.That (Enum.GetValues ().Contains (VTMotionBlurConfiguration.DefaultRevision), "DefaultRevision"); }); } } diff --git a/tests/monotouch-test/VideoToolbox/VTMotionEstimationSessionTest.cs b/tests/monotouch-test/VideoToolbox/VTMotionEstimationSessionTest.cs index 6295817fbbe3..a8f49139e6ff 100644 --- a/tests/monotouch-test/VideoToolbox/VTMotionEstimationSessionTest.cs +++ b/tests/monotouch-test/VideoToolbox/VTMotionEstimationSessionTest.cs @@ -111,6 +111,6 @@ public void GetTypeId () { TestRuntime.AssertXcodeVersion (26, 0); - Assert.AreNotEqual (0, VTMotionEstimationSession.GetTypeId (), "GetTypeId"); + Assert.That (VTMotionEstimationSession.GetTypeId (), Is.Not.EqualTo (0), "GetTypeId"); } } diff --git a/tests/monotouch-test/VideoToolbox/VTMultiPassStorageTests.cs b/tests/monotouch-test/VideoToolbox/VTMultiPassStorageTests.cs index 01e60984aa63..92563f669e57 100644 --- a/tests/monotouch-test/VideoToolbox/VTMultiPassStorageTests.cs +++ b/tests/monotouch-test/VideoToolbox/VTMultiPassStorageTests.cs @@ -26,7 +26,7 @@ public void MultiPassStorageCreateTest () TestRuntime.AssertSystemVersion (ApplePlatform.TVOS, 10, 2, throwIfOtherPlatform: false); using (var storage = VTMultiPassStorage.Create ()) { - Assert.IsNotNull (storage, "Storage should not be null"); + Assert.That (storage, Is.Not.Null, "Storage should not be null"); } } @@ -39,7 +39,7 @@ public void MultiPassStorageCloseTest () using (var storage = VTMultiPassStorage.Create ()) { var result = storage.Close (); - Assert.IsTrue (result == VTStatus.Ok, "VTMultiPassStorage Close"); + Assert.That (result == VTStatus.Ok, Is.True, "VTMultiPassStorage Close"); } } } diff --git a/tests/monotouch-test/VideoToolbox/VTOpticalFlowConfigurationTest.cs b/tests/monotouch-test/VideoToolbox/VTOpticalFlowConfigurationTest.cs index 58fa9115ef4b..aa3a88cb8d4b 100644 --- a/tests/monotouch-test/VideoToolbox/VTOpticalFlowConfigurationTest.cs +++ b/tests/monotouch-test/VideoToolbox/VTOpticalFlowConfigurationTest.cs @@ -3,6 +3,8 @@ #if __MACOS__ +using System.Linq; + using AVFoundation; using CoreMedia; using CoreVideo; @@ -33,10 +35,10 @@ public void Properties () Assert.That (VTOpticalFlowConfiguration.ProcessorSupported, Is.True, "ProcessorSupported"); Assert.That (VTOpticalFlowConfiguration.SupportedRevisions, Is.Not.Null, "SupportedRevisions"); - Assert.That (VTOpticalFlowConfiguration.SupportedRevisions, Does.Contain (VTOpticalFlowConfigurationRevision.Revision1), "SupportedRevisions.Contains"); + Assert.That (VTOpticalFlowConfiguration.SupportedRevisions.Contains (VTOpticalFlowConfigurationRevision.Revision1), "SupportedRevisions.Contains"); Assert.That (VTOpticalFlowConfiguration.WeakSupportedRevisions, Is.Not.Null, "WeakSupportedRevisions"); - Assert.That (VTOpticalFlowConfiguration.WeakSupportedRevisions, Does.Contain ((nuint) 1), "WeakSupportedRevisions.Contains"); - Assert.That (Enum.GetValues (), Does.Contain (VTOpticalFlowConfiguration.DefaultRevision), "DefaultRevision"); + Assert.That (VTOpticalFlowConfiguration.WeakSupportedRevisions.Contains ((nuint) 1), "WeakSupportedRevisions.Contains"); + Assert.That (Enum.GetValues ().Contains (VTOpticalFlowConfiguration.DefaultRevision), "DefaultRevision"); }); } } diff --git a/tests/monotouch-test/VideoToolbox/VTPixelRotationSessionTests.cs b/tests/monotouch-test/VideoToolbox/VTPixelRotationSessionTests.cs index d606ad5e52dd..0e7578118b20 100644 --- a/tests/monotouch-test/VideoToolbox/VTPixelRotationSessionTests.cs +++ b/tests/monotouch-test/VideoToolbox/VTPixelRotationSessionTests.cs @@ -30,7 +30,7 @@ public class VTPixelRotationSessionTests { public void CreateTest () { using var session = VTPixelRotationSession.Create (); - Assert.IsNotNull (session, "Session should not be null"); + Assert.That (session, Is.Not.Null, "Session should not be null"); } [Test] @@ -41,10 +41,10 @@ public void RotateImageTest () using var destinationPixelBuffer = new CVPixelBuffer (480, 640, CVPixelFormatType.CV420YpCbCr8BiPlanarFullRange); var result = session.SetProperty (VTPixelRotationPropertyKeys.Rotation, VTRotation.ClockwiseNinety.GetConstant ()); - Assert.AreEqual (result, VTStatus.Ok, "SetProperty"); + Assert.That (VTStatus.Ok, Is.EqualTo (result), "SetProperty"); result = session.RotateImage (sourcePixelBuffer, destinationPixelBuffer); - Assert.AreEqual (result, VTStatus.Ok, "RotateImage"); + Assert.That (VTStatus.Ok, Is.EqualTo (result), "RotateImage"); } [Test] @@ -55,7 +55,7 @@ public void SetRotationPropertiesTest () Rotation = VTRotation.ClockwiseNinety }); - Assert.AreEqual (result, VTStatus.Ok, "SetRotationProperties"); + Assert.That (VTStatus.Ok, Is.EqualTo (result), "SetRotationProperties"); } } } diff --git a/tests/monotouch-test/VideoToolbox/VTPixelTransferSessionTests.cs b/tests/monotouch-test/VideoToolbox/VTPixelTransferSessionTests.cs index 48e0a3ec96ef..c92832b2ac66 100644 --- a/tests/monotouch-test/VideoToolbox/VTPixelTransferSessionTests.cs +++ b/tests/monotouch-test/VideoToolbox/VTPixelTransferSessionTests.cs @@ -30,7 +30,7 @@ public class VTPixelTransferSessionTests { public void PixelTransferSessionCreateTest () { using var session = VTPixelTransferSession.Create (); - Assert.IsNotNull (session, "Session should not be null"); + Assert.That (session, Is.Not.Null, "Session should not be null"); } [Test] @@ -40,7 +40,7 @@ public void PixelTransferSessionTransferImageTest () using var sourcePixelBuffer = new CVPixelBuffer (640, 480, CVPixelFormatType.CV420YpCbCr8BiPlanarFullRange); using var destinationPixelBuffer = new CVPixelBuffer (320, 240, CVPixelFormatType.CV420YpCbCr8BiPlanarFullRange); var result = session.TransferImage (sourcePixelBuffer, destinationPixelBuffer); - Assert.AreEqual (result, VTStatus.Ok, "TransferImage"); + Assert.That (VTStatus.Ok, Is.EqualTo (result), "TransferImage"); } [Test] @@ -51,7 +51,7 @@ public void SetTransferPropertiesTest () ScalingMode = VTScalingMode.Letterbox }); - Assert.AreEqual (result, VTStatus.Ok, "SetTransferProperties"); + Assert.That (VTStatus.Ok, Is.EqualTo (result), "SetTransferProperties"); } } } diff --git a/tests/monotouch-test/VideoToolbox/VTRawProcessingSessionTest.cs b/tests/monotouch-test/VideoToolbox/VTRawProcessingSessionTest.cs index 30dacac1e34d..52d1c65251b0 100644 --- a/tests/monotouch-test/VideoToolbox/VTRawProcessingSessionTest.cs +++ b/tests/monotouch-test/VideoToolbox/VTRawProcessingSessionTest.cs @@ -31,11 +31,11 @@ public void Create_NSDictionary_Test () using var pixelBuffer = new CVPixelBuffer (720, 480, CVPixelFormatType.CV422YpCbCr8BiPlanarFullRange); using var desc = CMVideoFormatDescription.CreateForImageBuffer (pixelBuffer, out var fde); - Assert.IsNotNull (desc, "Desc"); - Assert.AreEqual (CMFormatDescriptionError.None, fde, "vdf error"); + Assert.That (desc, Is.Not.Null, "Desc"); + Assert.That (fde, Is.EqualTo (CMFormatDescriptionError.None), "vdf error"); using var session = VTRawProcessingSession.Create (desc, (NSDictionary) null, (NSDictionary) null, out var vtStatus); // I have not been able to figure out what kind of CMVideoFormatDescription is needed to create a VTRawProcessingSession. - Assert.AreEqual (VTStatus.CouldNotCreateInstance, vtStatus, "status"); + Assert.That (vtStatus, Is.EqualTo (VTStatus.CouldNotCreateInstance), "status"); } [Test] @@ -45,11 +45,11 @@ public void Create_CVPixelBufferAttributes_Test () using var pixelBuffer = new CVPixelBuffer (480, 360, CVPixelFormatType.CV422YpCbCr8BiPlanarFullRange); using var desc = CMVideoFormatDescription.CreateForImageBuffer (pixelBuffer, out var fde); - Assert.IsNotNull (desc, "Desc"); - Assert.AreEqual (CMFormatDescriptionError.None, fde, "vdf error"); + Assert.That (desc, Is.Not.Null, "Desc"); + Assert.That (fde, Is.EqualTo (CMFormatDescriptionError.None), "vdf error"); using var session = VTRawProcessingSession.Create (desc, (CVPixelBufferAttributes) null, (VTRawProcessingParameters) null, out var vtStatus); // I have not been able to figure out what kind of CMVideoFormatDescription is needed to create a VTRawProcessingSession. - Assert.AreEqual (VTStatus.CouldNotCreateInstance, vtStatus, "status"); + Assert.That (vtStatus, Is.EqualTo (VTStatus.CouldNotCreateInstance), "status"); } [Test] @@ -57,7 +57,7 @@ public void GetTypeId () { TestRuntime.AssertXcodeVersion (16, 0); - Assert.AreNotEqual (0, VTRawProcessingSession.GetTypeId (), "GetTypeId"); + Assert.That (VTRawProcessingSession.GetTypeId (), Is.Not.EqualTo (0), "GetTypeId"); } [Test] @@ -67,10 +67,10 @@ public void ProcessingTest () using var pixelBuffer = new CVPixelBuffer (20, 10, CVPixelFormatType.CV24RGB); using var desc = CMVideoFormatDescription.CreateForImageBuffer (pixelBuffer, out var fde); - Assert.IsNotNull (desc, "Desc"); - Assert.AreEqual (CMFormatDescriptionError.None, fde, "vdf error"); + Assert.That (desc, Is.Not.Null, "Desc"); + Assert.That (fde, Is.EqualTo (CMFormatDescriptionError.None), "vdf error"); using var session = VTRawProcessingSession.Create (desc, (CVPixelBufferAttributes) null, (VTRawProcessingParameters) null, out var vtStatus); - Assert.AreEqual (VTStatus.CouldNotCreateInstance, vtStatus, "Create status"); + Assert.That (vtStatus, Is.EqualTo (VTStatus.CouldNotCreateInstance), "Create status"); // I have not been able to figure out what kind of CMVideoFormatDescription // is needed to successfully create a VTRawProcessingSession, @@ -81,18 +81,18 @@ public void ProcessingTest () // }); // var parameters = session.CopyProcessingParameters (out vtStatus); - // Assert.AreEqual (VTStatus.Ok, vtStatus, "CopyProcessingParameters status"); - // Assert.IsNotNull (parameters, "Parameters"); + // Assert.That (vtStatus, Is.EqualTo (VTStatus.Ok), "CopyProcessingParameters status"); + // Assert.That (parameters, Is.Not.Null, "Parameters"); // Console.WriteLine (parameters); // var prms = session.ProcessingParameters; - // Assert.IsNotNull (prms, "ProcessingParameters"); + // Assert.That (prms, Is.Not.Null, "ProcessingParameters"); // Console.WriteLine (prms); // vtStatus = session.SetProcessingParameters (new NSDictionary ()); - // Assert.AreEqual (VTStatus.Ok, vtStatus, "SetProcessingParameters status"); + // Assert.That (vtStatus, Is.EqualTo (VTStatus.Ok), "SetProcessingParameters status"); // vtStatus = session.SetProcessingParameters (new VTRawProcessingParameters ()); - // Assert.AreEqual (VTStatus.Ok, vtStatus, "SetProcessingParameters status (VTRawProcessingParameter)"); + // Assert.That (vtStatus, Is.EqualTo (VTStatus.Ok), "SetProcessingParameters status (VTRawProcessingParameter)"); // session.ProcessFrame (pixelBuffer, (NSDictionary) null, (VTStatus status, CVPixelBuffer? processedPixelBuffer) => // { diff --git a/tests/monotouch-test/VideoToolbox/VTUtilitiesTests.cs b/tests/monotouch-test/VideoToolbox/VTUtilitiesTests.cs index 0f2c6a59b4ee..4892802b92bd 100644 --- a/tests/monotouch-test/VideoToolbox/VTUtilitiesTests.cs +++ b/tests/monotouch-test/VideoToolbox/VTUtilitiesTests.cs @@ -56,15 +56,15 @@ public void ToCGImageTest () pxbuffer.Unlock (CVPixelBufferLock.None); } - Assert.NotNull (pxbuffer, "VTUtilitiesTests.ToCGImageTest pxbuffer should not be null"); + Assert.That (pxbuffer, Is.Not.Null, "VTUtilitiesTests.ToCGImageTest pxbuffer should not be null"); CGImage newImage; var newImageStatus = pxbuffer.ToCGImage (out newImage); Assert.That (newImageStatus == VTStatus.Ok, "VTUtilitiesTests.ToCGImageTest must be ok"); - Assert.NotNull (newImage, "VTUtilitiesTests.ToCGImageTest pxbuffer should not be newImage"); - Assert.AreEqual (originalCGImage.Width, newImage.Width, "VTUtilitiesTests.ToCGImageTest"); - Assert.AreEqual (originalCGImage.Height, newImage.Height, "VTUtilitiesTests.ToCGImageTest"); + Assert.That (newImage, Is.Not.Null, "VTUtilitiesTests.ToCGImageTest pxbuffer should not be newImage"); + Assert.That (newImage.Width, Is.EqualTo (originalCGImage.Width), "VTUtilitiesTests.ToCGImageTest"); + Assert.That (newImage.Height, Is.EqualTo (originalCGImage.Height), "VTUtilitiesTests.ToCGImageTest"); var retainCount = CFGetRetainCount (newImage.Handle); Assert.That (retainCount, Is.EqualTo (1), "RetainCount"); @@ -122,11 +122,11 @@ public void CopyVideoDecoderExtensionPropertiesTest (CMVideoCodecType codecType) TestRuntime.AssertXcodeVersion (16, 0); using var desc = CMFormatDescription.Create (CMMediaType.Video, (uint) codecType, out var fde); - Assert.IsNotNull (desc, "CMFormatDescription"); + Assert.That (desc, Is.Not.Null, "CMFormatDescription"); Assert.That (fde, Is.EqualTo (CMFormatDescriptionError.None), "CMFormatDescriptionError #2 (authorized)"); using var dict = VTUtilities.CopyVideoDecoderExtensionProperties (desc, out var vtError); Assert.That (vtError, Is.EqualTo (VTStatus.CouldNotFindVideoDecoder).Or.EqualTo (VTStatus.CouldNotFindExtensionErr), "VTError"); - Assert.IsNull (dict, "CopyVideoDecoderExtensionProperties"); + Assert.That (dict, Is.Null, "CopyVideoDecoderExtensionProperties"); // I have not been able to figure out what kind of CMVideoFormatDescription is needed for CopyVideoDecoderExtensionProperties to work, // so I can't test that case. @@ -140,10 +140,10 @@ public void CopyRawVideoDecoderExtensionPropertiesTest (CMVideoCodecType codecTy using var desc = CMFormatDescription.Create (CMMediaType.Video, (uint) codecType, out var fde); Assert.That (fde, Is.EqualTo (CMFormatDescriptionError.None), "CMFormatDescriptionError #2 (authorized)"); - Assert.IsNotNull (desc, "CMFormatDescription"); + Assert.That (desc, Is.Not.Null, "CMFormatDescription"); using var dict = VTUtilities.CopyRawProcessorExtensionProperties (desc, out var vtError); Assert.That (vtError, Is.EqualTo (VTStatus.CouldNotCreateInstance).Or.EqualTo (VTStatus.CouldNotFindExtensionErr), "VTError"); - Assert.IsNull (dict, "CopyRawProcessorExtensionProperties"); + Assert.That (dict, Is.Null, "CopyRawProcessorExtensionProperties"); // I have not been able to figure out what kind of CMVideoFormatDescription is needed for VTRawProcessingSession, // so I can't test the case where a CMFormatDescription is handled. diff --git a/tests/monotouch-test/VideoToolbox/VTVideoEncoderListTests.cs b/tests/monotouch-test/VideoToolbox/VTVideoEncoderListTests.cs index d87cb235598f..6a0e3109e404 100644 --- a/tests/monotouch-test/VideoToolbox/VTVideoEncoderListTests.cs +++ b/tests/monotouch-test/VideoToolbox/VTVideoEncoderListTests.cs @@ -26,7 +26,7 @@ public void VideoEncoderListTest () TestRuntime.AssertSystemVersion (ApplePlatform.TVOS, 10, 2, throwIfOtherPlatform: false); var encoders = VTVideoEncoder.GetEncoderList (); - Assert.NotNull (encoders, "VTVideoEncoder.GetEncoderList () Should Not be null"); + Assert.That (encoders, Is.Not.Null, "VTVideoEncoder.GetEncoderList () Should Not be null"); } [Test] @@ -35,7 +35,7 @@ public void SupportedEncoderPropertiesTest () TestRuntime.AssertXcodeVersion (9, 0); var props = VTVideoEncoder.GetSupportedEncoderProperties (1920, 1080, CMVideoCodecType.H264); - Assert.NotNull (props, "props should Not be null"); + Assert.That (props, Is.Not.Null, "props should Not be null"); } } } diff --git a/tests/monotouch-test/Vision/VNCircleTests.cs b/tests/monotouch-test/Vision/VNCircleTests.cs index 43d0d87918de..8759455bd77f 100644 --- a/tests/monotouch-test/Vision/VNCircleTests.cs +++ b/tests/monotouch-test/Vision/VNCircleTests.cs @@ -25,10 +25,10 @@ public class VNCircleTests { public void CreateUsingRadiusTest () { var circle = VNCircle.CreateUsingRadius (new VNPoint (10, 10), radius: 10); - Assert.NotNull (circle, "Circle not null"); - Assert.AreEqual (circle.Radius, 10, "Radius"); - Assert.AreEqual (circle.Center.X, 10, "X"); - Assert.AreEqual (circle.Center.Y, 10, "Y"); + Assert.That (circle, Is.Not.Null, "Circle not null"); + Assert.That (circle.Radius, Is.EqualTo (10), "Radius"); + Assert.That (circle.Center.X, Is.EqualTo (10), "X"); + Assert.That (circle.Center.Y, Is.EqualTo (10), "Y"); Assert.That (circle.RetainCount, Is.EqualTo ((nuint) 1), "RetainCount"); } @@ -36,10 +36,10 @@ public void CreateUsingRadiusTest () public void CreateUsingDiameterTest () { var circle = VNCircle.CreateUsingDiameter (new VNPoint (5, 6), diameter: 7); - Assert.NotNull (circle, "Circle not null"); - Assert.AreEqual (circle.Diameter, 7, "Diameter"); - Assert.AreEqual (circle.Center.Y, 6, "Y"); - Assert.AreEqual (circle.Center.X, 5, "X"); + Assert.That (circle, Is.Not.Null, "Circle not null"); + Assert.That (circle.Diameter, Is.EqualTo (7), "Diameter"); + Assert.That (circle.Center.Y, Is.EqualTo (6), "Y"); + Assert.That (circle.Center.X, Is.EqualTo (5), "X"); Assert.That (circle.RetainCount, Is.EqualTo ((nuint) 1), "RetainCount"); } @@ -47,10 +47,10 @@ public void CreateUsingDiameterTest () public void CreateUsingRadiusCtorTest () { using var circle = new VNCircle (new VNPoint (10, 10), radiusOrDiameter: 10, option: VNCircleInitializationOption.Radius); - Assert.NotNull (circle, "Circle not null"); - Assert.AreEqual (circle.Radius, 10, "Radius"); - Assert.AreEqual (circle.Center.X, 10, "X"); - Assert.AreEqual (circle.Center.Y, 10, "Y"); + Assert.That (circle, Is.Not.Null, "Circle not null"); + Assert.That (circle.Radius, Is.EqualTo (10), "Radius"); + Assert.That (circle.Center.X, Is.EqualTo (10), "X"); + Assert.That (circle.Center.Y, Is.EqualTo (10), "Y"); Assert.That (circle.RetainCount, Is.EqualTo ((nuint) 1), "RetainCount"); } @@ -58,10 +58,10 @@ public void CreateUsingRadiusCtorTest () public void CreateUsingDiameterCtorTest () { using var circle = new VNCircle (new VNPoint (5, 6), radiusOrDiameter: 7, option: VNCircleInitializationOption.Diameter); - Assert.NotNull (circle, "Circle not null"); - Assert.AreEqual (circle.Diameter, 7, "Diameter"); - Assert.AreEqual (circle.Center.Y, 6, "Y"); - Assert.AreEqual (circle.Center.X, 5, "X"); + Assert.That (circle, Is.Not.Null, "Circle not null"); + Assert.That (circle.Diameter, Is.EqualTo (7), "Diameter"); + Assert.That (circle.Center.Y, Is.EqualTo (6), "Y"); + Assert.That (circle.Center.X, Is.EqualTo (5), "X"); Assert.That (circle.RetainCount, Is.EqualTo ((nuint) 1), "RetainCount"); } diff --git a/tests/monotouch-test/Vision/VNGeometryUtilsTests.cs b/tests/monotouch-test/Vision/VNGeometryUtilsTests.cs index 19bb7254e2a2..fa0d5e0e9888 100644 --- a/tests/monotouch-test/Vision/VNGeometryUtilsTests.cs +++ b/tests/monotouch-test/Vision/VNGeometryUtilsTests.cs @@ -34,8 +34,8 @@ public void CreateBoundingCircleTest () }; var ncircle = VNGeometryUtils.CreateBoundingCircle (nvectors, out var nerror); - Assert.Null (nerror, "nerror was not null"); - Assert.NotNull (ncircle, "ncircle was null"); + Assert.That (nerror, Is.Null, "nerror was not null"); + Assert.That (ncircle, Is.Not.Null, "ncircle was null"); var vectors = new [] { new Vector2 (1,1), @@ -45,11 +45,11 @@ public void CreateBoundingCircleTest () }; var circle = VNGeometryUtils.CreateBoundingCircle (vectors, out var error); - Assert.Null (error, "Error was not null"); - Assert.NotNull (circle, "circle was null"); + Assert.That (error, Is.Null, "Error was not null"); + Assert.That (circle, Is.Not.Null, "circle was null"); - Assert.AreEqual (ncircle.Diameter, circle.Diameter, "Diameter"); - Assert.AreEqual (ncircle.Radius, circle.Radius, "Radius"); + Assert.That (circle.Diameter, Is.EqualTo (ncircle.Diameter), "Diameter"); + Assert.That (circle.Radius, Is.EqualTo (ncircle.Radius), "Radius"); } } } diff --git a/tests/monotouch-test/Vision/VNGetCameraRelativePositionTest.cs b/tests/monotouch-test/Vision/VNGetCameraRelativePositionTest.cs index 9685f82c7e01..31f46b797ef9 100644 --- a/tests/monotouch-test/Vision/VNGetCameraRelativePositionTest.cs +++ b/tests/monotouch-test/Vision/VNGetCameraRelativePositionTest.cs @@ -39,14 +39,14 @@ public void GetCameraRelativePositionTest () var request = new VNDetectHumanBodyPose3DRequest (); var didPerform = requestHandler.Perform (new VNRequest [] { request }, out NSError error); - Assert.Null (error, $"VNImageRequestHandler.Perform should not return an error {error}"); + Assert.That (error, Is.Null, $"VNImageRequestHandler.Perform should not return an error {error}"); var observation = request.Results?.Length > 0 ? request.Results [0] : null; if (TestRuntime.IsDevice && observation is null) Assert.Ignore ("This test fails sometimes on device."); // maybe it requires camera access? - Assert.NotNull (observation, "VNImageRequestHandler.Perform should return a result."); + Assert.That (observation, Is.Not.Null, "VNImageRequestHandler.Perform should return a result."); Matrix4 expectedMatrix = new Matrix4 ( (float) -0.98357517, (float) 0.014054606, (float) -0.17995091, (float) 0.012865879, @@ -55,7 +55,7 @@ public void GetCameraRelativePositionTest () (float) 0, (float) 0, (float) 0, (float) 1); var position = observation.GetCameraRelativePosition (out var modelPositionOut, VNHumanBodyPose3DObservationJointName.CenterHead, out NSError observationError); - Assert.Null (observationError, $"GetCameraRelativePosition should not return an error {observationError}"); + Assert.That (observationError, Is.Null, $"GetCameraRelativePosition should not return an error {observationError}"); // GetCameraRelativePosition results can vary slightly between runs so we need to use a delta. Asserts.AreEqual (expectedMatrix, modelPositionOut, 0.5f, "VNVector3DGetCameraRelativePosition result is not equal to expected matrix"); } diff --git a/tests/monotouch-test/Vision/VNRequestGetResultsTest.cs b/tests/monotouch-test/Vision/VNRequestGetResultsTest.cs index e8350f1056f5..305acdbe7b20 100644 --- a/tests/monotouch-test/Vision/VNRequestGetResultsTest.cs +++ b/tests/monotouch-test/Vision/VNRequestGetResultsTest.cs @@ -21,7 +21,7 @@ public void GetResults_BeforePerform_ReturnsNull () using var request = new VNDetectFaceRectanglesRequest ((request, error) => { }); var results = request.GetResults (); - Assert.IsNull (results, "GetResults/before-perform"); + Assert.That (results, Is.Null, "GetResults/before-perform"); } [Test] @@ -42,7 +42,7 @@ public void GetResults_AfterPerform () // Results may be empty but should not be null after performing var results = request.GetResults (); - Assert.IsNotNull (results, "GetResults/after-perform"); + Assert.That (results, Is.Not.Null, "GetResults/after-perform"); } } } diff --git a/tests/monotouch-test/Vision/VNRequestTests.cs b/tests/monotouch-test/Vision/VNRequestTests.cs index 1a443c3ee87c..039efc774b30 100644 --- a/tests/monotouch-test/Vision/VNRequestTests.cs +++ b/tests/monotouch-test/Vision/VNRequestTests.cs @@ -121,62 +121,62 @@ public void VNSupportedRevisionsUnsupportedTest () var rect = new CGRect (0, 0, 10, 10); { var detectedObjectObservation = VNDetectedObjectObservation.FromBoundingBox (VNDetectedObjectObservationRequestRevision.Unspecified, rect); - Assert.NotNull (detectedObjectObservation, "detectedObjectObservation is null"); + Assert.That (detectedObjectObservation, Is.Not.Null, "detectedObjectObservation is null"); Assert.That (detectedObjectObservation.BoundingBox, Is.EqualTo (rect)); var faceObservation = VNFaceObservation.FromBoundingBox (VNFaceObservationRequestRevision.Unspecified, rect); - Assert.NotNull (faceObservation, "faceObservation is null"); + Assert.That (faceObservation, Is.Not.Null, "faceObservation is null"); Assert.That (faceObservation.BoundingBox, Is.EqualTo (rect)); var recognizedObjectObservation = VNRecognizedObjectObservation.FromBoundingBox (VNRecognizedObjectObservationRequestRevision.Unspecified, rect); if (TestRuntime.CheckXcodeVersion (11, 0) && !TestRuntime.CheckXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch)) { - Assert.IsNull (recognizedObjectObservation, "recognizedObjectObservation is not null"); + Assert.That (recognizedObjectObservation, Is.Null, "recognizedObjectObservation is not null"); } else { - Assert.NotNull (recognizedObjectObservation, "recognizedObjectObservation is null"); + Assert.That (recognizedObjectObservation, Is.Not.Null, "recognizedObjectObservation is null"); Assert.That (recognizedObjectObservation.BoundingBox, Is.EqualTo (rect)); } var rectangleObservation = VNRectangleObservation.FromBoundingBox (VNRectangleObservationRequestRevision.Unspecified, rect); - Assert.NotNull (rectangleObservation, "rectangleObservation is null"); + Assert.That (rectangleObservation, Is.Not.Null, "rectangleObservation is null"); Assert.That (rectangleObservation.BoundingBox, Is.EqualTo (rect)); var textObservation = VNTextObservation.FromBoundingBox (VNTextObservationRequestRevision.Unspecified, rect); - Assert.NotNull (textObservation, "textObservation is null"); + Assert.That (textObservation, Is.Not.Null, "textObservation is null"); Assert.That (textObservation.BoundingBox, Is.EqualTo (rect)); var barcodeObservation = VNBarcodeObservation.FromBoundingBox (VNBarcodeObservationRequestRevision.Unspecified, rect); - Assert.NotNull (barcodeObservation, "barcodeObservation is null"); + Assert.That (barcodeObservation, Is.Not.Null, "barcodeObservation is null"); Assert.That (barcodeObservation.BoundingBox, Is.EqualTo (rect)); } // Tests random request revision { var detectedObjectObservation = VNDetectedObjectObservation.FromBoundingBox ((VNDetectedObjectObservationRequestRevision) 5000, rect); - Assert.NotNull (detectedObjectObservation, "randomRevision detectedObjectObservation is null"); + Assert.That (detectedObjectObservation, Is.Not.Null, "randomRevision detectedObjectObservation is null"); Assert.That (detectedObjectObservation.BoundingBox, Is.EqualTo (rect)); var faceObservation = VNFaceObservation.FromBoundingBox ((VNFaceObservationRequestRevision) 5000, rect); - Assert.NotNull (faceObservation, "randomRevision faceObservation is null"); + Assert.That (faceObservation, Is.Not.Null, "randomRevision faceObservation is null"); Assert.That (faceObservation.BoundingBox, Is.EqualTo (rect)); var recognizedObjectObservation = VNRecognizedObjectObservation.FromBoundingBox ((VNRecognizedObjectObservationRequestRevision) 5000, rect); if (TestRuntime.CheckXcodeVersion (11, 0) && !TestRuntime.CheckXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch)) { - Assert.IsNull (recognizedObjectObservation, "randomRevision recognizedObjectObservation is null"); + Assert.That (recognizedObjectObservation, Is.Null, "randomRevision recognizedObjectObservation is null"); } else { - Assert.NotNull (recognizedObjectObservation, "randomRevision recognizedObjectObservation is null"); + Assert.That (recognizedObjectObservation, Is.Not.Null, "randomRevision recognizedObjectObservation is null"); Assert.That (recognizedObjectObservation.BoundingBox, Is.EqualTo (rect)); } var rectangleObservation = VNRectangleObservation.FromBoundingBox ((VNRectangleObservationRequestRevision) 5000, rect); - Assert.NotNull (rectangleObservation, "randomRevision rectangleObservation is null"); + Assert.That (rectangleObservation, Is.Not.Null, "randomRevision rectangleObservation is null"); Assert.That (rectangleObservation.BoundingBox, Is.EqualTo (rect)); var textObservation = VNTextObservation.FromBoundingBox ((VNTextObservationRequestRevision) 5000, rect); - Assert.NotNull (textObservation, "randomRevision textObservation is null"); + Assert.That (textObservation, Is.Not.Null, "randomRevision textObservation is null"); Assert.That (textObservation.BoundingBox, Is.EqualTo (rect)); var barcodeObservation = VNBarcodeObservation.FromBoundingBox ((VNBarcodeObservationRequestRevision) 5000, rect); - Assert.NotNull (barcodeObservation, "randomRevision barcodeObservation is null"); + Assert.That (barcodeObservation, Is.Not.Null, "randomRevision barcodeObservation is null"); Assert.That (barcodeObservation.BoundingBox, Is.EqualTo (rect)); } } @@ -188,31 +188,31 @@ public void VNSupportedRevisionsTwoTest () var rect = new CGRect (0, 0, 10, 10); { var detectedObjectObservation = VNDetectedObjectObservation.FromBoundingBox (VNDetectedObjectObservationRequestRevision.Two, rect); - Assert.NotNull (detectedObjectObservation, "detectedObjectObservation is null"); + Assert.That (detectedObjectObservation, Is.Not.Null, "detectedObjectObservation is null"); Assert.That (detectedObjectObservation.BoundingBox, Is.EqualTo (rect)); var faceObservation = VNFaceObservation.FromBoundingBox (VNFaceObservationRequestRevision.Two, rect); - Assert.NotNull (faceObservation, "faceObservation is null"); + Assert.That (faceObservation, Is.Not.Null, "faceObservation is null"); Assert.That (faceObservation.BoundingBox, Is.EqualTo (rect)); var recognizedObjectObservation = VNRecognizedObjectObservation.FromBoundingBox (VNRecognizedObjectObservationRequestRevision.Two, rect); if (TestRuntime.CheckXcodeVersion (11, 0) && !TestRuntime.CheckXcodeVersion (12, TestRuntime.MinorXcode12APIMismatch)) { - Assert.Null (recognizedObjectObservation, "recognizedObjectObservation is null"); + Assert.That (recognizedObjectObservation, Is.Null, "recognizedObjectObservation is null"); } else { - Assert.NotNull (recognizedObjectObservation, "recognizedObjectObservation is null"); + Assert.That (recognizedObjectObservation, Is.Not.Null, "recognizedObjectObservation is null"); Assert.That (recognizedObjectObservation.BoundingBox, Is.EqualTo (rect)); } var rectangleObservation = VNRectangleObservation.FromBoundingBox (VNRectangleObservationRequestRevision.Two, rect); - Assert.NotNull (rectangleObservation, "rectangleObservation is null"); + Assert.That (rectangleObservation, Is.Not.Null, "rectangleObservation is null"); Assert.That (rectangleObservation.BoundingBox, Is.EqualTo (rect)); var textObservation = VNTextObservation.FromBoundingBox (VNTextObservationRequestRevision.Two, rect); - Assert.NotNull (textObservation, "textObservation is null"); + Assert.That (textObservation, Is.Not.Null, "textObservation is null"); Assert.That (textObservation.BoundingBox, Is.EqualTo (rect)); var barcodeObservation = VNBarcodeObservation.FromBoundingBox (VNBarcodeObservationRequestRevision.Two, rect); - Assert.NotNull (barcodeObservation, "barcodeObservation is null"); + Assert.That (barcodeObservation, Is.Not.Null, "barcodeObservation is null"); Assert.That (barcodeObservation.BoundingBox, Is.EqualTo (rect)); } } diff --git a/tests/monotouch-test/Vision/VNUtilsTests.cs b/tests/monotouch-test/Vision/VNUtilsTests.cs index c9d5959d6535..de7c0fad7ab8 100644 --- a/tests/monotouch-test/Vision/VNUtilsTests.cs +++ b/tests/monotouch-test/Vision/VNUtilsTests.cs @@ -61,10 +61,10 @@ public void GetNormalizedFaceBoundingBoxPointTest () [Test] public void IsIdentityTest () { - Assert.True (VNUtils.IsIdentityRect (new CGRect (0, 0, 1, 1)), "Identity"); - Assert.False (VNUtils.IsIdentityRect (new CGRect (0, 0, 2, 2)), "Not Identity A"); - Assert.False (VNUtils.IsIdentityRect (new CGRect (1, 1, 1, 1)), "Not Identity B"); - Assert.False (VNUtils.IsIdentityRect (new CGRect (1, 1, 0, 0)), "Not Identity C"); + Assert.That (VNUtils.IsIdentityRect (new CGRect (0, 0, 1, 1)), Is.True, "Identity"); + Assert.That (VNUtils.IsIdentityRect (new CGRect (0, 0, 2, 2)), Is.False, "Not Identity A"); + Assert.That (VNUtils.IsIdentityRect (new CGRect (1, 1, 1, 1)), Is.False, "Not Identity B"); + Assert.That (VNUtils.IsIdentityRect (new CGRect (1, 1, 0, 0)), Is.False, "Not Identity C"); } } diff --git a/tests/monotouch-test/Vision/VNVectorTests.cs b/tests/monotouch-test/Vision/VNVectorTests.cs index d2448455f453..7f91b9cd3bad 100644 --- a/tests/monotouch-test/Vision/VNVectorTests.cs +++ b/tests/monotouch-test/Vision/VNVectorTests.cs @@ -25,9 +25,9 @@ public class VNVectorTests { public void VNVectorCreateTest () { var vector = VNVector.Create (r: 10, theta: 0.5); - Assert.NotNull (vector, "vector not null"); - Assert.AreEqual (vector.R, 10, "R"); - Assert.AreEqual (vector.Theta, 0.5, "Theta"); + Assert.That (vector, Is.Not.Null, "vector not null"); + Assert.That (vector.R, Is.EqualTo (10), "R"); + Assert.That (0.5, Is.EqualTo (vector.Theta), "Theta"); Assert.That (vector.RetainCount, Is.EqualTo ((nuint) 1), "RetainCount"); } @@ -35,9 +35,9 @@ public void VNVectorCreateTest () public void VNVectorCtorTest () { using var vector = new VNVector ((R: 10, Theta: 0.5)); - Assert.NotNull (vector, "vector not null"); - Assert.AreEqual (vector.R, 10, "R"); - Assert.AreEqual (vector.Theta, 0.5, "Theta"); + Assert.That (vector, Is.Not.Null, "vector not null"); + Assert.That (vector.R, Is.EqualTo (10), "R"); + Assert.That (0.5, Is.EqualTo (vector.Theta), "Theta"); Assert.That (vector.RetainCount, Is.EqualTo ((nuint) 1), "RetainCount"); } } diff --git a/tests/monotouch-test/WebKit/NSAttributedStringCatagoryTest.cs b/tests/monotouch-test/WebKit/NSAttributedStringCatagoryTest.cs index 56e0aa453618..a1c3a813de0f 100644 --- a/tests/monotouch-test/WebKit/NSAttributedStringCatagoryTest.cs +++ b/tests/monotouch-test/WebKit/NSAttributedStringCatagoryTest.cs @@ -38,7 +38,7 @@ public void LoadHtmlAsync_NSUrl () completed = true; } }, () => completed); - Assert.True (completed, "completed"); + Assert.That (completed, Is.True, "completed"); } } } diff --git a/tests/monotouch-test/dotnet/shared.csproj b/tests/monotouch-test/dotnet/shared.csproj index 37437089b7fe..989a89db0bef 100644 --- a/tests/monotouch-test/dotnet/shared.csproj +++ b/tests/monotouch-test/dotnet/shared.csproj @@ -39,24 +39,25 @@ $(NoWarn);CS8002 - - - true - Nullable - - + + - - - + + + + + + + + @@ -238,11 +239,11 @@ - Contents/Resources/ + Contents/Resources/ - + <_SmeltingSdk Condition="'$(_PlatformName)' == 'iOS'">iphoneos <_SmeltingSdk Condition="'$(_PlatformName)' == 'tvOS'">appletvos diff --git a/tests/monotouch-test/mono/Symbols.cs b/tests/monotouch-test/mono/Symbols.cs index b66f5acb0800..0c06fefc5af9 100644 --- a/tests/monotouch-test/mono/Symbols.cs +++ b/tests/monotouch-test/mono/Symbols.cs @@ -26,7 +26,7 @@ public void FunctionNames () } } - Assert.IsTrue (aot || interp || llvmonly || nativeaot, $"#1\n\t{string.Join ("\n\t", symbols)}"); + Assert.That (aot || interp || llvmonly || nativeaot, Is.True, $"#1\n\t{string.Join ("\n\t", symbols)}"); } void Collect () diff --git a/tests/monotouch-test/mono/bug18634.cs b/tests/monotouch-test/mono/bug18634.cs index 93e9bd4c481d..372f50eb56a1 100644 --- a/tests/monotouch-test/mono/bug18634.cs +++ b/tests/monotouch-test/mono/bug18634.cs @@ -31,7 +31,7 @@ public void Bug18632 () return true; }).Subscribe (new AnonymousObserver ()); - Assert.IsTrue (hit, "The second CombineLatest callback wasn't called."); + Assert.That (hit, Is.True, "The second CombineLatest callback wasn't called."); } class QueryLanguage : IQueryLanguage { diff --git a/tests/monotouch-test/mono/bug26989.cs b/tests/monotouch-test/mono/bug26989.cs index 32b7fe7a873a..559d6dd6b0b0 100644 --- a/tests/monotouch-test/mono/bug26989.cs +++ b/tests/monotouch-test/mono/bug26989.cs @@ -9,7 +9,7 @@ public partial class MonoRuntimeTests { public void Bug26989 () { strlen ("abc"); - Assert.AreEqual ("ChocolateCookie", cookie); + Assert.That (cookie, Is.EqualTo ("ChocolateCookie")); } [DllImport (Constants.libcLibrary)] diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/AssemblySetup.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/AssemblySetup.cs index db3cb3520b67..5059aab86236 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/AssemblySetup.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/AssemblySetup.cs @@ -17,7 +17,7 @@ public void AssemblyInitialization () const string msbuild_exe_path = "/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/msbuild/15.0/bin/MSBuild.dll"; if (is_in_vsmac) { var env = new Dictionary { - { "MD_APPLE_SDK_ROOT", Path.GetDirectoryName (Path.GetDirectoryName (Configuration.xcode_root)) ?? string.Empty }, + { "DEVELOPER_DIR", Path.GetDirectoryName (Path.GetDirectoryName (Configuration.xcode_root)) ?? string.Empty }, { "MSBUILD_EXE_PATH", msbuild_exe_path }, }; diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ACToolTaskTest.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ACToolTaskTest.cs index ef806c289d0a..218b3cf4fa9e 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ACToolTaskTest.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ACToolTaskTest.cs @@ -22,9 +22,9 @@ ACTool CreateACToolTask (ApplePlatform platform, string projectDir, out string i intermediateOutputPath = Cache.CreateTemporaryDirectory (); - var sdk = Sdks.GetAppleSdk (platform); + var task = CreateTask (); + var version = AppleSdkVersion.UseDefault.ToString (); - var root = sdk.GetSdkPath (version, false); string sdkPlatform; var uiDeviceFamily = ""; @@ -47,7 +47,6 @@ ACTool CreateACToolTask (ApplePlatform platform, string projectDir, out string i throw new NotImplementedException (platform.ToString ()); } - var task = CreateTask (); task.ImageAssets = imageAssets .Select (v => { var spl = v.Split ('|'); @@ -92,10 +91,10 @@ public void DefaultAppIcons (ApplePlatform platform) var actool = CreateACToolTaskWithResources (platform); ExecuteTask (actool); - Assert.IsNotNull (actool.PartialAppManifest, "PartialAppManifest"); + Assert.That (actool.PartialAppManifest, Is.Not.Null, "PartialAppManifest"); var appIconsManifestPath = actool.PartialAppManifest?.ItemSpec ?? ""; - var appIconsManifest = PDictionary.FromFile (appIconsManifestPath)!; - Assert.AreEqual (0, appIconsManifest.Count, $"Partial plist contents: {actool.PartialAppManifest?.ItemSpec}"); + var appIconsManifest = PDictionary.OpenFile (appIconsManifestPath); + Assert.That (appIconsManifest.Count, Is.EqualTo (0), $"Partial plist contents: {actool.PartialAppManifest?.ItemSpec}"); var expectedXml = """ @@ -120,7 +119,7 @@ public void AllAppIcons (ApplePlatform platform) ExecuteTask (actool); - Assert.IsNotNull (actool.PartialAppManifest, "PartialAppManifest"); + Assert.That (actool.PartialAppManifest, Is.Not.Null, "PartialAppManifest"); var appIconsManifestPath = actool.PartialAppManifest?.ItemSpec ?? ""; string expectedXml; @@ -168,7 +167,7 @@ public void AllAppIconsWithAppIcon (ApplePlatform platform) ExecuteTask (actool); - Assert.IsNotNull (actool.PartialAppManifest, "PartialAppManifest"); + Assert.That (actool.PartialAppManifest, Is.Not.Null, "PartialAppManifest"); var appIconsManifestPath = actool.PartialAppManifest?.ItemSpec!; string expectedXml; @@ -293,7 +292,7 @@ public void AppIcon (ApplePlatform platform) ExecuteTask (actool); - Assert.IsNotNull (actool.PartialAppManifest, "PartialAppManifest"); + Assert.That (actool.PartialAppManifest, Is.Not.Null, "PartialAppManifest"); var appIconsManifestPath = actool.PartialAppManifest?.ItemSpec ?? ""; string expectedXml; @@ -390,7 +389,7 @@ public void AppIconAndAlternateIcons (ApplePlatform platform) ExecuteTask (actool); - Assert.IsNotNull (actool.PartialAppManifest, "PartialAppManifest"); + Assert.That (actool.PartialAppManifest, Is.Not.Null, "PartialAppManifest"); var appIconsManifestPath = actool.PartialAppManifest?.ItemSpec ?? ""; string expectedXml; @@ -575,7 +574,7 @@ public void InexistentAppIcon (ApplePlatform platform) default: throw new NotImplementedException (platform.ToString ()); } - Assert.AreEqual (expectedErrorMessage, Engine.Logger.ErrorEvents [0].Message, "Error message"); + Assert.That (Engine.Logger.ErrorEvents [0].Message, Is.EqualTo (expectedErrorMessage), "Error message"); } [Test] @@ -602,7 +601,7 @@ public void InexistentAlternateIcons (ApplePlatform platform) default: throw new NotImplementedException (platform.ToString ()); } - Assert.AreEqual (expectedErrorMessage, Engine.Logger.ErrorEvents [0].Message, "Error message"); + Assert.That (Engine.Logger.ErrorEvents [0].Message, Is.EqualTo (expectedErrorMessage), "Error message"); } [Test] @@ -617,7 +616,7 @@ public void BothAlternateAndMainIcon (ApplePlatform platform) actool.AppIcon = "AppIcons"; ExecuteTask (actool, 1); - Assert.AreEqual ($"The image resource '{actool.AppIcon}' is specified as both 'AppIcon' and 'AlternateAppIcon'.", Engine.Logger.ErrorEvents [0].Message, "Error message"); + Assert.That (Engine.Logger.ErrorEvents [0].Message, Is.EqualTo ($"The image resource '{actool.AppIcon}' is specified as both 'AppIcon' and 'AlternateAppIcon'."), "Error message"); } [Test] @@ -632,7 +631,217 @@ public void XSAppIconAssetsAndAppIcon (ApplePlatform platform) actool.XSAppIconAssets = "Resources/Images.xcassets/AppIcons.appiconset"; ExecuteTask (actool, 1); - Assert.AreEqual ("Can't specify both 'XSAppIconAssets' in the Info.plist and 'AppIcon' in the project file. Please select one or the other.", Engine.Logger.ErrorEvents [0].Message, "Error message"); + Assert.That (Engine.Logger.ErrorEvents [0].Message, Is.EqualTo ("Can't specify both 'XSAppIconAssets' in the Info.plist and 'AppIcon' in the project file. Please select one or the other."), "Error message"); + } + + [Test] + [TestCase (ApplePlatform.iOS)] + [TestCase (ApplePlatform.TVOS)] + [TestCase (ApplePlatform.MacCatalyst)] + [TestCase (ApplePlatform.MacOSX)] + public void IconFileSupport (ApplePlatform platform) + { + // Test that .icon folders (Icon Composer format) are recognized as app icons + var projectDir = Cache.CreateTemporaryDirectory (); + var iconFolderPath = Path.Combine (projectDir, "Resources", "AppIcon.icon"); + var assetsPath = Path.Combine (iconFolderPath, "Assets"); + Directory.CreateDirectory (assetsPath); + + // Create a placeholder icon.json file (simplified structure for testing) + var iconJsonPath = Path.Combine (iconFolderPath, "icon.json"); + File.WriteAllText (iconJsonPath, @"{""groups"":[{""layers"":[{""image-name"":""icon_512x512.png"",""name"":""icon""}]}]}"); + + // Create a placeholder image file in the Assets folder + var imagePath = Path.Combine (assetsPath, "icon_512x512.png"); + File.WriteAllText (imagePath, "placeholder image"); + + var actool = CreateACToolTask ( + platform, + projectDir, + out var _, + iconJsonPath + "|Resources/AppIcon.icon/icon.json", + imagePath + "|Resources/AppIcon.icon/Assets/icon_512x512.png" + ); + actool.AppIcon = "AppIcon"; + + // actool may fail on the placeholder .icon content, but the validation phase should pass + actool.Execute (); + + // Verify that no icon validation errors were logged + AssertNoIconValidationErrors (); + } + + [Test] + [TestCase (ApplePlatform.iOS)] + [TestCase (ApplePlatform.TVOS)] + [TestCase (ApplePlatform.MacCatalyst)] + [TestCase (ApplePlatform.MacOSX)] + public void IconFileSupportWithIncludeAllAppIcons (ApplePlatform platform) + { + // Test that .icon folders work with IncludeAllAppIcons + var projectDir = Cache.CreateTemporaryDirectory (); + var iconFolderPath = Path.Combine (projectDir, "Resources", "AppIcon.icon"); + var assetsPath = Path.Combine (iconFolderPath, "Assets"); + Directory.CreateDirectory (assetsPath); + + var iconJsonPath = Path.Combine (iconFolderPath, "icon.json"); + File.WriteAllText (iconJsonPath, @"{""groups"":[{""layers"":[{""image-name"":""icon_512x512.png"",""name"":""icon""}]}]}"); + + var imagePath = Path.Combine (assetsPath, "icon_512x512.png"); + File.WriteAllText (imagePath, "placeholder image"); + + var actool = CreateACToolTask ( + platform, + projectDir, + out var _, + iconJsonPath + "|Resources/AppIcon.icon/icon.json", + imagePath + "|Resources/AppIcon.icon/Assets/icon_512x512.png" + ); + actool.AppIcon = "AppIcon"; + actool.IncludeAllAppIcons = true; + + // actool may fail on the placeholder .icon content, but the validation phase should pass + actool.Execute (); + + // Verify that no icon validation errors were logged + AssertNoIconValidationErrors (); + } + + [Test] + [TestCase (ApplePlatform.iOS)] + [TestCase (ApplePlatform.TVOS)] + [TestCase (ApplePlatform.MacCatalyst)] + [TestCase (ApplePlatform.MacOSX)] + public void IconFileSupportAsAlternateIcon (ApplePlatform platform) + { + // Test that .icon folders work as alternate app icons + var projectDir = Cache.CreateTemporaryDirectory (); + var iconFolderPath = Path.Combine (projectDir, "Resources", "AlternateIcon.icon"); + var assetsPath = Path.Combine (iconFolderPath, "Assets"); + Directory.CreateDirectory (assetsPath); + + var iconJsonPath = Path.Combine (iconFolderPath, "icon.json"); + File.WriteAllText (iconJsonPath, @"{""groups"":[{""layers"":[{""image-name"":""icon_512x512.png"",""name"":""icon""}]}]}"); + + var imagePath = Path.Combine (assetsPath, "icon_512x512.png"); + File.WriteAllText (imagePath, "placeholder image"); + + // Also need a primary icon for the alternate icon test to make sense + var primaryIconPath = Path.Combine (projectDir, "Resources", "AppIcon.icon"); + var primaryAssetsPath = Path.Combine (primaryIconPath, "Assets"); + Directory.CreateDirectory (primaryAssetsPath); + + var primaryIconJsonPath = Path.Combine (primaryIconPath, "icon.json"); + File.WriteAllText (primaryIconJsonPath, @"{""groups"":[{""layers"":[{""image-name"":""icon_512x512.png"",""name"":""icon""}]}]}"); + + var primaryImagePath = Path.Combine (primaryAssetsPath, "icon_512x512.png"); + File.WriteAllText (primaryImagePath, "placeholder image"); + + var actool = CreateACToolTask ( + platform, + projectDir, + out var _, + iconJsonPath + "|Resources/AlternateIcon.icon/icon.json", + imagePath + "|Resources/AlternateIcon.icon/Assets/icon_512x512.png", + primaryIconJsonPath + "|Resources/AppIcon.icon/icon.json", + primaryImagePath + "|Resources/AppIcon.icon/Assets/icon_512x512.png" + ); + actool.AppIcon = "AppIcon"; + actool.AlternateAppIcons = new ITaskItem [] { new TaskItem ("AlternateIcon") }; + + // actool may fail on the placeholder .icon content, but the validation phase should pass + actool.Execute (); + + // Verify that no icon validation errors were logged + AssertNoIconValidationErrors (); + } + + [Test] + [TestCase (ApplePlatform.iOS)] + [TestCase (ApplePlatform.TVOS)] + [TestCase (ApplePlatform.MacCatalyst)] + [TestCase (ApplePlatform.MacOSX)] + public void InexistentIconFile (ApplePlatform platform) + { + // Test that an inexistent .icon-based app icon is correctly reported + var projectDir = Cache.CreateTemporaryDirectory (); + var iconFolderPath = Path.Combine (projectDir, "Resources", "AppIcon.icon"); + var assetsPath = Path.Combine (iconFolderPath, "Assets"); + Directory.CreateDirectory (assetsPath); + + var iconJsonPath = Path.Combine (iconFolderPath, "icon.json"); + File.WriteAllText (iconJsonPath, @"{""groups"":[{""layers"":[{""image-name"":""icon_512x512.png"",""name"":""icon""}]}]}"); + + var imagePath = Path.Combine (assetsPath, "icon_512x512.png"); + File.WriteAllText (imagePath, "placeholder image"); + + var actool = CreateACToolTask ( + platform, + projectDir, + out var _, + iconJsonPath + "|Resources/AppIcon.icon/icon.json", + imagePath + "|Resources/AppIcon.icon/Assets/icon_512x512.png" + ); + actool.AppIcon = "InexistentIcon"; + + ExecuteTask (actool, 1); + + var errorMessages = Engine.Logger.ErrorEvents.Select (e => e.Message).ToList (); + Assert.That (errorMessages.Any (m => m?.Contains ("Can't find the AppIcon 'InexistentIcon'") == true), Is.True, "Should report that InexistentIcon is not found among image resources"); + } + + [Test] + [TestCase (ApplePlatform.iOS)] + [TestCase (ApplePlatform.MacCatalyst)] + [TestCase (ApplePlatform.MacOSX)] + public void MixedXCAssetsAndIconFile (ApplePlatform platform) + { + // Test that .icon folders and .xcassets can coexist in the validation phase + var projectDir = Path.Combine (Configuration.SourceRoot, "tests", "dotnet", "AppWithXCAssets", platform.AsString ()); + var files = Directory.GetFiles (Path.Combine (projectDir, "Resources", "Images.xcassets"), "*", SearchOption.AllDirectories); + var imageAssets = files.Select (v => v + "|" + v.Substring (projectDir.Length + 1)).ToList (); + + // Add a .icon folder alongside the existing .xcassets + var tmpDir = Cache.CreateTemporaryDirectory (); + var iconFolderPath = Path.Combine (tmpDir, "ComposerIcon.icon"); + var assetsPath = Path.Combine (iconFolderPath, "Assets"); + Directory.CreateDirectory (assetsPath); + + var iconJsonPath = Path.Combine (iconFolderPath, "icon.json"); + File.WriteAllText (iconJsonPath, @"{""groups"":[{""layers"":[{""image-name"":""icon_512x512.png"",""name"":""icon""}]}]}"); + + var imagePath = Path.Combine (assetsPath, "icon_512x512.png"); + File.WriteAllText (imagePath, "placeholder image"); + + imageAssets.Add (iconJsonPath + "|Resources/ComposerIcon.icon/icon.json"); + imageAssets.Add (imagePath + "|Resources/ComposerIcon.icon/Assets/icon_512x512.png"); + + var actool = CreateACToolTask ( + platform, + projectDir, + out var _, + imageAssets.ToArray () + ); + actool.AppIcon = "AppIcons"; + + // actool may fail on the placeholder .icon content, but the validation phase should pass + actool.Execute (); + + // Verify that no icon validation errors were logged + AssertNoIconValidationErrors (); + } + + void AssertNoIconValidationErrors () + { + var errorMessages = Engine.Logger.ErrorEvents.Select (e => e.Message).ToList (); + Assert.That (errorMessages, Has.None.Contain ("Can't find the AppIcon"), + "Should not report that AppIcon is not found among image resources"); + Assert.That (errorMessages, Has.None.Contain ("Can't find the AlternateAppIcon"), + "Should not report that AlternateAppIcon is not found among image resources"); + Assert.That (errorMessages, Has.None.Contain ("is specified as both 'AppIcon' and 'AlternateAppIcon'"), + "Should not report icon conflict between AppIcon and AlternateAppIcon"); + Assert.That (errorMessages, Has.None.Contain ("Can't specify both 'XSAppIconAssets'"), + "Should not report XSAppIconAssets conflict"); } } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/BundleResourceTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/BundleResourceTests.cs index d005250d7603..58c9eb2aba3d 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/BundleResourceTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/BundleResourceTests.cs @@ -38,8 +38,7 @@ class ResourceTask : Task, IHasSessionId, IHasProjectDir { public void GetVirtualProjectPathTest () { Assert.Multiple (() => { - Assert.AreEqual ("Archer_Attack.atlas/archer_attack_0001.png", - BundleResource.GetVirtualProjectPath ( + Assert.That (BundleResource.GetVirtualProjectPath ( new ResourceTask { BuildEngine = new TestEngine (), ProjectDir = "/Users/rolf/work/maccore/windows/xamarin-macios/tests/dotnet/LibraryWithResources/iOS", @@ -48,11 +47,9 @@ public void GetVirtualProjectPathTest () "../Archer_Attack.atlas/archer_attack_0001.png", localMSBuildProjectFullPath: "/Users/rolf/work/maccore/windows/xamarin-macios/tests/dotnet/LibraryWithResources/shared.csproj", localDefiningProjectFullPath: "/Users/rolf/work/maccore/windows/xamarin-macios/tests/dotnet/LibraryWithResources/shared.csproj" - )), - "A"); + )), Is.EqualTo ("Archer_Attack.atlas/archer_attack_0001.png"), "A"); - Assert.AreEqual ("Archer_Attack.atlas/archer_attack_0001.png", - BundleResource.GetVirtualProjectPath ( + Assert.That (BundleResource.GetVirtualProjectPath ( new ResourceTask { BuildEngine = new TestEngine (), ProjectDir = "C:/src/xamarin-macios/tests/dotnet/LibraryWithResources/iOS", @@ -62,8 +59,7 @@ public void GetVirtualProjectPathTest () "../Archer_Attack.atlas/archer_attack_0001.png", localMSBuildProjectFullPath: @"C:\src\xamarin-macios\tests\dotnet\LibraryWithResources\shared.csproj", localDefiningProjectFullPath: @"C:\src\xamarin-macios\tests\dotnet\LibraryWithResources\shared.csproj" - )), - "B"); + )), Is.EqualTo ("Archer_Attack.atlas/archer_attack_0001.png"), "B"); }); } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CollectITunesArtworkTaskTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CollectITunesArtworkTaskTests.cs index 7237be4e39d7..14b75f2f1a4c 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CollectITunesArtworkTaskTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CollectITunesArtworkTaskTests.cs @@ -69,10 +69,10 @@ public void Valid (string extension) }; ExecuteTask (task); - Assert.AreEqual (2, task.ITunesArtworkWithLogicalNames.Length, "ITunesArtworkWithLogicalNames.Count"); + Assert.That (task.ITunesArtworkWithLogicalNames.Length, Is.EqualTo (2), "ITunesArtworkWithLogicalNames.Count"); for (var i = 0; i < task.ITunesArtworkWithLogicalNames.Length; i++) { - Assert.AreEqual (Path.GetFileNameWithoutExtension (task.ITunesArtwork [i].GetMetadata ("FullPath")), task.ITunesArtworkWithLogicalNames [i].GetMetadata ("LogicalName"), $"LogicalName #{i}"); - Assert.AreEqual ("false", task.ITunesArtworkWithLogicalNames [i].GetMetadata ("Optimize"), $"Optimize #{i}"); + Assert.That (task.ITunesArtworkWithLogicalNames [i].GetMetadata ("LogicalName"), Is.EqualTo (Path.GetFileNameWithoutExtension (task.ITunesArtwork [i].GetMetadata ("FullPath"))), $"LogicalName #{i}"); + Assert.That (task.ITunesArtworkWithLogicalNames [i].GetMetadata ("Optimize"), Is.EqualTo ("false"), $"Optimize #{i}"); } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CompileAppManifestTaskTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CompileAppManifestTaskTests.cs index 17f5f44f93ad..e07a1d80c94d 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CompileAppManifestTaskTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CompileAppManifestTaskTests.cs @@ -20,11 +20,11 @@ CompileAppManifest CreateTask (string? tmpdir = null, ApplePlatform platform = A var task = CreateTask (); task.AppBundleName = "AppBundleName"; task.CompiledAppManifest = new TaskItem (Path.Combine (tmpdir, "TemporaryAppManifest.plist")); - task.DefaultSdkVersion = Sdks.GetAppleSdk (platform).GetInstalledSdkVersions (false).First ().ToString ()!; task.MinSupportedOSPlatformVersion = "10.0"; task.SupportedOSPlatformVersion = "15.0"; task.SdkVersion = task.DefaultSdkVersion ?? string.Empty; task.TargetFrameworkMoniker = TargetFramework.GetTargetFramework (platform).ToString (); + task.DefaultSdkVersion = task.CurrentSdk.GetInstalledSdkVersions (false).First ().ToString ()!; return task; } @@ -45,8 +45,8 @@ public void MainMinimumOSVersions () ExecuteTask (task); - var plist = PDictionary.FromFile (task.CompiledAppManifest!.ItemSpec)!; - Assert.AreEqual ("14.0", plist.GetMinimumOSVersion (), "MinimumOSVersion"); + var plist = PDictionary.OpenFile (task.CompiledAppManifest!.ItemSpec); + Assert.That (plist.GetMinimumOSVersion (), Is.EqualTo ("14.0"), "MinimumOSVersion"); } [Test] @@ -72,8 +72,8 @@ public void MultipleMinimumOSVersions () ExecuteTask (task); - var plist = PDictionary.FromFile (task.CompiledAppManifest!.ItemSpec)!; - Assert.AreEqual ("13.0", plist.GetMinimumOSVersion (), "MinimumOSVersion"); + var plist = PDictionary.OpenFile (task.CompiledAppManifest!.ItemSpec); + Assert.That (plist.GetMinimumOSVersion (), Is.EqualTo ("13.0"), "MinimumOSVersion"); } [Test] @@ -102,8 +102,8 @@ public void MultipleMinimumOSVersions_Overwrite (bool overwrite, string expected ExecuteTask (task); - var plist = PDictionary.FromFile (task.CompiledAppManifest!.ItemSpec)!; - Assert.AreEqual (expectedMinimumOSVersion, plist.GetMinimumOSVersion (), "MinimumOSVersion"); + var plist = PDictionary.OpenFile (task.CompiledAppManifest!.ItemSpec); + Assert.That (plist.GetMinimumOSVersion (), Is.EqualTo (expectedMinimumOSVersion), "MinimumOSVersion"); } [Test] @@ -120,7 +120,7 @@ public void ErrorWithMismatchedInfoPlistMinimumOSVersion () task.SupportedOSPlatformVersion = "11.0"; ExecuteTask (task, expectedErrorCount: 1); - Assert.AreEqual ("The MinimumOSVersion value in the Info.plist (10.0) does not match the SupportedOSPlatformVersion value (11.0) in the project file (if there is no SupportedOSPlatformVersion value in the project file, then a default value has been assumed). Either change the value in the Info.plist to match the SupportedOSPlatformVersion value, or remove the value in the Info.plist (and add a SupportedOSPlatformVersion value to the project file if it doesn't already exist).", Engine.Logger.ErrorEvents [0].Message); + Assert.That (Engine.Logger.ErrorEvents [0].Message, Is.EqualTo ("The MinimumOSVersion value in the Info.plist (10.0) does not match the SupportedOSPlatformVersion value (11.0) in the project file (if there is no SupportedOSPlatformVersion value in the project file, then a default value has been assumed). Either change the value in the Info.plist to match the SupportedOSPlatformVersion value, or remove the value in the Info.plist (and add a SupportedOSPlatformVersion value to the project file if it doesn't already exist).")); } [Test] @@ -133,8 +133,8 @@ public void SupportedOSPlatformVersion () ExecuteTask (task); - var plist = PDictionary.FromFile (task.CompiledAppManifest!.ItemSpec)!; - Assert.AreEqual ("11.0", plist.GetMinimumOSVersion (), "MinimumOSVersion"); + var plist = PDictionary.OpenFile (task.CompiledAppManifest!.ItemSpec); + Assert.That (plist.GetMinimumOSVersion (), Is.EqualTo ("11.0"), "MinimumOSVersion"); } [Test] @@ -144,8 +144,8 @@ public void MacCatalystVersionCheck () task.SupportedOSPlatformVersion = "14.2"; ExecuteTask (task); - var plist = PDictionary.FromFile (task.CompiledAppManifest!.ItemSpec)!; - Assert.AreEqual ("11.0", plist.GetMinimumSystemVersion (), "MinimumOSVersion"); + var plist = PDictionary.OpenFile (task.CompiledAppManifest!.ItemSpec); + Assert.That (plist.GetMinimumSystemVersion (), Is.EqualTo ("11.0"), "MinimumOSVersion"); } [Test] @@ -171,7 +171,7 @@ public void XcodeVariables (ApplePlatform platform, bool isSimulator, string exp task.SdkIsSimulator = isSimulator; ExecuteTask (task); - var plist = PDictionary.FromFile (task.CompiledAppManifest!.ItemSpec)!; + var plist = PDictionary.OpenFile (task.CompiledAppManifest!.ItemSpec); var variables = new string [] { "DTCompiler", "DTPlatformBuild", @@ -186,7 +186,7 @@ public void XcodeVariables (ApplePlatform platform, bool isSimulator, string exp var value = plist.GetString (variable)?.Value; Assert.That (value, Is.Not.Null.And.Not.Empty, variable); } - Assert.AreEqual (expectedDTPlatformName, plist.GetString ("DTPlatformName")?.Value, "Expected DTPlatformName"); + Assert.That (plist.GetString ("DTPlatformName")?.Value, Is.EqualTo (expectedDTPlatformName), "Expected DTPlatformName"); } } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CompileEntitlementsTaskTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CompileEntitlementsTaskTests.cs index 25e61039c696..2165a3f632ff 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CompileEntitlementsTaskTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CompileEntitlementsTaskTests.cs @@ -115,7 +115,7 @@ void ExecuteAndCheckValidationErrors (Task task, params string [] expectedMessag expectedCode = expectedMessage [0..6]; expectedMessage = expectedMessage [7..]; } - Assert.AreEqual (expectedMessage, buildEvents [i].Message, $"Error message #{i + 1}"); + Assert.That (buildEvents [i].Message, Is.EqualTo (expectedMessage), $"Error message #{i + 1}"); if (expectedCode is not null) { string actualCode; if (buildEvents [i] is BuildErrorEventArgs beea) { @@ -139,17 +139,17 @@ public void ValidateEntitlement () "The app requests the entitlement 'com.apple.developer.pass-type-identifiers', but the provisioning profile 'iOS Team Provisioning Profile: *' doesn't contain this entitlement.", "The app requests the entitlement 'com.apple.developer.ubiquity-kvstore-identifier', but the provisioning profile 'iOS Team Provisioning Profile: *' doesn't contain this entitlement."); - var compiled = PDictionary.FromFile (compiledEntitlements)!; - Assert.IsTrue (compiled.Get (EntitlementKeys.GetTaskAllow)?.Value, "#1"); - Assert.AreEqual ("32UV7A8CDE.com.xamarin.MySingleView", compiled.Get ("application-identifier")?.Value, "#2"); - Assert.AreEqual ("Z8CSQKJE7R", compiled.Get ("com.apple.developer.team-identifier")?.Value, "#3"); - Assert.AreEqual ("applinks:*.xamarin.com", compiled.GetAssociatedDomains ().ToStringArray ().First (), "#4"); - Assert.AreEqual ("Z8CSQKJE7R.*", compiled.GetPassBookIdentifiers ().ToStringArray ().First (), "#5"); - Assert.AreEqual ("Z8CSQKJE7R.com.xamarin.MySingleView", compiled.GetUbiquityKeyValueStore (), "#6"); - Assert.AreEqual ("32UV7A8CDE.com.xamarin.MySingleView", compiled.GetKeychainAccessGroups ().ToStringArray ().First (), "#7"); + var compiled = PDictionary.OpenFile (compiledEntitlements); + Assert.That (compiled.Get (EntitlementKeys.GetTaskAllow)?.Value, Is.True, "#1"); + Assert.That (compiled.Get ("application-identifier")?.Value, Is.EqualTo ("32UV7A8CDE.com.xamarin.MySingleView"), "#2"); + Assert.That (compiled.Get ("com.apple.developer.team-identifier")?.Value, Is.EqualTo ("Z8CSQKJE7R"), "#3"); + Assert.That (compiled.GetAssociatedDomains ().ToStringArray ().First (), Is.EqualTo ("applinks:*.xamarin.com"), "#4"); + Assert.That (compiled.GetPassBookIdentifiers ().ToStringArray ().First (), Is.EqualTo ("Z8CSQKJE7R.*"), "#5"); + Assert.That (compiled.GetUbiquityKeyValueStore (), Is.EqualTo ("Z8CSQKJE7R.com.xamarin.MySingleView"), "#6"); + Assert.That (compiled.GetKeychainAccessGroups ().ToStringArray ().First (), Is.EqualTo ("32UV7A8CDE.com.xamarin.MySingleView"), "#7"); var archived = PDictionary.FromFile (archivedEntitlements); - Assert.IsTrue (compiled.ContainsKey ("application-identifier"), "archived"); + Assert.That (compiled.ContainsKey ("application-identifier"), Is.True, "archived"); } [TestCase ("Invalid", null, "Unknown type 'Invalid' for the entitlement 'com.xamarin.custom.entitlement' specified in the CustomEntitlements item group. Expected 'Remove', 'Boolean', 'String', or 'StringArray'.")] @@ -172,7 +172,7 @@ public void InvalidCustomEntitlements (string type, string? value, string errorM task.CustomEntitlements = customEntitlements; task.ProvisioningProfile = GetResourcePath ("WildCardMacAppDevelopment.provisionprofile"); ExecuteTask (task, expectedErrorCount: 1); - Assert.AreEqual (errorMessage, Engine.Logger.ErrorEvents [0].Message, "Error message"); + Assert.That (Engine.Logger.ErrorEvents [0].Message, Is.EqualTo (errorMessage), "Error message"); } [Test] @@ -193,9 +193,9 @@ public void CustomEntitlemements_String (string value) task.CustomEntitlements = customEntitlements; task.ProvisioningProfile = GetResourcePath ("WildCardMacAppDevelopment.provisionprofile"); ExecuteTask (task); - var compiled = PDictionary.FromFile (compiledEntitlements)!; - Assert.AreEqual (value ?? string.Empty, compiled.GetString ("com.xamarin.custom.entitlement")?.Value, "#1"); - Assert.IsTrue (Engine.Logger.MessageEvents.Any (v => v.Message?.Contains ("The app requests the entitlement 'com.xamarin.custom.entitlement', but provisioning profile WildCardMacAppDevelopment does not grant this entitlement. This is probably not OK.") == true), "custom entitlement"); + var compiled = PDictionary.OpenFile (compiledEntitlements); + Assert.That (compiled.GetString ("com.xamarin.custom.entitlement")?.Value, Is.EqualTo (value ?? string.Empty), "#1"); + Assert.That (Engine.Logger.MessageEvents.Any (v => v.Message?.Contains ("The app requests the entitlement 'com.xamarin.custom.entitlement', but provisioning profile WildCardMacAppDevelopment does not grant this entitlement. This is probably not OK.") == true), Is.True, "custom entitlement"); } [Test] @@ -214,11 +214,11 @@ public void CustomEntitlemements_StringArray () task.ProvisioningProfile = GetResourcePath ("WildCardMacAppDevelopment.provisionprofile"); task.CustomEntitlements = customEntitlements; ExecuteTask (task); - var compiled = PDictionary.FromFile (compiledEntitlements)!; + var compiled = PDictionary.OpenFile (compiledEntitlements); var array = compiled.GetArray ("com.xamarin.custom.entitlement"); - Assert.NotNull (array, "array"); - Assert.AreEqual (new string [] { "A", "B", "C" }, array.ToStringArray (), "array contents"); - Assert.IsTrue (Engine.Logger.MessageEvents.Any (v => v.Message?.Contains ("The app requests the entitlement 'com.xamarin.custom.entitlement', but provisioning profile WildCardMacAppDevelopment does not grant this entitlement. This is probably not OK.") == true), "custom entitlement"); + Assert.That (array, Is.Not.Null, "array"); + Assert.That (array.ToStringArray (), Is.EqualTo (new string [] { "A", "B", "C" }), "array contents"); + Assert.That (Engine.Logger.MessageEvents.Any (v => v.Message?.Contains ("The app requests the entitlement 'com.xamarin.custom.entitlement', but provisioning profile WildCardMacAppDevelopment does not grant this entitlement. This is probably not OK.") == true), Is.True, "custom entitlement"); } [Test] @@ -239,10 +239,10 @@ public void CustomEntitlemements_StringArray_CustomSeparator (string separator) task.CustomEntitlements = customEntitlements; task.ProvisioningProfile = GetResourcePath ("WildCardMacAppDevelopment.provisionprofile"); ExecuteTask (task); - var compiled = PDictionary.FromFile (compiledEntitlements)!; + var compiled = PDictionary.OpenFile (compiledEntitlements); var array = compiled.GetArray ("com.xamarin.custom.entitlement"); - Assert.NotNull (array, "array"); - Assert.AreEqual (new string [] { "A;B;C", "D", "E" }, array.ToStringArray (), "array contents"); + Assert.That (array, Is.Not.Null, "array"); + Assert.That (array.ToStringArray (), Is.EqualTo (new string [] { "A;B;C", "D", "E" }), "array contents"); } [Test] @@ -252,8 +252,8 @@ public void AllowJit_Default () task.TargetFrameworkMoniker = ".NETCoreApp,Version=v6.0,Profile=maccatalyst"; task.ProvisioningProfile = GetResourcePath ("WildCardMacAppDevelopment.provisionprofile"); ExecuteTask (task); - var compiled = PDictionary.FromFile (compiledEntitlements)!; - Assert.IsFalse (compiled.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), "#1"); + var compiled = PDictionary.OpenFile (compiledEntitlements); + Assert.That (compiled.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), Is.False, "#1"); } [Test] @@ -267,9 +267,9 @@ public void AllowJit_True () task.ProvisioningProfile = GetResourcePath ("WildCardMacAppDevelopment.provisionprofile"); task.CustomEntitlements = customEntitlements; ExecuteTask (task); - var compiled = PDictionary.FromFile (compiledEntitlements)!; - Assert.IsTrue (compiled.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), "#1"); - Assert.IsTrue (compiled.Get (EntitlementKeys.AllowExecutionOfJitCode)?.Value, "#2"); + var compiled = PDictionary.OpenFile (compiledEntitlements); + Assert.That (compiled.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), Is.True, "#1"); + Assert.That (compiled.Get (EntitlementKeys.AllowExecutionOfJitCode)?.Value, Is.True, "#2"); } [Test] @@ -283,9 +283,9 @@ public void AllowJit_False () task.ProvisioningProfile = GetResourcePath ("WildCardMacAppDevelopment.provisionprofile"); task.CustomEntitlements = customEntitlements; ExecuteTask (task); - var compiled = PDictionary.FromFile (compiledEntitlements)!; - Assert.IsTrue (compiled.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), "#1"); - Assert.IsFalse (compiled.Get (EntitlementKeys.AllowExecutionOfJitCode)?.Value, "#2"); + var compiled = PDictionary.OpenFile (compiledEntitlements); + Assert.That (compiled.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), Is.True, "#1"); + Assert.That (compiled.Get (EntitlementKeys.AllowExecutionOfJitCode)?.Value, Is.False, "#2"); Assert.That (archivedEntitlements, Does.Not.Exist, "No archived entitlements"); } @@ -301,8 +301,8 @@ public void AllowJit_None () task.ProvisioningProfile = GetResourcePath ("WildCardMacAppDevelopment.provisionprofile"); task.CustomEntitlements = customEntitlements; ExecuteTask (task); - var compiled = PDictionary.FromFile (compiledEntitlements)!; - Assert.IsFalse (compiled.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), "#1"); + var compiled = PDictionary.OpenFile (compiledEntitlements); + Assert.That (compiled.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), Is.False, "#1"); } [Test] @@ -315,13 +315,13 @@ public void AppIdentifierPrefix () task.TargetFrameworkMoniker = ".NETCoreApp,Version=v6.0,Profile=ios"; task.CustomEntitlements = customEntitlements; ExecuteTask (task); - var compiled = PDictionary.FromFile (compiledEntitlements)!; - Assert.IsFalse (compiled.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), "#1"); + var compiled = PDictionary.OpenFile (compiledEntitlements); + Assert.That (compiled.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), Is.False, "#1"); var kag = ((PString?) compiled ["keychain-access-groups"])?.Value; Assert.That (kag, Is.EqualTo ("32UV7A8CDE.org.xamarin"), "value 1"); var archived = PDictionary.FromFile (archivedEntitlements)!; - Assert.IsTrue (archived.ContainsKey ("keychain-access-groups"), "archived"); + Assert.That (archived.ContainsKey ("keychain-access-groups"), Is.True, "archived"); var archivedKag = ((PString?) archived ["keychain-access-groups"])?.Value; Assert.That (archivedKag, Is.EqualTo ("32UV7A8CDE.org.xamarin"), "archived value 1"); } @@ -336,13 +336,13 @@ public void TeamIdentifierPrefix () task.TargetFrameworkMoniker = ".NETCoreApp,Version=v6.0,Profile=ios"; task.CustomEntitlements = customEntitlements; ExecuteTask (task); - var compiled = PDictionary.FromFile (compiledEntitlements)!; - Assert.IsFalse (compiled.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), "#1"); + var compiled = PDictionary.OpenFile (compiledEntitlements); + Assert.That (compiled.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), Is.False, "#1"); var kag = ((PString?) compiled ["keychain-access-groups"])?.Value; Assert.That (kag, Is.EqualTo ("Z8CSQKJE7R.org.xamarin"), "value 1"); var archived = PDictionary.FromFile (archivedEntitlements)!; - Assert.IsTrue (archived.ContainsKey ("keychain-access-groups"), "archived"); + Assert.That (archived.ContainsKey ("keychain-access-groups"), Is.True, "archived"); var archivedKag = ((PString?) archived ["keychain-access-groups"])?.Value; Assert.That (archivedKag, Is.EqualTo ("Z8CSQKJE7R.org.xamarin"), "archived value 1"); } @@ -362,16 +362,16 @@ public void TeamIdentifierPrefix_Simulator () Assert.Multiple (() => { Assert.That (archivedEntitlements, Does.Not.Exist, "archived"); - var inExecutable = PDictionary.FromFile (task.EntitlementsInExecutable!.ItemSpec)!; + var inExecutable = PDictionary.OpenFile (task.EntitlementsInExecutable!.ItemSpec); Assert.That (inExecutable.Count, Is.EqualTo (4), $"in executable count"); - Assert.IsFalse (inExecutable.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), "#1"); - Assert.IsTrue (inExecutable.ContainsKey ("keychain-access-groups"), "in executable"); + Assert.That (inExecutable.ContainsKey (EntitlementKeys.AllowExecutionOfJitCode), Is.False, "#1"); + Assert.That (inExecutable.ContainsKey ("keychain-access-groups"), Is.True, "in executable"); Assert.That (((PString?) inExecutable ["keychain-access-groups"])?.Value, Is.EqualTo ("Z8CSQKJE7R.org.xamarin"), "in executable value 1"); - Assert.IsFalse (inExecutable.ContainsKey ("com.apple.security.get-task-allow"), "in executable com.apple.security.get-task-allow"); - Assert.IsTrue (inExecutable.ContainsKey ("get-task-allow"), $"in executable get-task-allow"); + Assert.That (inExecutable.ContainsKey ("com.apple.security.get-task-allow"), Is.False, "in executable com.apple.security.get-task-allow"); + Assert.That (inExecutable.ContainsKey ("get-task-allow"), Is.True, $"in executable get-task-allow"); - var inSignature = PDictionary.FromFile (task.EntitlementsInSignature!.ItemSpec)!; + var inSignature = PDictionary.OpenFile (task.EntitlementsInSignature!.ItemSpec); Assert.That (inSignature.Count, Is.EqualTo (0), $"in signature count"); }); } @@ -573,6 +573,38 @@ public void ValidateStringArrayEntitlement (string entitlement, EntitlementsMode ValidateEntitlementsImpl (platform, "error", [], mode, entitlement, "String", "InvalidValue", mobileProvision: "Apple_Signin_Test_Profile.mobileprovision"); } + // Test case inspired by https://github.com/dotnet/macios/issues/25306 + // A wallet extension requests com.apple.developer.payment-pass-provisioning, + // but the provisioning profile doesn't grant it. This should produce a + // warning/error so the developer knows why installation fails on device. + [Test] + [TestCase (EntitlementsMode.InCustomEntitlements)] + [TestCase (EntitlementsMode.InFile)] + public void ValidateEntitlements_PaymentPassProvisioningNotInProfile (EntitlementsMode mode) + { + ValidateEntitlementsImpl (ApplePlatform.iOS, "error", [ + "MT7140:The app requests the entitlement 'com.apple.developer.payment-pass-provisioning', but the provisioning profile 'iOS Team Provisioning Profile: *' doesn't contain this entitlement." + ], mode, "com.apple.developer.payment-pass-provisioning", "Boolean", "true"); + } + + [Test] + [TestCase (EntitlementsMode.InCustomEntitlements)] + [TestCase (EntitlementsMode.InFile)] + public void ValidateEntitlements_PaymentPassProvisioningNotInProfile_Warning (EntitlementsMode mode) + { + ValidateEntitlementsImpl (ApplePlatform.iOS, "warn", [ + "MT7140:The app requests the entitlement 'com.apple.developer.payment-pass-provisioning', but the provisioning profile 'iOS Team Provisioning Profile: *' doesn't contain this entitlement." + ], mode, "com.apple.developer.payment-pass-provisioning", "Boolean", "true"); + } + + [Test] + [TestCase (EntitlementsMode.InCustomEntitlements)] + [TestCase (EntitlementsMode.InFile)] + public void ValidateEntitlements_PaymentPassProvisioningNotInProfile_Disable (EntitlementsMode mode) + { + ValidateEntitlementsImpl (ApplePlatform.iOS, "disable", [], mode, "com.apple.developer.payment-pass-provisioning", "Boolean", "true"); + } + public enum EntitlementsMode { None, InFile, diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ComputeCodesignItemsTaskTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ComputeCodesignItemsTaskTests.cs index 6e964fc46e09..3c3cfff6ff63 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ComputeCodesignItemsTaskTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ComputeCodesignItemsTaskTests.cs @@ -345,7 +345,7 @@ public void Compute (ApplePlatform platform) task.NativeStripItems = nativeStripItems.ToArray (); task.TargetFrameworkMoniker = TargetFramework.GetTargetFramework (platform).ToString (); ExecuteTask (task); - Assert.AreEqual (0, Engine.Logger.WarningsEvents.Count, "Warning Count"); + Assert.That (Engine.Logger.WarningsEvents.Count, Is.EqualTo (0), "Warning Count"); VerifyCodesigningResults (infos, task.OutputCodesignItems, platform); } finally { @@ -413,7 +413,7 @@ public void Symlinks (ApplePlatform platform) task.CodesignStampPath = "codesign-stamp-path/"; task.TargetFrameworkMoniker = TargetFramework.GetTargetFramework (platform).ToString (); ExecuteTask (task); - Assert.AreEqual (0, Engine.Logger.WarningsEvents.Count, "Warning Count"); + Assert.That (Engine.Logger.WarningsEvents.Count, Is.EqualTo (0), "Warning Count"); VerifyCodesigningResults (infos, task.OutputCodesignItems, platform); } finally { @@ -494,7 +494,7 @@ public void SkipDirectories (ApplePlatform platform) task.CodesignStampPath = "codesign-stamp-path/"; task.TargetFrameworkMoniker = TargetFramework.GetTargetFramework (platform).ToString (); ExecuteTask (task); - Assert.AreEqual (0, Engine.Logger.WarningsEvents.Count, "Warning Count"); + Assert.That (Engine.Logger.WarningsEvents.Count, Is.EqualTo (0), "Warning Count"); VerifyCodesigningResults (infos, task.OutputCodesignItems, platform); } finally { @@ -557,7 +557,7 @@ public void Duplicated (ApplePlatform platform) task.CodesignStampPath = "codesign-stamp-path/"; task.TargetFrameworkMoniker = TargetFramework.GetTargetFramework (platform).ToString (); ExecuteTask (task); - Assert.AreEqual (0, Engine.Logger.WarningsEvents.Count, "Warning Count"); + Assert.That (Engine.Logger.WarningsEvents.Count, Is.EqualTo (0), "Warning Count"); VerifyCodesigningResults (infos, task.OutputCodesignItems, platform); } finally { @@ -631,10 +631,10 @@ public void DuplicatedWithDifferentMetadata (ApplePlatform platform) task.CodesignStampPath = "codesign-stamp-path/"; task.TargetFrameworkMoniker = TargetFramework.GetTargetFramework (platform).ToString (); ExecuteTask (task); - Assert.AreEqual (3, Engine.Logger.WarningsEvents.Count, "Warning Count"); - Assert.AreEqual ("Code signing has been requested multiple times for 'Bundle.app/Contents/MonoBundle/createdump', with different metadata. The metadata 'OnlyIn1=true' has been set for one item, but not the other.", Engine.Logger.WarningsEvents [0].Message, "Message #0"); - Assert.AreEqual ("Code signing has been requested multiple times for 'Bundle.app/Contents/MonoBundle/createdump', with different metadata. The metadata 'InOneAndTwoWithDifferentValues' has different values for each item (once it's '1', another time it's '2').", Engine.Logger.WarningsEvents [1].Message, "Message #1"); - Assert.AreEqual ("Code signing has been requested multiple times for 'Bundle.app/Contents/MonoBundle/createdump', with different metadata. The metadata for one are: 'CodesignStampFile, InOneAndTwoWithDifferentValues, OnlyIn1, RequireCodeSigning', while the metadata for the other are: 'CodesignStampFile, RequireCodeSigning'", Engine.Logger.WarningsEvents [2].Message, "Message #2"); + Assert.That (Engine.Logger.WarningsEvents.Count, Is.EqualTo (3), "Warning Count"); + Assert.That (Engine.Logger.WarningsEvents [0].Message, Is.EqualTo ("Code signing has been requested multiple times for 'Bundle.app/Contents/MonoBundle/createdump', with different metadata. The metadata 'OnlyIn1=true' has been set for one item, but not the other."), "Message #0"); + Assert.That (Engine.Logger.WarningsEvents [1].Message, Is.EqualTo ("Code signing has been requested multiple times for 'Bundle.app/Contents/MonoBundle/createdump', with different metadata. The metadata 'InOneAndTwoWithDifferentValues' has different values for each item (once it's '1', another time it's '2')."), "Message #1"); + Assert.That (Engine.Logger.WarningsEvents [2].Message, Is.EqualTo ("Code signing has been requested multiple times for 'Bundle.app/Contents/MonoBundle/createdump', with different metadata. The metadata for one are: 'CodesignStampFile, InOneAndTwoWithDifferentValues, OnlyIn1, RequireCodeSigning', while the metadata for the other are: 'CodesignStampFile, RequireCodeSigning'"), "Message #2"); VerifyCodesigningResults (infos, task.OutputCodesignItems, platform); } finally { diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CreateBindingResourceTaskTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CreateBindingResourceTaskTests.cs index f5d655244035..fbfdae8f49a8 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CreateBindingResourceTaskTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/CreateBindingResourceTaskTests.cs @@ -95,7 +95,7 @@ void Extract (string zipArchive, string targetDirectory) unzipArguments.Add (targetDirectory); unzipArguments.Add (zipArchive); var rv = Execution.RunAsync ("unzip", unzipArguments).Result; - Assert.AreEqual (0, rv.ExitCode, "ExitCode\n" + rv.Output.MergedOutput); + Assert.That (rv.ExitCode, Is.EqualTo (0), "ExitCode\n" + rv.Output.MergedOutput); } void AssertResourceDirectory (string directory, bool symlinks) @@ -104,22 +104,22 @@ void AssertResourceDirectory (string directory, bool symlinks) foreach (var file in allFiles) Console.WriteLine (file); if (symlinks) { - Assert.AreEqual (7, allFiles.Length, "Length"); + Assert.That (allFiles.Length, Is.EqualTo (7), "Length"); } else { - Assert.AreEqual (5, allFiles.Length, "Length"); + Assert.That (allFiles.Length, Is.EqualTo (5), "Length"); } - Assert.AreEqual ("ABCDEFGHIJKLMAAA", File.ReadAllText (Path.Combine (directory, "A.txt")), "A.txt"); - Assert.AreEqual ("ABCDEFGHIJKLMBBB", File.ReadAllText (Path.Combine (directory, "B.txt")), "B.txt"); - Assert.AreEqual ("ABCDEFGHIJKLMCCC", File.ReadAllText (Path.Combine (directory, "C.framework/C.txt")), "C.txt"); + Assert.That (File.ReadAllText (Path.Combine (directory, "A.txt")), Is.EqualTo ("ABCDEFGHIJKLMAAA"), "A.txt"); + Assert.That (File.ReadAllText (Path.Combine (directory, "B.txt")), Is.EqualTo ("ABCDEFGHIJKLMBBB"), "B.txt"); + Assert.That (File.ReadAllText (Path.Combine (directory, "C.framework/C.txt")), Is.EqualTo ("ABCDEFGHIJKLMCCC"), "C.txt"); if (symlinks) { var linkToCPath = Path.Combine (directory, "C.framework/LinkToC.txt"); - Assert.AreEqual ("ABCDEFGHIJKLMCCC", File.ReadAllText (linkToCPath), "LinkToC.txt"); - Assert.IsTrue (PathUtils.IsSymlink (linkToCPath), "LinkToC.txt - IsSymlink"); - Assert.AreEqual ("C.txt", PathUtils.GetSymlinkTarget (linkToCPath), "LinkToC.txt - IsSymlink target"); + Assert.That (File.ReadAllText (linkToCPath), Is.EqualTo ("ABCDEFGHIJKLMCCC"), "LinkToC.txt"); + Assert.That (PathUtils.IsSymlink (linkToCPath), Is.True, "LinkToC.txt - IsSymlink"); + Assert.That (PathUtils.GetSymlinkTarget (linkToCPath), Is.EqualTo ("C.txt"), "LinkToC.txt - IsSymlink target"); var linkToNowherePath = Path.Combine (directory, "C.framework/LinkToNowhere.txt"); Assert.Throws (() => File.ReadAllText (linkToNowherePath), "LinkToNowhere.txt"); - Assert.AreEqual ("Nowhere.txt", PathUtils.GetSymlinkTarget (linkToNowherePath), "LinkToNowhere.txt - IsSymlink target"); + Assert.That (PathUtils.GetSymlinkTarget (linkToNowherePath), Is.EqualTo ("Nowhere.txt"), "LinkToNowhere.txt - IsSymlink target"); } var manifest = @" @@ -157,7 +157,7 @@ void AssertResourceDirectory (string directory, bool symlinks) "; - Assert.AreEqual (manifest, File.ReadAllText (Path.Combine (directory, "manifest")), "Manifest"); + Assert.That (File.ReadAllText (Path.Combine (directory, "manifest")), Is.EqualTo (manifest), "Manifest"); } ITaskItem [] CreateNativeReferences (string tmpdir, bool symlinks) diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/DetectSdkLocationsTaskTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/DetectSdkLocationsTaskTests.cs index e073eda32d71..7c49889b880f 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/DetectSdkLocationsTaskTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/DetectSdkLocationsTaskTests.cs @@ -18,7 +18,7 @@ public void InvalidXamarinSdkRoot () task.TargetFrameworkMoniker = TargetFramework.DotNet_iOS_String; ExecuteTask (task, 1); - Assert.AreEqual ("XYZ", task.XamarinSdkRoot, "#1"); + Assert.That (task.XamarinSdkRoot, Is.EqualTo ("XYZ"), "#1"); } } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/DetectSigningIdentityTaskTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/DetectSigningIdentityTaskTests.cs index ae959e2c7f31..2b30d1a51326 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/DetectSigningIdentityTaskTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/DetectSigningIdentityTaskTests.cs @@ -35,11 +35,11 @@ public void Default () ExecuteTask (task); Assert.That (task.DetectedAppId, Is.Null.Or.Empty, "DetectedAppId"); - Assert.AreEqual ("-", task.DetectedCodeSigningKey, "DetectedCodeSigningKey"); - Assert.AreEqual ($"{Xamarin.Tests.Configuration.XcodeLocation}/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate", task.DetectedCodesignAllocate, "DetectedCodesignAllocate"); - Assert.AreEqual ("Any", task.DetectedDistributionType, "DetectedDistributionType"); + Assert.That (task.DetectedCodeSigningKey, Is.EqualTo ("-"), "DetectedCodeSigningKey"); + Assert.That (task.DetectedCodesignAllocate, Is.EqualTo ($"{Xamarin.Tests.Configuration.XcodeLocation}/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate"), "DetectedCodesignAllocate"); + Assert.That (task.DetectedDistributionType, Is.EqualTo ("Any"), "DetectedDistributionType"); Assert.That (task.DetectedProvisioningProfile, Is.Null.Or.Empty, "DetectedProvisioningProfile"); - Assert.IsFalse (task.HasEntitlements, "HasEntitlements"); + Assert.That (task.HasEntitlements, Is.False, "HasEntitlements"); } const string EmptyEntitlements1 = @" @@ -142,17 +142,17 @@ public void EmptyEntitlements (EntitlementTestCase testCase) Assert.That (task.DetectedAppId, Does.EndWith (".com.tests.emptyentitlements"), "DetectedAppId"); Assert.That (task.DetectedProvisioningProfile, Is.Not.Null.And.Not.Empty, "DetectedProvisioningProfile"); } else { - Assert.AreEqual ("com.tests.emptyentitlements", task.DetectedAppId, "DetectedAppId"); + Assert.That (task.DetectedAppId, Is.EqualTo ("com.tests.emptyentitlements"), "DetectedAppId"); Assert.That (task.DetectedProvisioningProfile, Is.Null.Or.Empty, "DetectedProvisioningProfile"); } if (testCase.IsSimulator || !requiresProvisioningProfile) { - Assert.AreEqual ("-", task.DetectedCodeSigningKey, "DetectedCodeSigningKey"); + Assert.That (task.DetectedCodeSigningKey, Is.EqualTo ("-"), "DetectedCodeSigningKey"); Assert.That (task.DetectedDistributionType, Is.EqualTo ("Any"), "DetectedDistributionType"); } else { Assert.That (task.DetectedCodeSigningKey, Has.Length.EqualTo ("20D63576DE3EA7BE419C18997CF948D759B43D53".Length), "DetectedCodeSigningKey"); Assert.That (task.DetectedDistributionType, Is.EqualTo ("Development").Or.EqualTo ("AppStore").Or.EqualTo ("Any"), "DetectedDistributionType"); } - Assert.AreEqual ($"{Xamarin.Tests.Configuration.XcodeLocation}/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate", task.DetectedCodesignAllocate, "DetectedCodesignAllocate"); + Assert.That (task.DetectedCodesignAllocate, Is.EqualTo ($"{Xamarin.Tests.Configuration.XcodeLocation}/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate"), "DetectedCodesignAllocate"); } [Test] @@ -164,11 +164,11 @@ public void CustomEntitlements () ExecuteTask (task); Assert.That (task.DetectedAppId, Is.Not.Null.And.Not.Empty, "DetectedAppId"); - Assert.AreEqual ("-", task.DetectedCodeSigningKey, "DetectedCodeSigningKey"); - Assert.AreEqual ($"{Xamarin.Tests.Configuration.XcodeLocation}/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate", task.DetectedCodesignAllocate, "DetectedCodesignAllocate"); - Assert.AreEqual ("Any", task.DetectedDistributionType, "DetectedDistributionType"); + Assert.That (task.DetectedCodeSigningKey, Is.EqualTo ("-"), "DetectedCodeSigningKey"); + Assert.That (task.DetectedCodesignAllocate, Is.EqualTo ($"{Xamarin.Tests.Configuration.XcodeLocation}/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate"), "DetectedCodesignAllocate"); + Assert.That (task.DetectedDistributionType, Is.EqualTo ("Any"), "DetectedDistributionType"); Assert.That (task.DetectedProvisioningProfile, Is.Not.Null.And.Not.Empty, "DetectedProvisioningProfile"); - Assert.IsTrue (task.HasEntitlements, "HasEntitlements"); + Assert.That (task.HasEntitlements, Is.True, "HasEntitlements"); } [Test] @@ -183,11 +183,11 @@ public void Simulator () Assert.Multiple (() => { Assert.That (task.DetectedAppId, Does.EndWith ("." + task.BundleIdentifier), "DetectedAppId"); - Assert.AreEqual ("-", task.DetectedCodeSigningKey, "DetectedCodeSigningKey"); - Assert.AreEqual ($"{Xamarin.Tests.Configuration.XcodeLocation}/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate", task.DetectedCodesignAllocate, "DetectedCodesignAllocate"); - Assert.AreEqual ("Any", task.DetectedDistributionType, "DetectedDistributionType"); + Assert.That (task.DetectedCodeSigningKey, Is.EqualTo ("-"), "DetectedCodeSigningKey"); + Assert.That (task.DetectedCodesignAllocate, Is.EqualTo ($"{Xamarin.Tests.Configuration.XcodeLocation}/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate"), "DetectedCodesignAllocate"); + Assert.That (task.DetectedDistributionType, Is.EqualTo ("Any"), "DetectedDistributionType"); Assert.That (task.DetectedProvisioningProfile, Is.Not.Null.And.Not.Empty, "DetectedProvisioningProfile"); - Assert.IsTrue (task.HasEntitlements, "HasEntitlements"); + Assert.That (task.HasEntitlements, Is.True, "HasEntitlements"); }); } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_Core.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_Core.cs index f369b2035fad..f6b0181548aa 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_Core.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_Core.cs @@ -46,6 +46,7 @@ protected virtual void ConfigureTask () Task.MinSupportedOSPlatformVersion = "10.0"; Task.SupportedOSPlatformVersion = "15.0"; Task.SdkVersion = "10.0"; + Task.TargetFrameworkMoniker = TargetFramework.GetTargetFramework (Platform).ToString (); Plist = new PDictionary (); Plist ["CFBundleDisplayName"] = displayName; @@ -60,7 +61,7 @@ public override void Setup () ConfigureTask (); ExecuteTask (Task); - CompiledPlist = PDictionary.FromFile (Task.CompiledAppManifest!.ItemSpec) ?? throw new InvalidOperationException ("Failed to load compiled plist"); + CompiledPlist = PDictionary.OpenFile (Task.CompiledAppManifest!.ItemSpec); } #region General tests @@ -68,16 +69,16 @@ public override void Setup () public void PlistMissing () { File.Delete (Task.AppManifest!.ItemSpec); - Assert.IsTrue (Task.Execute (), "#1"); + Assert.That (Task.Execute (), Is.True, "#1"); Assert.That (Task.CompiledAppManifest!.ItemSpec, Does.Exist, "#2"); } [Test] public void NormalPlist () { - Assert.IsTrue (Task.Execute (), "#1"); - Assert.IsNotNull (Task.CompiledAppManifest?.ItemSpec, "#2"); - Assert.IsTrue (File.Exists (Task.CompiledAppManifest!.ItemSpec), "#3"); + Assert.That (Task.Execute (), Is.True, "#1"); + Assert.That (Task.CompiledAppManifest?.ItemSpec, Is.Not.Null, "#2"); + Assert.That (File.Exists (Task.CompiledAppManifest!.ItemSpec), Is.True, "#3"); } [Test] @@ -85,7 +86,7 @@ public void MissingBundleIdentifier () { Plist.Remove ("CFBundleIdentifier"); Plist.Save (Task.AppManifest!.ItemSpec); - Assert.IsTrue (Task.Execute (), "#1"); + Assert.That (Task.Execute (), Is.True, "#1"); } [Test] @@ -93,7 +94,7 @@ public void MissingDisplayName () { Plist.Remove ("CFBundleDisplayName"); Plist.Save (Task.AppManifest!.ItemSpec); - Assert.IsTrue (Task.Execute (), "#1"); + Assert.That (Task.Execute (), Is.True, "#1"); } [Test] @@ -116,28 +117,28 @@ public void BuildMachineOSBuild () [Test] public void BundleDevelopmentRegion () { - Assert.IsFalse (CompiledPlist.ContainsKey (ManifestKeys.CFBundleDevelopmentRegion), "#1"); + Assert.That (CompiledPlist.ContainsKey (ManifestKeys.CFBundleDevelopmentRegion), Is.False, "#1"); } [Test] public virtual void BundleExecutable () { Assert.That (CompiledPlist.ContainsKey (ManifestKeys.CFBundleExecutable), "#1"); - Assert.AreEqual (CompiledPlist.Get (ManifestKeys.CFBundleExecutable)?.Value, assemblyName, "#2"); + Assert.That (assemblyName, Is.EqualTo (CompiledPlist.Get (ManifestKeys.CFBundleExecutable)?.Value), "#2"); } [Test] public virtual void BundleName () { Assert.That (CompiledPlist.ContainsKey (ManifestKeys.CFBundleName), "#1"); - Assert.AreEqual (CompiledPlist.Get (ManifestKeys.CFBundleName)?.Value, appBundleName, "#2"); + Assert.That (appBundleName, Is.EqualTo (CompiledPlist.Get (ManifestKeys.CFBundleName)?.Value), "#2"); } [Test] public virtual void BundleIdentifier () { Assert.That (CompiledPlist.ContainsKey (ManifestKeys.CFBundleIdentifier), "#1"); - Assert.AreEqual (CompiledPlist.Get (ManifestKeys.CFBundleIdentifier)?.Value, bundleIdentifier, "#2"); + Assert.That (bundleIdentifier, Is.EqualTo (CompiledPlist.Get (ManifestKeys.CFBundleIdentifier)?.Value), "#2"); } [Test] @@ -151,14 +152,14 @@ public virtual void BundleInfoDictionaryVersion () public virtual void BundlePackageType () { Assert.That (CompiledPlist.ContainsKey (ManifestKeys.CFBundlePackageType), "#1"); - Assert.AreEqual (CompiledPlist.Get (ManifestKeys.CFBundlePackageType)?.Value, "APPL", "#2"); + Assert.That ("APPL", Is.EqualTo (CompiledPlist.Get (ManifestKeys.CFBundlePackageType)?.Value), "#2"); } [Test] public virtual void BundleSignature () { Assert.That (CompiledPlist.ContainsKey (ManifestKeys.CFBundleSignature), "#1"); - Assert.AreEqual (CompiledPlist.Get (ManifestKeys.CFBundleSignature)?.Value, "????", "#2"); + Assert.That ("????", Is.EqualTo (CompiledPlist.Get (ManifestKeys.CFBundleSignature)?.Value), "#2"); } [Test] diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_iOS.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_iOS.cs index 9ccd1a1b8930..eec87ffd32f5 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_iOS.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_iOS.cs @@ -15,7 +15,7 @@ protected override void ConfigureTask () Configuration.IgnoreIfIgnoredPlatform (ApplePlatform.iOS); base.ConfigureTask (); - Task.DefaultSdkVersion = Sdks.IOS.GetClosestInstalledSdk (AppleSdkVersion.V6_1, true).ToString (); + Task.DefaultSdkVersion = Task.CurrentSdk.GetClosestInstalledSdk (AppleSdkVersion.V6_1, true).ToString () ?? ""; Task.TargetFrameworkMoniker = TargetFramework.DotNet_iOS_String; Task.TargetArchitectures = "ARM64"; } @@ -26,14 +26,14 @@ public override void BundleExecutable () base.BundleExecutable (); // Adding ".app" to the assembly name isn't allowed because iOS may fail to launch the app. Task.BundleExecutable = "AssemblyName.app"; - Assert.IsFalse (Task.Execute (), "#1"); + Assert.That (Task.Execute (), Is.False, "#1"); } [Test] public override void BundleName () { Assert.That (CompiledPlist.ContainsKey (ManifestKeys.CFBundleName), "#1"); - Assert.AreEqual (CompiledPlist.Get (ManifestKeys.CFBundleName)?.Value, appBundleName, "#2"); + Assert.That (appBundleName, Is.EqualTo (CompiledPlist.Get (ManifestKeys.CFBundleName)?.Value), "#2"); } [Test] @@ -41,10 +41,10 @@ public void RequiredDeviceCapabilities () { PArray? array; - Assert.IsTrue (CompiledPlist.TryGetValue (ManifestKeys.UIRequiredDeviceCapabilities, out array), "#1"); - Assert.IsTrue (array?.OfType ().Any (x => x.Value == "arm64") == true, "#2"); - Assert.IsFalse (array?.OfType ().Any (x => x.Value == "armv6") == true, "#3"); - Assert.IsFalse (array?.OfType ().Any (x => x.Value == "armv7") == true, "#4"); + Assert.That (CompiledPlist.TryGetValue (ManifestKeys.UIRequiredDeviceCapabilities, out array), Is.True, "#1"); + Assert.That (array?.OfType ().Any (x => x.Value == "arm64") == true, Is.True, "#2"); + Assert.That (array?.OfType ().Any (x => x.Value == "armv6") == true, Is.False, "#3"); + Assert.That (array?.OfType ().Any (x => x.Value == "armv7") == true, Is.False, "#4"); } } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_iOS_AppExtension.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_iOS_AppExtension.cs index dace42f2137e..49adae09756d 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_iOS_AppExtension.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_iOS_AppExtension.cs @@ -14,7 +14,7 @@ protected override void ConfigureTask () public override void BundlePackageType () { Assert.That (CompiledPlist.ContainsKey (ManifestKeys.CFBundlePackageType), "#1"); - Assert.AreEqual (CompiledPlist.Get (ManifestKeys.CFBundlePackageType)?.Value, "XPC!", "#2"); + Assert.That ("XPC!", Is.EqualTo (CompiledPlist.Get (ManifestKeys.CFBundlePackageType)?.Value), "#2"); } } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_tvOS.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_tvOS.cs index b77904722891..06ab59fadfbe 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_tvOS.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GeneratePlistTaskTests/GeneratePlistTaskTests_tvOS.cs @@ -14,7 +14,7 @@ protected override void ConfigureTask () Configuration.IgnoreIfIgnoredPlatform (ApplePlatform.TVOS); base.ConfigureTask (); - Task.DefaultSdkVersion = Sdks.TVOS.GetClosestInstalledSdk (AppleSdkVersion.V9_0, true).ToString (); + Task.DefaultSdkVersion = Task.CurrentSdk.GetClosestInstalledSdk (AppleSdkVersion.V9_0, true).ToString () ?? ""; Task.TargetFrameworkMoniker = TargetFramework.DotNet_tvOS_String; } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GetAvailableDevicesTest.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GetAvailableDevicesTest.cs index beb8be0f356d..1d874fcb732c 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GetAvailableDevicesTest.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GetAvailableDevicesTest.cs @@ -58,7 +58,7 @@ public void EmptyJsons (string simctl, string devicectl) { var platform = ApplePlatform.iOS; var task = CreateTask (platform, simctl, devicectl); - Assert.IsTrue (task.Execute (), "Task should have succeeded."); + Assert.That (task.Execute (), Is.True, "Task should have succeeded."); Assert.That (task.Devices.Count, Is.EqualTo (0), "Devices should be empty."); Assert.That (task.DiscardedDevices.Count, Is.EqualTo (0), "No devices should have been discarded."); } @@ -68,7 +68,7 @@ public void DeviceCtl1 () { var platform = ApplePlatform.iOS; var task = CreateTask (platform, "", DEVICECTL_JSON_1); - Assert.IsTrue (task.Execute (), "Task should have succeeded."); + Assert.That (task.Execute (), Is.True, "Task should have succeeded."); Assert.Multiple (() => { Assert.That (task.Devices.Count, Is.EqualTo (3), "Devices count mismatch."); Assert.That (task.DiscardedDevices.Count, Is.EqualTo (1), "Discarded device count mismatch."); @@ -111,7 +111,7 @@ public void SimCtl1 () var platform = ApplePlatform.iOS; var task = CreateTask (platform, SIMCTL_JSON_1, ""); - Assert.IsTrue (task.Execute (), "Task should have succeeded."); + Assert.That (task.Execute (), Is.True, "Task should have succeeded."); Assert.Multiple (() => { Assert.That (task.Devices.Count, Is.EqualTo (2), "Devices count mismatch."); Assert.That (task.DiscardedDevices.Count, Is.EqualTo (3), "Discarded device count mismatch."); @@ -139,7 +139,7 @@ public void SimCtl1 () Assert.That (task.DiscardedDevices [1].ItemSpec, Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 2 mismatch."); Assert.That (task.DiscardedDevices [1].GetMetadata ("Description"), Is.EqualTo ("iPhone 17 Pro"), "Discarded Device 2 Name mismatch."); - Assert.That (task.DiscardedDevices [1].GetMetadata ("OSVersion"), Is.EqualTo (""), "Discarded Device 2 OSVersion mismatch."); + Assert.That (task.DiscardedDevices [1].GetMetadata ("OSVersion"), Is.EqualTo ("26.0"), "Discarded Device 2 OSVersion mismatch."); Assert.That (task.DiscardedDevices [1].GetMetadata ("UDID"), Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 2 UDID mismatch."); Assert.That (task.DiscardedDevices [1].GetMetadata ("RuntimeIdentifier"), Is.EqualTo (""), "Discarded Device 2 RuntimeIdentifier mismatch."); Assert.That (task.DiscardedDevices [1].GetMetadata ("DiscardedReason"), Is.EqualTo ("Device is not available: runtime profile not found using \"System\" match policy"), "Discarded Device 2 reason mismatch."); @@ -160,7 +160,7 @@ public void Ctl1 () var platform = ApplePlatform.iOS; var task = CreateTask (platform, SIMCTL_JSON_1, DEVICECTL_JSON_1); - Assert.IsTrue (task.Execute (), "Task should have succeeded."); + Assert.That (task.Execute (), Is.True, "Task should have succeeded."); Assert.Multiple (() => { Assert.That (task.Devices.Count, Is.EqualTo (5), "Devices count mismatch."); Assert.That (task.DiscardedDevices.Count, Is.EqualTo (4), "Discarded device count mismatch."); @@ -216,7 +216,7 @@ public void Ctl1 () Assert.That (task.DiscardedDevices [2].ItemSpec, Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 3 UDID mismatch."); Assert.That (task.DiscardedDevices [2].GetMetadata ("Description"), Is.EqualTo ("iPhone 17 Pro"), "Discarded Device 3 Name mismatch."); - Assert.That (task.DiscardedDevices [2].GetMetadata ("OSVersion"), Is.EqualTo (""), "Discarded Device 3 OSVersion mismatch."); + Assert.That (task.DiscardedDevices [2].GetMetadata ("OSVersion"), Is.EqualTo ("26.0"), "Discarded Device 3 OSVersion mismatch."); Assert.That (task.DiscardedDevices [2].GetMetadata ("UDID"), Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 3 UDID mismatch."); Assert.That (task.DiscardedDevices [2].GetMetadata ("RuntimeIdentifier"), Is.EqualTo (""), "Discarded Device 3 RuntimeIdentifier mismatch."); Assert.That (task.DiscardedDevices [2].GetMetadata ("DiscardedReason"), Is.EqualTo ("Device is not available: runtime profile not found using \"System\" match policy"), "Discarded Device 3 reason mismatch."); @@ -250,7 +250,7 @@ public void Ctl1_iPhone () """; var task = CreateTask (platform, SIMCTL_JSON_1, DEVICECTL_JSON_1, appManifestXml); - Assert.IsTrue (task.Execute (), "Task should have succeeded."); + Assert.That (task.Execute (), Is.True, "Task should have succeeded."); Assert.Multiple (() => { Assert.That (task.Devices.Count, Is.EqualTo (5), "Devices count mismatch."); Assert.That (task.DiscardedDevices.Count, Is.EqualTo (4), "Discarded device count mismatch."); @@ -306,7 +306,7 @@ public void Ctl1_iPhone () Assert.That (task.DiscardedDevices [2].ItemSpec, Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 3 UDID mismatch."); Assert.That (task.DiscardedDevices [2].GetMetadata ("Description"), Is.EqualTo ("iPhone 17 Pro"), "Discarded Device 3 Name mismatch."); - Assert.That (task.DiscardedDevices [2].GetMetadata ("OSVersion"), Is.EqualTo (""), "Discarded Device 3 OSVersion mismatch."); + Assert.That (task.DiscardedDevices [2].GetMetadata ("OSVersion"), Is.EqualTo ("26.0"), "Discarded Device 3 OSVersion mismatch."); Assert.That (task.DiscardedDevices [2].GetMetadata ("UDID"), Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 3 UDID mismatch."); Assert.That (task.DiscardedDevices [2].GetMetadata ("RuntimeIdentifier"), Is.EqualTo (""), "Discarded Device 3 RuntimeIdentifier mismatch."); Assert.That (task.DiscardedDevices [2].GetMetadata ("DiscardedReason"), Is.EqualTo ("Device is not available: runtime profile not found using \"System\" match policy"), "Discarded Device 3 reason mismatch."); @@ -344,7 +344,7 @@ public void Ctl1_iPad () var task = CreateTask (platform, SIMCTL_JSON_1, DEVICECTL_JSON_1, appManifestXml); - Assert.IsTrue (task.Execute (), "Task should have succeeded."); + Assert.That (task.Execute (), Is.True, "Task should have succeeded."); Assert.Multiple (() => { Assert.That (task.Devices.Count, Is.EqualTo (2), "Devices count mismatch."); Assert.That (task.DiscardedDevices.Count, Is.EqualTo (7), "Discarded device count mismatch."); @@ -393,7 +393,7 @@ public void Ctl1_iPad () Assert.That (task.DiscardedDevices [4].ItemSpec, Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 5 ItemSpec mismatch."); Assert.That (task.DiscardedDevices [4].GetMetadata ("Description"), Is.EqualTo ("iPhone 17 Pro"), "Discarded Device 5 Description mismatch."); - Assert.That (task.DiscardedDevices [4].GetMetadata ("OSVersion"), Is.EqualTo (""), "Discarded Device 5 OSVersion mismatch."); + Assert.That (task.DiscardedDevices [4].GetMetadata ("OSVersion"), Is.EqualTo ("26.0"), "Discarded Device 5 OSVersion mismatch."); Assert.That (task.DiscardedDevices [4].GetMetadata ("UDID"), Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 5 UDID mismatch."); Assert.That (task.DiscardedDevices [4].GetMetadata ("RuntimeIdentifier"), Is.EqualTo (""), "Discarded Device 5 RuntimeIdentifier mismatch."); Assert.That (task.DiscardedDevices [4].GetMetadata ("DiscardedReason"), Is.EqualTo ("Device is not available: runtime profile not found using \"System\" match policy"), "Discarded Device 5 reason mismatch."); @@ -438,7 +438,7 @@ public void Ctl1_OSVersion () File.WriteAllText (appManifestPath, appManifestXml); task.AppBundleManifestPath = appManifestPath; - Assert.IsTrue (task.Execute (), "Task should have succeeded."); + Assert.That (task.Execute (), Is.True, "Task should have succeeded."); Assert.Multiple (() => { Assert.That (task.Devices.Count, Is.EqualTo (3), "Devices count mismatch."); Assert.That (task.DiscardedDevices.Count, Is.EqualTo (6), "Discarded device count mismatch."); @@ -487,7 +487,7 @@ public void Ctl1_OSVersion () Assert.That (task.DiscardedDevices [3].ItemSpec, Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 4 UDID mismatch."); Assert.That (task.DiscardedDevices [3].GetMetadata ("Description"), Is.EqualTo ("iPhone 17 Pro"), "Discarded Device 4 Name mismatch."); - Assert.That (task.DiscardedDevices [3].GetMetadata ("OSVersion"), Is.EqualTo (""), "Discarded Device 4 OSVersion mismatch."); + Assert.That (task.DiscardedDevices [3].GetMetadata ("OSVersion"), Is.EqualTo ("26.0"), "Discarded Device 4 OSVersion mismatch."); Assert.That (task.DiscardedDevices [3].GetMetadata ("UDID"), Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 4 UDID mismatch."); Assert.That (task.DiscardedDevices [3].GetMetadata ("RuntimeIdentifier"), Is.EqualTo (""), "Discarded Device 4 RuntimeIdentifier mismatch."); Assert.That (task.DiscardedDevices [3].GetMetadata ("DiscardedReason"), Is.EqualTo ("Device is not available: runtime profile not found using \"System\" match policy"), "Discarded Device 4 reason mismatch."); @@ -531,7 +531,7 @@ public void Ctl1_RuntimeIdentifier () task.AppBundleManifestPath = appManifestPath; task.RuntimeIdentifier = $"ios-arm64"; - Assert.IsTrue (task.Execute (), "Task should have succeeded."); + Assert.That (task.Execute (), Is.True, "Task should have succeeded."); Assert.Multiple (() => { Assert.That (task.Devices.Count, Is.EqualTo (3), "Devices count mismatch."); Assert.That (task.DiscardedDevices.Count, Is.EqualTo (6), "Discarded device count mismatch."); @@ -573,7 +573,7 @@ public void Ctl1_RuntimeIdentifier () Assert.That (task.DiscardedDevices [2].ItemSpec, Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 3 UDID mismatch."); Assert.That (task.DiscardedDevices [2].GetMetadata ("Description"), Is.EqualTo ("iPhone 17 Pro"), "Discarded Device 3 Name mismatch."); - Assert.That (task.DiscardedDevices [2].GetMetadata ("OSVersion"), Is.EqualTo (""), "Discarded Device 3 OSVersion mismatch."); + Assert.That (task.DiscardedDevices [2].GetMetadata ("OSVersion"), Is.EqualTo ("26.0"), "Discarded Device 3 OSVersion mismatch."); Assert.That (task.DiscardedDevices [2].GetMetadata ("UDID"), Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 3 UDID mismatch."); Assert.That (task.DiscardedDevices [2].GetMetadata ("RuntimeIdentifier"), Is.EqualTo (""), "Discarded Device 3 RuntimeIdentifier mismatch."); Assert.That (task.DiscardedDevices [2].GetMetadata ("DiscardedReason"), Is.EqualTo ("Device is not available: runtime profile not found using \"System\" match policy"), "Discarded Device 3 reason mismatch."); @@ -609,7 +609,7 @@ public void Ctl1_AppleTV () var platform = ApplePlatform.TVOS; var task = CreateTask (platform, SIMCTL_JSON_1, DEVICECTL_JSON_1); - Assert.IsTrue (task.Execute (), "Task should have succeeded."); + Assert.That (task.Execute (), Is.True, "Task should have succeeded."); Assert.Multiple (() => { Assert.That (task.Devices.Count, Is.EqualTo (1), "Devices count mismatch."); Assert.That (task.DiscardedDevices.Count, Is.EqualTo (8), "Discarded device count mismatch."); @@ -651,7 +651,7 @@ public void Ctl1_AppleTV () Assert.That (task.DiscardedDevices [4].ItemSpec, Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 5 ItemSpec mismatch."); Assert.That (task.DiscardedDevices [4].GetMetadata ("Description"), Is.EqualTo ("iPhone 17 Pro"), "Discarded Device 5 Description mismatch."); - Assert.That (task.DiscardedDevices [4].GetMetadata ("OSVersion"), Is.EqualTo (""), "Discarded Device 5 OSVersion mismatch."); + Assert.That (task.DiscardedDevices [4].GetMetadata ("OSVersion"), Is.EqualTo ("26.0"), "Discarded Device 5 OSVersion mismatch."); Assert.That (task.DiscardedDevices [4].GetMetadata ("UDID"), Is.EqualTo ("D4D95709-144A-4CAA-8469-89566EC1C935"), "Discarded Device 5 UDID mismatch."); Assert.That (task.DiscardedDevices [4].GetMetadata ("RuntimeIdentifier"), Is.EqualTo (""), "Discarded Device 5 RuntimeIdentifier mismatch."); Assert.That (task.DiscardedDevices [4].GetMetadata ("DiscardedReason"), Is.EqualTo ("Device is not available: runtime profile not found using \"System\" match policy"), "Discarded Device 5 reason mismatch."); @@ -684,7 +684,7 @@ public void DeviceCtl2_Mac () { var platform = ApplePlatform.iOS; var task = CreateTask (platform, "", DEVICECTL_JSON_2); - Assert.IsTrue (task.Execute (), "Task should have succeeded."); + Assert.That (task.Execute (), Is.True, "Task should have succeeded."); Assert.Multiple (() => { Assert.That (task.DiscardedDevices [0].ItemSpec, Is.EqualTo ("12345678-1234-1234-ABCD-1234567980AB"), "Discarded Device 1 itemspec mismatch."); diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GetBundleNameTaskTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GetBundleNameTaskTests.cs index 516fe565cacc..4676f3bee06a 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GetBundleNameTaskTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GetBundleNameTaskTests.cs @@ -21,7 +21,7 @@ public void GetBundleName () task.ProjectName = "!@£///Hello_World%£"; ExecuteTask (task); - Assert.AreEqual ("Hello_World", task.BundleName, "#2"); + Assert.That (task.BundleName, Is.EqualTo ("Hello_World"), "#2"); } } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GetPropertyListValueTaskTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GetPropertyListValueTaskTests.cs index 22554e631acc..38eb9c5a3a32 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GetPropertyListValueTaskTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/GetPropertyListValueTaskTests.cs @@ -23,7 +23,7 @@ void TestExecuteTask (string property, string? expected) ExecuteTask (task); - Assert.AreEqual (expected, task.Value, "Task produced the incorrect plist output."); + Assert.That (task.Value, Is.EqualTo (expected), "Task produced the incorrect plist output."); } [Test] diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/IBToolTaskTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/IBToolTaskTests.cs index 8c301b35e3c8..2b66ae4a5f93 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/IBToolTaskTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/IBToolTaskTests.cs @@ -18,10 +18,10 @@ namespace Xamarin.MacDev.Tasks { public class IBToolTaskTests : TestBase { IBTool CreateIBToolTask (ApplePlatform framework, string projectDir, string intermediateOutputPath) { + var task = CreateTask (); + var interfaceDefinitions = new List (); - var sdk = Sdks.GetSdk (framework); - var version = AppleSdkVersion.GetDefault (sdk, false); - var root = sdk.GetSdkPath (version, false); + var version = AppleSdkVersion.UseDefault.ToString (); string platform; switch (framework) { @@ -39,17 +39,16 @@ IBTool CreateIBToolTask (ApplePlatform framework, string projectDir, string inte foreach (var item in Directory.EnumerateFiles (projectDir, "*.xib", SearchOption.AllDirectories)) interfaceDefinitions.Add (new TaskItem (item)); - var task = CreateTask (); task.InterfaceDefinitions = interfaceDefinitions.ToArray (); task.IntermediateOutputPath = intermediateOutputPath; - task.MinimumOSVersion = PDictionary.FromFile (Path.Combine (projectDir, "Info.plist")).GetMinimumOSVersion (); + task.MinimumOSVersion = PDictionary.OpenFile (Path.Combine (projectDir, "Info.plist")).GetMinimumOSVersion (); task.ResourcePrefix = "Resources"; task.ProjectDir = projectDir; task.SdkDevPath = Configuration.xcode_root; task.SdkPlatform = platform; task.SdkVersion = version.ToString (); - task.SdkRoot = root; task.TargetFrameworkMoniker = TargetFramework.DotNet_iOS_String; + task.SdkRoot = task.CurrentSdk.GetSdkPath (version, false); return task; } @@ -62,10 +61,10 @@ public void TestBasicIBToolFunctionality () var ibtool = CreateIBToolTask (ApplePlatform.iOS, srcdir, tmp); var bundleResources = new HashSet (); - Assert.IsTrue (ibtool.Execute (), "Execution of IBTool task failed."); + ExecuteTask (ibtool); foreach (var bundleResource in ibtool.BundleResources) { - Assert.IsTrue (File.Exists (bundleResource.ItemSpec), "File does not exist: {0}", bundleResource.ItemSpec); + Assert.That (File.Exists (bundleResource.ItemSpec), Is.True, $"File does not exist: {bundleResource.ItemSpec}"); Assert.That (bundleResource.GetMetadata ("LogicalName"), Is.Not.Null.Or.Empty, "The 'LogicalName' metadata must be set."); Assert.That (bundleResource.GetMetadata ("Optimize"), Is.Not.Null.Or.Empty, "The 'Optimize' metadata must be set."); @@ -104,18 +103,18 @@ public void TestAdvancedIBToolFunctionality () ibtool.EnableOnDemandResources = true; - Assert.IsTrue (ibtool.Execute (), "Execution of IBTool task failed."); + ExecuteTask (ibtool); foreach (var bundleResource in ibtool.BundleResources) { var bundleName = bundleResource.GetMetadata ("LogicalName"); var tag = bundleResource.GetMetadata ("ResourceTags"); - Assert.IsTrue (File.Exists (bundleResource.ItemSpec), "File does not exist: {0}", bundleResource.ItemSpec); + Assert.That (File.Exists (bundleResource.ItemSpec), Is.True, $"File does not exist: {bundleResource.ItemSpec}"); Assert.That (bundleResource.GetMetadata ("LogicalName"), Is.Not.Null.Or.Empty, "The 'LogicalName' metadata must be set."); Assert.That (bundleResource.GetMetadata ("Optimize"), Is.Not.Null.Or.Empty, "The 'Optimize' metadata must be set."); Assert.That (tag, Is.Not.Null.Or.Empty, "The 'ResourceTags' metadata should be set."); - Assert.IsTrue (bundleName.Contains (".lproj/" + tag + ".storyboardc/"), "BundleResource does not have the proper ResourceTags set: {0}", bundleName); + Assert.That (bundleName.Contains (".lproj/" + tag + ".storyboardc/"), Is.True, $"BundleResource does not have the proper ResourceTags set: {bundleName}"); bundleResources.Add (bundleName); } @@ -179,18 +178,18 @@ void TestGenericAndDeviceSpecificXibsGeneric (params string [] fileNames) ibtool.EnableOnDemandResources = true; - Assert.IsTrue (ibtool.Execute (), "Execution of IBTool task failed."); + ExecuteTask (ibtool); foreach (var bundleResource in ibtool.BundleResources) { var bundleName = bundleResource.GetMetadata ("LogicalName"); var tag = bundleResource.GetMetadata ("ResourceTags"); - Assert.IsTrue (File.Exists (bundleResource.ItemSpec), "File does not exist: {0}", bundleResource.ItemSpec); + Assert.That (File.Exists (bundleResource.ItemSpec), Is.True, $"File does not exist: {bundleResource.ItemSpec}"); Assert.That (bundleResource.GetMetadata ("LogicalName"), Is.Not.Null.Or.Empty, "The 'LogicalName' metadata must be set."); Assert.That (bundleResource.GetMetadata ("Optimize"), Is.Not.Null.Or.Empty, "The 'Optimize' metadata must be set."); Assert.That (tag, Is.Not.Null.Or.Empty, "The 'ResourceTags' metadata should be set."); - Assert.AreEqual (Path.Combine (tmp, "ibtool", tag + ".nib"), bundleResource.ItemSpec, $"BundleResource {bundleName} is not at the expected location."); + Assert.That (bundleResource.ItemSpec, Is.EqualTo (Path.Combine (tmp, "ibtool", tag + ".nib")), $"BundleResource {bundleName} is not at the expected location."); bundleResources.Add (bundleName); } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/LocalizationStringTest.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/LocalizationStringTest.cs index d6bb024a3940..ac38aee0da38 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/LocalizationStringTest.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/LocalizationStringTest.cs @@ -43,7 +43,7 @@ public void AllSupportedTranslations (string culture, string errorMessage) ExecuteTask (task, 1); bool isTranslated = Engine.Logger.ErrorEvents [0].Message?.Contains (errorMessage) == true; - Assert.IsTrue (isTranslated, $"Should contain \"{errorMessage}\", but instead has value: \"{Engine.Logger.ErrorEvents [0].Message}\""); + Assert.That (isTranslated, Is.True, $"Should contain \"{errorMessage}\", but instead has value: \"{Engine.Logger.ErrorEvents [0].Message}\""); } finally { Thread.CurrentThread.CurrentUICulture = originalUICulture; Thread.CurrentThread.CurrentCulture = originalCulture; @@ -71,11 +71,11 @@ public void SpecificErrorTranslation (string culture) CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture; try { - Assert.IsFalse (string.IsNullOrEmpty (errorCode), "Error code is null or empty"); + Assert.That (string.IsNullOrEmpty (errorCode), Is.False, "Error code is null or empty"); string? englishError = TranslateError ("en-US", errorCode); string? newCultureError = TranslateError (culture, errorCode); - Assert.AreNotEqual (englishError, newCultureError, $"\"{errorCode}\" is not translated in {culture}."); + Assert.That (newCultureError, Is.Not.EqualTo (englishError), $"\"{errorCode}\" is not translated in {culture}."); } catch (NullReferenceException) { Assert.Fail ($"Error code \"{errorCode}\" was not found"); } finally { @@ -110,8 +110,8 @@ public void UpdatedResources () var errorsNotInResources = string.Join (" ", resxHashSet.Where (n => !resourceHashSet.Contains (n) && !ignoreList.Contains (n))); var errorsNotInResx = string.Join (" ", resourceHashSet.Where (n => !resxHashSet.Contains (n) && !ignoreList.Contains (n))); - Assert.IsEmpty (errorsNotInResources, $"The following error(s) were found in MSBStrings.resx but not through the MSBStrings resource. Try to recompile the msbuild project and then the test project\n{errorsNotInResources}"); - Assert.IsEmpty (errorsNotInResx, $"The following error(s) were found in the MSBStrings resource but not in MSBStrings.resx. Try to recompile the msbuild project and then the test project\n{errorsNotInResx}"); + Assert.That (errorsNotInResources, Is.Empty, $"The following error(s) were found in MSBStrings.resx but not through the MSBStrings resource. Try to recompile the msbuild project and then the test project\n{errorsNotInResources}"); + Assert.That (errorsNotInResx, Is.Empty, $"The following error(s) were found in the MSBStrings resource but not in MSBStrings.resx. Try to recompile the msbuild project and then the test project\n{errorsNotInResx}"); } } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/MergeAppBundleTaskTest.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/MergeAppBundleTaskTest.cs index 29a8e9650f2b..309d9aa597f9 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/MergeAppBundleTaskTest.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/MergeAppBundleTaskTest.cs @@ -102,13 +102,13 @@ public void TestLipoExecutable () ExecuteTask (task); // The bundle should only contain a single file. - Assert.AreEqual (1, Directory.GetFileSystemEntries (outputBundle).Length, "Files in bundle"); + Assert.That (Directory.GetFileSystemEntries (outputBundle).Length, Is.EqualTo (1), "Files in bundle"); // The resulting dylib should contain 2 architectures. var fatLibrary = Path.Combine (outputBundle, "libframework.dylib"); Assert.That (fatLibrary, Does.Exist, "Existence"); var machO = MachO.Read (fatLibrary).ToArray (); - Assert.AreEqual (2, machO.Length, "Architecture Count"); + Assert.That (machO.Length, Is.EqualTo (2), "Architecture Count"); } [Test] @@ -132,7 +132,7 @@ public void TestPEAssembly () ExecuteTask (task); // The bundle should have all the files - Assert.AreEqual (complexFiles.Length, Directory.GetFileSystemEntries (outputBundle).Length, "Files in bundle"); + Assert.That (Directory.GetFileSystemEntries (outputBundle).Length, Is.EqualTo (complexFiles.Length), "Files in bundle"); // with the same structure foreach (var file in complexFiles) @@ -152,7 +152,7 @@ public void TestDifferentOtherFiles () var outputBundle = Path.Combine (Cache.CreateTemporaryDirectory (), "Merged.app"); var task = CreateTask (outputBundle, bundles); ExecuteTask (task, 3); - Assert.AreEqual ("Unable to merge the file 'Something.txt', it's different between the input app bundles.", Engine.Logger.ErrorEvents [0].Message, "Error message"); + Assert.That (Engine.Logger.ErrorEvents [0].Message, Is.EqualTo ("Unable to merge the file 'Something.txt', it's different between the input app bundles."), "Error message"); Assert.That (Engine.Logger.ErrorEvents [1].Message, Does.Match ("App bundle file #1: .*/MergeMe.app/Something.txt"), "Error message 2"); Assert.That (Engine.Logger.ErrorEvents [2].Message, Does.Match ("App bundle file #2: .*/MergeMe.app/Something.txt"), "Error message 3"); } @@ -170,14 +170,14 @@ public void TestSymlinks () File.WriteAllText (fileB, "A"); var linkA = Path.Combine (bundleA, "B.txt"); var linkB = Path.Combine (bundleB, "B.txt"); - Assert.IsTrue (PathUtils.Symlink ("A.txt", linkA), "Link A"); - Assert.IsTrue (PathUtils.Symlink ("A.txt", linkB), "Link B"); + Assert.That (PathUtils.Symlink ("A.txt", linkA), Is.True, "Link A"); + Assert.That (PathUtils.Symlink ("A.txt", linkB), Is.True, "Link B"); var outputBundle = Path.Combine (Cache.CreateTemporaryDirectory (), "Merged.app"); var task = CreateTask (outputBundle, bundleA, bundleB); ExecuteTask (task); - Assert.IsTrue (PathUtils.IsSymlink (Path.Combine (outputBundle, "B.txt")), "IsSymlink"); + Assert.That (PathUtils.IsSymlink (Path.Combine (outputBundle, "B.txt")), Is.True, "IsSymlink"); } [Test] @@ -198,14 +198,14 @@ public void TestSymlinksWithDifferentTargets () // There's a symlink in both apps, but they have different targets. var linkA = Path.Combine (bundleA, "B.txt"); var linkB = Path.Combine (bundleB, "B.txt"); - Assert.IsTrue (PathUtils.Symlink ("A.txt", linkA), "Link A"); - Assert.IsTrue (PathUtils.Symlink ("C.txt", linkB), "Link B"); + Assert.That (PathUtils.Symlink ("A.txt", linkA), Is.True, "Link A"); + Assert.That (PathUtils.Symlink ("C.txt", linkB), Is.True, "Link B"); var outputBundle = Path.Combine (Cache.CreateTemporaryDirectory (), "Merged.app"); var task = CreateTask (outputBundle, bundleA, bundleB); ExecuteTask (task, 3); - Assert.AreEqual ("Can't merge the symlink 'B.txt', it has different targets.", Engine.Logger.ErrorEvents [0].Message, "Error message"); + Assert.That (Engine.Logger.ErrorEvents [0].Message, Is.EqualTo ("Can't merge the symlink 'B.txt', it has different targets."), "Error message"); Assert.That (Engine.Logger.ErrorEvents [1].Message, Does.Match ("App bundle file #1: .*/MergeMe.app/B.txt"), "Error message 2"); Assert.That (Engine.Logger.ErrorEvents [2].Message, Does.Match ("App bundle file #2: .*/MergeMe.app/B.txt"), "Error message 3"); } @@ -248,7 +248,7 @@ public void TestDirectories () Assert.That (Path.Combine (outputBundle, nestedSharedOnlyB), Does.Exist, "nestedSharedOnlyB"); // Verify that there aren't any other directories - Assert.AreEqual (7, Directory.GetFileSystemEntries (outputBundle).Length, "Directories in bundle"); + Assert.That (Directory.GetFileSystemEntries (outputBundle).Length, Is.EqualTo (7), "Directories in bundle"); } [Test] @@ -262,13 +262,13 @@ public void TestSingleInput () ExecuteTask (task); // The bundle should only contain a single file. - Assert.AreEqual (1, Directory.GetFileSystemEntries (outputBundle).Length, "Files in bundle"); + Assert.That (Directory.GetFileSystemEntries (outputBundle).Length, Is.EqualTo (1), "Files in bundle"); // The resulting dylib should contain 1 architecture. var nonFatBinary = Path.Combine (outputBundle, "libframework.dylib"); Assert.That (nonFatBinary, Does.Exist, "Existence"); var machO = MachO.Read (nonFatBinary).ToArray (); - Assert.AreEqual (1, machO.Length, "Architecture Count"); + Assert.That (machO.Length, Is.EqualTo (1), "Architecture Count"); // and the file size should be the same as the input Assert.That (new FileInfo (fileA).Length, Is.EqualTo (new FileInfo (nonFatBinary).Length), "File length"); @@ -287,15 +287,15 @@ public void TestDirectoriesAsSymlinks () File.WriteAllText (fileB, "A"); var linkA = Path.Combine (bundleA, "B"); var linkB = Path.Combine (bundleB, "B"); - Assert.IsTrue (PathUtils.Symlink ("A", linkA), "Link A"); - Assert.IsTrue (PathUtils.Symlink ("A", linkB), "Link B"); + Assert.That (PathUtils.Symlink ("A", linkA), Is.True, "Link A"); + Assert.That (PathUtils.Symlink ("A", linkB), Is.True, "Link B"); var outputBundle = Path.Combine (Cache.CreateTemporaryDirectory (), "Merged.app"); var task = CreateTask (outputBundle, bundleA, bundleB); ExecuteTask (task); - Assert.IsTrue (PathUtils.IsSymlink (Path.Combine (outputBundle, "B")), "IsSymlink"); - Assert.IsFalse (PathUtils.IsSymlink (Path.Combine (outputBundle, "A", "A.txt")), "IsSymlink"); - Assert.IsFalse (PathUtils.IsSymlink (Path.Combine (outputBundle, "B", "A.txt")), "IsSymlink"); + Assert.That (PathUtils.IsSymlink (Path.Combine (outputBundle, "B")), Is.True, "IsSymlink"); + Assert.That (PathUtils.IsSymlink (Path.Combine (outputBundle, "A", "A.txt")), Is.False, "IsSymlink"); + Assert.That (PathUtils.IsSymlink (Path.Combine (outputBundle, "B", "A.txt")), Is.False, "IsSymlink"); } } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ParseBundlerArgumentsTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ParseBundlerArgumentsTests.cs index feeeb720781f..48ea288f44ad 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ParseBundlerArgumentsTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ParseBundlerArgumentsTests.cs @@ -16,14 +16,14 @@ public void NoExtraArgs () { var task = CreateTask (); ExecuteTask (task); - Assert.AreEqual ("false", task.NoSymbolStrip, "nosymbolstrip"); - Assert.AreEqual ("false", task.NoDSymUtil, "nodsymutil"); + Assert.That (task.NoSymbolStrip, Is.EqualTo ("false"), "nosymbolstrip"); + Assert.That (task.NoDSymUtil, Is.EqualTo ("false"), "nodsymutil"); task = CreateTask (); task.ExtraArgs = string.Empty; ExecuteTask (task); - Assert.AreEqual ("false", task.NoSymbolStrip, "nosymbolstrip"); - Assert.AreEqual ("false", task.NoDSymUtil, "nodsymutil"); + Assert.That (task.NoSymbolStrip, Is.EqualTo ("false"), "nosymbolstrip"); + Assert.That (task.NoDSymUtil, Is.EqualTo ("false"), "nodsymutil"); } [Test] @@ -48,16 +48,16 @@ public void NoSymbolStrip () var task = CreateTask (); task.ExtraArgs = variation; ExecuteTask (task, message: "execute: " + variation); - Assert.AreEqual ("false", task.NoSymbolStrip, "nosymbolstrip: " + variation); - Assert.AreEqual ("false", task.NoDSymUtil, "nodsymutil: " + variation); + Assert.That (task.NoSymbolStrip, Is.EqualTo ("false"), "nosymbolstrip: " + variation); + Assert.That (task.NoDSymUtil, Is.EqualTo ("false"), "nodsymutil: " + variation); } foreach (var variation in true_variations) { var task = CreateTask (); task.ExtraArgs = variation; ExecuteTask (task, message: "execute: " + variation); - Assert.AreEqual ("true", task.NoSymbolStrip, "nosymbolstrip: " + variation); - Assert.AreEqual ("false", task.NoDSymUtil, "nodsymutil: " + variation); + Assert.That (task.NoSymbolStrip, Is.EqualTo ("true"), "nosymbolstrip: " + variation); + Assert.That (task.NoDSymUtil, Is.EqualTo ("false"), "nodsymutil: " + variation); } } @@ -86,16 +86,16 @@ public void NoDSymUtil () var task = CreateTask (); task.ExtraArgs = variation; ExecuteTask (task, message: "execute: " + variation); - Assert.AreEqual ("false", task.NoSymbolStrip, "nosymbolstrip: " + variation); - Assert.AreEqual ("false", task.NoDSymUtil, "nodsymutil: " + variation); + Assert.That (task.NoSymbolStrip, Is.EqualTo ("false"), "nosymbolstrip: " + variation); + Assert.That (task.NoDSymUtil, Is.EqualTo ("false"), "nodsymutil: " + variation); } foreach (var variation in true_variations) { var task = CreateTask (); task.ExtraArgs = variation; ExecuteTask (task, message: "execute: " + variation); - Assert.AreEqual ("false", task.NoSymbolStrip, "nosymbolstrip: " + variation); - Assert.AreEqual ("true", task.NoDSymUtil, "nodsymutil: " + variation); + Assert.That (task.NoSymbolStrip, Is.EqualTo ("false"), "nosymbolstrip: " + variation); + Assert.That (task.NoDSymUtil, Is.EqualTo ("true"), "nodsymutil: " + variation); } } @@ -117,7 +117,7 @@ public void MarshalManagedExceptionMode (string input, string output, string exi task.MarshalManagedExceptionMode = existingValue; task.ExtraArgs = input; ExecuteTask (task, message: input); - Assert.AreEqual (output, task.MarshalManagedExceptionMode, output); + Assert.That (task.MarshalManagedExceptionMode, Is.EqualTo (output), output); } [Test] @@ -138,7 +138,7 @@ public void MarshalObjetiveCExceptionMode (string input, string output, string e task.MarshalObjectiveCExceptionMode = existingValue; task.ExtraArgs = input; ExecuteTask (task, message: input); - Assert.AreEqual (output, task.MarshalObjectiveCExceptionMode, output); + Assert.That (task.MarshalObjectiveCExceptionMode, Is.EqualTo (output), output); } [Test] @@ -156,7 +156,7 @@ public void Optimize (string input, string output) var task = CreateTask (); task.ExtraArgs = input; ExecuteTask (task, message: input); - Assert.AreEqual (output, task.Optimize, output); + Assert.That (task.Optimize, Is.EqualTo (output), output); } [TestCase ("--registrar", "")] @@ -172,7 +172,7 @@ public void Registrar (string input, string output) var task = CreateTask (); task.ExtraArgs = input; ExecuteTask (task, message: input); - Assert.AreEqual (output, task.Registrar, output); + Assert.That (task.Registrar, Is.EqualTo (output), output); } [TestCase ("--xml", null, "")] @@ -198,7 +198,7 @@ void XmlDefinitionsTest (string input, string existing, string output) task.XmlDefinitions = existing.Split (new char [] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select (v => new TaskItem (v)).ToArray (); task.ExtraArgs = input; ExecuteTask (task, message: input); - Assert.AreEqual (output, string.Join (";", task.XmlDefinitions.Select (v => v.ItemSpec).ToArray ()), output); + Assert.That (string.Join (";", task.XmlDefinitions.Select (v => v.ItemSpec).ToArray ()), Is.EqualTo (output), output); } [TestCase ("/xml:\\path\\a /xml:/path/b", null, "/path/a;/path/b")] @@ -219,7 +219,7 @@ public void CustomBundleName (string input, string output) var task = CreateTask (); task.ExtraArgs = input; ExecuteTask (task, message: input); - Assert.AreEqual (output, task.CustomBundleName, output); + Assert.That (task.CustomBundleName, Is.EqualTo (output), output); } [TestCase ("--gcc_flags -dead_strip", new string [] { "-dead_strip" })] @@ -236,7 +236,7 @@ public void CustomLinkFlags (string input, string [] output) var task = CreateTask (); task.ExtraArgs = input; ExecuteTask (task, message: input); - CollectionAssert.AreEquivalent (output, task.CustomLinkFlags.Select (v => v.ItemSpec).ToArray (), string.Join (" ", output)); + Assert.That (task.CustomLinkFlags.Select (v => v.ItemSpec).ToArray (), Is.EquivalentTo (output), string.Join (" ", output)); } [TestCase ("-v", "1")] @@ -250,7 +250,7 @@ public void Verbosity (string input, string output) var task = CreateTask (); task.ExtraArgs = input; ExecuteTask (task, message: input); - Assert.AreEqual (output, task.Verbosity, "Equality"); + Assert.That (task.BundlerVerbosity, Is.EqualTo (output), "Equality"); } [TestCase ("--nowarn", "-1")] @@ -264,7 +264,7 @@ public void NoWarn (string input, string output) var task = CreateTask (); task.ExtraArgs = input; ExecuteTask (task, message: input); - Assert.AreEqual (output, task.NoWarn, output); + Assert.That (task.NoWarn, Is.EqualTo (output), output); } [TestCase ("--warnaserror", "-1")] @@ -278,7 +278,7 @@ public void WarnAsError (string input, string output) var task = CreateTask (); task.ExtraArgs = input; ExecuteTask (task, message: input); - Assert.AreEqual (output, task.WarnAsError, output); + Assert.That (task.WarnAsError, Is.EqualTo (output), output); } } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/PropertyListEditorTaskTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/PropertyListEditorTaskTests.cs index 120a3b6d6838..b91585a23bf7 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/PropertyListEditorTaskTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/PropertyListEditorTaskTests.cs @@ -11,10 +11,10 @@ namespace Xamarin.MacDev.Tasks { public class PropertyListEditorTaskTests : TestBase { static void CheckArray (PArray array, PArray expected) { - Assert.AreEqual (expected.Count, array.Count, "Unexpected number of array elements"); + Assert.That (array.Count, Is.EqualTo (expected.Count), "Unexpected number of array elements"); for (int i = 0; i < expected.Count; i++) { - Assert.AreEqual (expected [i].Type, array [i].Type, "Type-mismatch for array element {0}", i); + Assert.That (array [i].Type, Is.EqualTo (expected [i].Type), $"Type-mismatch for array element {i}"); CheckValue (array [i], expected [i]); } } @@ -22,10 +22,10 @@ static void CheckArray (PArray array, PArray expected) static void CheckDictionary (PDictionary dict, PDictionary expected) { foreach (var kvp in expected) { - Assert.IsTrue (dict.TryGetValue (kvp.Key, out PObject? value), "Expected key '{0}'", kvp.Key); + Assert.That (dict.TryGetValue (kvp.Key, out PObject? value), Is.True, $"Expected key '{kvp.Key}'"); if (value is null) continue; - Assert.AreEqual (kvp.Value.Type, value.Type, "Type-mismatch for '{0}'", kvp.Key); + Assert.That (value.Type, Is.EqualTo (kvp.Value.Type), $"Type-mismatch for '{kvp.Key}'"); CheckValue (value, kvp.Value); } @@ -45,22 +45,22 @@ static void CheckValue (PObject value, PObject expected) CheckArray ((PArray) value, (PArray) expected); break; case PObjectType.Real: - Assert.AreEqual (((PReal) expected).Value, ((PReal) value).Value); + Assert.That (((PReal) value).Value, Is.EqualTo (((PReal) expected).Value)); break; case PObjectType.Number: - Assert.AreEqual (((PNumber) expected).Value, ((PNumber) value).Value); + Assert.That (((PNumber) value).Value, Is.EqualTo (((PNumber) expected).Value)); break; case PObjectType.Boolean: - Assert.AreEqual (((PBoolean) expected).Value, ((PBoolean) value).Value); + Assert.That (((PBoolean) value).Value, Is.EqualTo (((PBoolean) expected).Value)); break; case PObjectType.Data: // TODO: implement this break; case PObjectType.String: - Assert.AreEqual (((PString) expected).Value, ((PString) value).Value); + Assert.That (((PString) value).Value, Is.EqualTo (((PString) expected).Value)); break; case PObjectType.Date: - Assert.AreEqual (((PDate) expected).Value, ((PDate) value).Value); + Assert.That (((PDate) value).Value, Is.EqualTo (((PDate) expected).Value)); break; } } @@ -90,7 +90,7 @@ void TestExecuteTask (string propertyList, PropertyListEditorAction action, stri var output = PObject.FromFile (task.PropertyList) ?? throw new InvalidOperationException ("PObject.FromFile returned null"); - Assert.AreEqual (expected.Type, output.Type, "Task produced the incorrect plist output."); + Assert.That (output.Type, Is.EqualTo (expected.Type), "Task produced the incorrect plist output."); CheckValue (output, expected); } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ReadAppManifestTaskTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ReadAppManifestTaskTests.cs index 1e5a9546e502..813da25c467e 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ReadAppManifestTaskTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ReadAppManifestTaskTests.cs @@ -35,7 +35,7 @@ public void MacCatalystVersionConversion () plist.SetMinimumSystemVersion ("10.15.2"); }); ExecuteTask (task); - Assert.AreEqual ("13.3", task.MinimumOSVersion, "MinimumOSVersion"); + Assert.That (task.MinimumOSVersion, Is.EqualTo ("13.3"), "MinimumOSVersion"); } [Test] diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ResolveNativeReferencesTaskTest.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ResolveNativeReferencesTaskTest.cs index ec39d36da20e..f89ae389df38 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ResolveNativeReferencesTaskTest.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TaskTests/ResolveNativeReferencesTaskTest.cs @@ -36,9 +36,9 @@ public void Xcode12_x (string targetFrameworkMoniker, bool isSimulator, string a { // on Xcode 12.2+ you get arm64 for all (iOS, tvOS) simulators var path = Path.Combine (Path.GetDirectoryName (GetType ().Assembly.Location)!, "Resources", "xcf-xcode12.2.plist"); - var plist = PDictionary.FromFile (path)!; + var plist = PDictionary.OpenFile (path); var result = ResolveNativeReferences.TryResolveXCFramework (log, plist, "N/A", targetFrameworkMoniker, isSimulator, architecture, null, out var frameworkPath); - Assert.AreEqual (result, !string.IsNullOrEmpty (expected), "result"); + Assert.That (!string.IsNullOrEmpty (expected), Is.EqualTo (result), "result"); Assert.That (frameworkPath, Is.EqualTo (expected), "frameworkPath"); } @@ -46,9 +46,9 @@ public void Xcode12_x (string targetFrameworkMoniker, bool isSimulator, string a public void PreXcode12 (string targetFrameworkMoniker, bool isSimulator, string architecture, string expected) { var path = Path.Combine (Path.GetDirectoryName (GetType ().Assembly.Location)!, "Resources", "xcf-prexcode12.plist"); - var plist = PDictionary.FromFile (path)!; + var plist = PDictionary.OpenFile (path); var result = ResolveNativeReferences.TryResolveXCFramework (log, plist, "N/A", targetFrameworkMoniker, isSimulator, architecture, null, out var frameworkPath); - Assert.AreEqual (result, !string.IsNullOrEmpty (expected), "result"); + Assert.That (!string.IsNullOrEmpty (expected), Is.EqualTo (result), "result"); Assert.That (frameworkPath, Is.EqualTo (expected), "frameworkPath"); } @@ -57,7 +57,7 @@ public void BadInfoPlist () { var plist = new PDictionary (); var result = ResolveNativeReferences.TryResolveXCFramework (log, plist, "N/A", TargetFramework.DotNet_iOS_String, false, "x86_64", null, out var frameworkPath); - Assert.IsFalse (result, "Invalid Info.plist"); + Assert.That (result, Is.False, "Invalid Info.plist"); } } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TestHelpers/TestBase.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TestHelpers/TestBase.cs index 93371c0fd435..05b391b10fbf 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TestHelpers/TestBase.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/TestHelpers/TestBase.cs @@ -73,9 +73,9 @@ public void ExecuteTask (Task task, int expectedErrorCount = 0, string message = messages = "\n\t" + string.Join ("\n\t", allEvents.Select ((v) => v.AsString ()).ToArray ()); } if (expectedErrorCount != Engine.Logger.ErrorEvents.Count) { - Assert.AreEqual (expectedErrorCount, Engine.Logger.ErrorEvents.Count, $"#RunTask-ErrorCount{(string.IsNullOrEmpty (message) ? "" : $" ({message})")}" + messages); + Assert.That (Engine.Logger.ErrorEvents.Count, Is.EqualTo (expectedErrorCount), $"#RunTask-ErrorCount{(string.IsNullOrEmpty (message) ? "" : $" ({message})")}" + messages); } - Assert.AreEqual (expectedErrorCount == 0, rv, $"Failure{(string.IsNullOrEmpty (message) ? "" : $" ({message})")}" + messages); + Assert.That (rv, Is.EqualTo (expectedErrorCount == 0), $"Failure{(string.IsNullOrEmpty (message) ? "" : $" ({message})")}" + messages); } protected string CreateTempFile (string path) diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/UtilityTests.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/UtilityTests.cs index f057607731db..4dfc91c8446b 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/UtilityTests.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/UtilityTests.cs @@ -19,7 +19,7 @@ public void TestAbsoluteToRelativePath () string rpath; rpath = PathUtils.AbsoluteToRelative ("/Users/user/source/Project", "/Users/user/Source/Project/Info.plist"); - Assert.AreEqual ("Info.plist", rpath, "#1"); + Assert.That (rpath, Is.EqualTo ("Info.plist"), "#1"); } } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/VerbosityTest.cs b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/VerbosityTest.cs index 87765cf7267e..4930ef8dc74c 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/VerbosityTest.cs +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/VerbosityTest.cs @@ -43,15 +43,15 @@ public void FromString (string commandLine, LoggerVerbosity expected) Assert.That (VerbosityUtils.GetVerbosityLevel (commandLine), Is.EqualTo (result), commandLine); } - [TestCase (LoggerVerbosity.Quiet, "-q -q -q -q")] - [TestCase (LoggerVerbosity.Minimal, "-q -q")] - [TestCase (LoggerVerbosity.Normal, "")] - [TestCase (LoggerVerbosity.Detailed, "-v -v")] - [TestCase (LoggerVerbosity.Diagnostic, "-v -v -v -v")] - [TestCase ((LoggerVerbosity) (-1), "")] - public void FromLoggerVerbosity (LoggerVerbosity v, string expectedResult) + [TestCase (LoggerVerbosity.Quiet, -4)] + [TestCase (LoggerVerbosity.Minimal, -2)] + [TestCase (LoggerVerbosity.Normal, 0)] + [TestCase (LoggerVerbosity.Detailed, 2)] + [TestCase (LoggerVerbosity.Diagnostic, 4)] + [TestCase ((LoggerVerbosity) (-1), 0)] + public void FromLoggerVerbosity (LoggerVerbosity v, int expectedResult) { - var s = String.Join (" ", VerbosityUtils.GetVerbosityLevel (v)); + var s = VerbosityUtils.GetVerbosityLevel (v); Assert.That (s, Is.EqualTo (expectedResult), v.ToString ()); } } diff --git a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/Xamarin.MacDev.Tasks.Tests.csproj b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/Xamarin.MacDev.Tasks.Tests.csproj index 9a5f7e8ff9f5..bbd8daba35b8 100644 --- a/tests/msbuild/Xamarin.MacDev.Tasks.Tests/Xamarin.MacDev.Tasks.Tests.csproj +++ b/tests/msbuild/Xamarin.MacDev.Tasks.Tests/Xamarin.MacDev.Tasks.Tests.csproj @@ -4,14 +4,11 @@ net$(BundledNETCoreAppTargetFrameworkVersion) false true - latest $(DefineConstants);MSBUILD_TASKS true ../../../product.snk $(NoWarn);MSB3277 $(NoWarn);CS1685 - true - enable true 12.0 - latest diff --git a/tests/perftest/legacy/perftest-legacy.csproj b/tests/perftest/legacy/perftest-legacy.csproj index 8f24ce3106b5..17aa1453b0b9 100644 --- a/tests/perftest/legacy/perftest-legacy.csproj +++ b/tests/perftest/legacy/perftest-legacy.csproj @@ -11,7 +11,6 @@ PerfTest v2.0 Xamarin.Mac - latest --registrar:static true None diff --git a/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Microsoft.Macios.Bindings.Analyzer.Tests.csproj b/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Microsoft.Macios.Bindings.Analyzer.Tests.csproj index 3679cb19bb65..9cdaa4af9313 100644 --- a/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Microsoft.Macios.Bindings.Analyzer.Tests.csproj +++ b/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Microsoft.Macios.Bindings.Analyzer.Tests.csproj @@ -2,9 +2,7 @@ net$(BundledNETCoreAppTargetFrameworkVersion) - enable false - true NU1608 diff --git a/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Validators/ArrayValidatorTests.cs b/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Validators/ArrayValidatorTests.cs index 5d265504094a..74b3a943027b 100644 --- a/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Validators/ArrayValidatorTests.cs +++ b/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Validators/ArrayValidatorTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable APL0003 +#pragma warning disable CS0618 // DisableZeroCopy is obsolete using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; diff --git a/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Validators/FieldValidatorTests.cs b/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Validators/FieldValidatorTests.cs index 7d9c84e75903..9571b1eb590f 100644 --- a/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Validators/FieldValidatorTests.cs +++ b/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Validators/FieldValidatorTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable APL0003 +#pragma warning disable CS0618 // DisableZeroCopy is obsolete using Microsoft.Macios.Bindings.Analyzer.Validators; using Xunit; diff --git a/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Validators/PropertyOrFieldValidatorTests.cs b/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Validators/PropertyOrFieldValidatorTests.cs index 738eded7d1a6..ca019c36bc7e 100644 --- a/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Validators/PropertyOrFieldValidatorTests.cs +++ b/tests/rgen/Microsoft.Macios.Bindings.Analyzer.Tests/Validators/PropertyOrFieldValidatorTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable APL0003 +#pragma warning disable CS0618 // DisableZeroCopy is obsolete using Microsoft.Macios.Bindings.Analyzer.Validators; using Xunit; diff --git a/tests/rgen/Microsoft.Macios.Bindings.CodeFixers.Tests/Microsoft.Macios.Bindings.CodeFixers.Tests.csproj b/tests/rgen/Microsoft.Macios.Bindings.CodeFixers.Tests/Microsoft.Macios.Bindings.CodeFixers.Tests.csproj index 1dac34ff1738..e0dbd00ba495 100644 --- a/tests/rgen/Microsoft.Macios.Bindings.CodeFixers.Tests/Microsoft.Macios.Bindings.CodeFixers.Tests.csproj +++ b/tests/rgen/Microsoft.Macios.Bindings.CodeFixers.Tests/Microsoft.Macios.Bindings.CodeFixers.Tests.csproj @@ -2,9 +2,6 @@ net$(BundledNETCoreAppTargetFrameworkVersion) - enable - latest - true false diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/Microsoft.Macios.Generator.Tests.csproj b/tests/rgen/Microsoft.Macios.Generator.Tests/Microsoft.Macios.Generator.Tests.csproj index f7795989d054..5d00980d51ba 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/Microsoft.Macios.Generator.Tests.csproj +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/Microsoft.Macios.Generator.Tests.csproj @@ -2,9 +2,7 @@ net$(BundledNETCoreAppTargetFrameworkVersion) - enable false - true NU1608 Microsoft.Macios.Generator.Tests RGEN diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/Microsoft.Macios.Transformer.Tests.csproj b/tests/rgen/Microsoft.Macios.Transformer.Tests/Microsoft.Macios.Transformer.Tests.csproj index 32570eb3f690..0656372608c8 100644 --- a/tests/rgen/Microsoft.Macios.Transformer.Tests/Microsoft.Macios.Transformer.Tests.csproj +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/Microsoft.Macios.Transformer.Tests.csproj @@ -3,7 +3,6 @@ net$(BundledNETCoreAppTargetFrameworkVersion) enable - enable false @@ -11,14 +10,6 @@ build/dotnet - - true - - - - true - - diff --git a/tests/sharpie/Sharpie.Bind.Tests/Sharpie.Bind.Tests.csproj b/tests/sharpie/Sharpie.Bind.Tests/Sharpie.Bind.Tests.csproj index ed7b97497bbe..433a6a473bb1 100644 --- a/tests/sharpie/Sharpie.Bind.Tests/Sharpie.Bind.Tests.csproj +++ b/tests/sharpie/Sharpie.Bind.Tests/Sharpie.Bind.Tests.csproj @@ -2,9 +2,7 @@ net$(BundledNETCoreAppTargetFrameworkVersion) - latest enable - enable false $(NETCoreSdkRuntimeIdentifier) diff --git a/tests/test-libraries/custom-type-assembly/custom-type-assembly.csproj b/tests/test-libraries/custom-type-assembly/custom-type-assembly.csproj index cb2f5900032c..e96b468d2244 100644 --- a/tests/test-libraries/custom-type-assembly/custom-type-assembly.csproj +++ b/tests/test-libraries/custom-type-assembly/custom-type-assembly.csproj @@ -2,7 +2,6 @@ net$(BundledNETCoreAppTargetFrameworkVersion)-macos - latest diff --git a/tests/test-libraries/testgenerator.cs b/tests/test-libraries/testgenerator.cs index b50e7b191a8c..c118503a9a17 100644 --- a/tests/test-libraries/testgenerator.cs +++ b/tests/test-libraries/testgenerator.cs @@ -953,7 +953,7 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ("\t\t\tusing (var tc = new ObjCRegistrarTest ()) {"); w.AppendLine ($"\t\t\t\tvar s = tc.PS{s};"); for (int i = 0; i < s.Length; i++) - w.AppendLine ($"\t\t\t\tAssert.AreEqual (0, s.x{i}, \"pre-#{i}\");"); + w.AppendLine ($"\t\t\t\tAssert.That (s.x{i}, Is.EqualTo (0), \"pre-#{i}\");"); w.Append ($"\t\t\t\tvar k = new S{s} () {{ "); for (int i = 0; i < s.Length; i++) w.Append ($"x{i} = ").Append (GetValue (s [i], i)).Append (", "); @@ -962,7 +962,7 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ($"\t\t\t\ttc.PS{s} = k;"); w.AppendLine ($"\t\t\t\ts = tc.PS{s};"); for (int i = 0; i < s.Length; i++) - w.AppendLine ($"\t\t\t\tAssert.AreEqual (k.x{i}, s.x{i}, \"post-#{i}\");"); + w.AppendLine ($"\t\t\t\tAssert.That (s.x{i}, Is.EqualTo (k.x{i}), \"post-#{i}\");"); w.AppendLine (); w.Append ($"\t\t\t\tvar v = new S{s} () {{ "); @@ -975,7 +975,7 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ($"\t\t\t\ttc.SetProperty{s} (v);"); w.AppendLine ($"\t\t\t\ts = tc.PS{s};"); for (int i = 0; i < s.Length; i++) - w.AppendLine ($"\t\t\t\tAssert.AreEqual (v.x{i}, s.x{i}, \"set-#{i}\");"); + w.AppendLine ($"\t\t\t\tAssert.That (s.x{i}, Is.EqualTo (v.x{i}), \"set-#{i}\");"); w.AppendLine ("\t\t\t}"); w.AppendLine ("\t\t}"); @@ -1066,32 +1066,32 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ("\t\t{"); WriteAsserts (w, v); w.AppendLine ($"\t\t\tusing (var obj = new ObjCRegistrarTest ()) {{"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.P{v.Managed}Number, \"initial null property\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.P{v.Managed}NumberNullable, \"initial nullable null property\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.Get{v.Managed}NumberNullable (), \"initial null method\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Number, Is.Null, \"initial null property\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}NumberNullable, Is.Null, \"initial nullable null property\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}NumberNullable (), Is.Null, \"initial null method\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\t{v.Managed}? value = default ({v.Managed});"); w.AppendLine ($"\t\t\t\tobj.Set{v.Managed}NumberNonNullable (value.Value);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.P{v.Managed}NumberNullable, \"nullable property after setting default value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Value, obj.P{v.Managed}NumberNonNullable, \"non-nullable property after setting default value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.Get{v.Managed}NumberNullable (), \"nullable get method after setting default value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Value, obj.Get{v.Managed}NumberNonNullable (), \"non-nullable get method after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}NumberNullable, Is.EqualTo (value), \"nullable property after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}NumberNonNullable, Is.EqualTo (value.Value), \"non-nullable property after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}NumberNullable (), Is.EqualTo (value), \"nullable get method after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}NumberNonNullable (), Is.EqualTo (value.Value), \"non-nullable get method after setting default value\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tobj.Set{v.Managed}NumberNonNullable (value.Value);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.P{v.Managed}NumberNullable, \"nullable property after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Value, obj.P{v.Managed}NumberNonNullable, \"non-nullable property after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.Get{v.Managed}NumberNullable (), \"nullable get method after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Value, obj.Get{v.Managed}NumberNonNullable (), \"non-nullable get method after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}NumberNullable, Is.EqualTo (value), \"nullable property after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}NumberNonNullable, Is.EqualTo (value.Value), \"non-nullable property after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}NumberNullable (), Is.EqualTo (value), \"nullable get method after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}NumberNonNullable (), Is.EqualTo (value.Value), \"non-nullable get method after setting custom value\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = null;"); w.AppendLine ($"\t\t\t\tobj.Set{v.Managed}NumberNullable (value);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.P{v.Managed}Number, \"null property after setting null value\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.P{v.Managed}NumberNullable, \"nullable null property after setting null value\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.Get{v.Managed}NumberNullable (), \"null method after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Number, Is.Null, \"null property after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}NumberNullable, Is.Null, \"nullable null property after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}NumberNullable (), Is.Null, \"null method after setting null value\");"); w.AppendLine ($"\t\t\t}}"); w.AppendLine ("\t\t}"); w.AppendLine (); @@ -1102,43 +1102,43 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ("\t\t{"); WriteAsserts (w, v); w.AppendLine ($"\t\t\tusing (var obj = new BindAsTestClassGenerated ()) {{"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.{v.Managed}Number, \"initial null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Number, Is.Null, \"initial null\");"); w.AppendLine ($"\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}NumberNullable:\"), IntPtr.Zero);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.{v.Managed}Number, \"null after setting null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Number, Is.Null, \"null after setting null\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Number = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}NumberNullable:\"), IntPtr.Zero);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.{v.Managed}Number, \"null after re-setting null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Number, Is.Null, \"null after re-setting null\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvar value = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tusing (var input = new NSNumber ({v.ToNSNumberCastExpression}value))"); w.AppendLine ($"\t\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}NumberNullable:\"), input.Handle);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.{v.Managed}Number, \"after setting A\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Number, Is.EqualTo (value), \"after setting A\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Number = null;"); w.AppendLine ($"\t\t\t\tusing (var input = new NSNumber ({v.ToNSNumberCastExpression}value))"); w.AppendLine ($"\t\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}NumberNonNullable:\"), input.Handle);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.{v.Managed}Number.Value, \"after setting B\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Number.Value, Is.EqualTo (value), \"after setting B\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Number = null;"); w.AppendLine ($"\t\t\t\tvar number = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"get{v.Managed}NumberNullable\")));"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (number, \"null from getter A\");"); + w.AppendLine ($"\t\t\t\tAssert.That (number, Is.Null, \"null from getter A\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Number = value;"); w.AppendLine ($"\t\t\t\tnumber = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"get{v.Managed}NumberNullable\")));"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, {v.FromNSNumberCastExpression}number{v.Map}, \"getter B\");"); + w.AppendLine ($"\t\t\t\tAssert.That ({v.FromNSNumberCastExpression}number{v.Map}, Is.EqualTo (value), \"getter B\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Number = value;"); w.AppendLine ($"\t\t\t\tnumber = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"get{v.Managed}NumberNonNullable\")));"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, {v.FromNSNumberCastExpression}number{v.Map}, \"getter C\");"); + w.AppendLine ($"\t\t\t\tAssert.That ({v.FromNSNumberCastExpression}number{v.Map}, Is.EqualTo (value), \"getter C\");"); w.AppendLine ($"\t\t\t}}"); w.AppendLine ("\t\t}"); @@ -1148,28 +1148,28 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ("\t\t{"); WriteAsserts (w, v); w.AppendLine ($"\t\t\tusing (var obj = new ObjCRegistrarTest ()) {{"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.P{v.Managed}Array, \"initial null property\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.Get{v.Managed}Array (), \"initial null method\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Array, Is.Null, \"initial null property\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}Array (), Is.Null, \"initial null method\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\t{v.Managed}[] value = null;"); w.AppendLine ($"\t\t\t\tobj.Set{v.Managed}Array (value);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.P{v.Managed}Array, \"nullable property after setting default value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.Get{v.Managed}Array (), \"nullable get method after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Array, Is.EqualTo (value), \"nullable property after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}Array (), Is.EqualTo (value), \"nullable get method after setting default value\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = new {v.Managed} [] {{ {v.ManagedNewExpression} }};"); w.AppendLine ($"\t\t\t\tobj.Set{v.Managed}Array (value);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (1, obj.P{v.Managed}Array.Length, \"nullable property after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (1, obj.Get{v.Managed}Array ().Length, \"nullable get method after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], obj.P{v.Managed}Array [0], \"nullable property after setting custom value element\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], obj.Get{v.Managed}Array () [0], \"nullable get method after setting custom value element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Array.Length, Is.EqualTo (1), \"nullable property after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}Array ().Length, Is.EqualTo (1), \"nullable get method after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Array [0], Is.EqualTo (value [0]), \"nullable property after setting custom value element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}Array () [0], Is.EqualTo (value [0]), \"nullable get method after setting custom value element\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = null;"); w.AppendLine ($"\t\t\t\tobj.Set{v.Managed}Array (value);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.P{v.Managed}Array, \"null property after setting null value\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.Get{v.Managed}Array (), \"null method after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Array, Is.Null, \"null property after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}Array (), Is.Null, \"null method after setting null value\");"); w.AppendLine ($"\t\t\t}}"); w.AppendLine ("\t\t}"); w.AppendLine (); @@ -1180,40 +1180,40 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ("\t\t{"); WriteAsserts (w, v); w.AppendLine ($"\t\t\tusing (var obj = new BindAsTestClassGenerated ()) {{"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.{v.Managed}Array, \"initial null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array, Is.Null, \"initial null\");"); w.AppendLine ($"\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}Array:\"), IntPtr.Zero);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.{v.Managed}Array, \"null after setting null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array, Is.Null, \"null after setting null\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Array = new {v.Managed} [] {{ {v.ManagedNewExpression} }};"); w.AppendLine ($"\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}Array:\"), IntPtr.Zero);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.{v.Managed}Array, \"null after re-setting null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array, Is.Null, \"null after re-setting null\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvar value = new {v.Managed} [] {{ {v.ManagedNewExpression} }};"); w.AppendLine ($"\t\t\t\tusing (var input = NSArray.FromNSObjects<{v.Managed}> ((v) => new NSNumber ({v.ToNSNumberCastExpression}v), value))"); w.AppendLine ($"\t\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}Array:\"), input.Handle);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Length, obj.{v.Managed}Array.Length, \"after setting A\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], obj.{v.Managed}Array [0], \"after setting A element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array.Length, Is.EqualTo (value.Length), \"after setting A\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array [0], Is.EqualTo (value [0]), \"after setting A element\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Array = null;"); w.AppendLine ($"\t\t\t\tusing (var input = NSArray.FromNSObjects<{v.Managed}> ((v) => new NSNumber ({v.ToNSNumberCastExpression}v), value))"); w.AppendLine ($"\t\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}Array:\"), input.Handle);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Length, obj.{v.Managed}Array.Length, \"after setting B\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], obj.{v.Managed}Array [0], \"after setting B element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array.Length, Is.EqualTo (value.Length), \"after setting B\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array [0], Is.EqualTo (value [0]), \"after setting B element\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Array = null;"); w.AppendLine ($"\t\t\t\tvar array = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"get{v.Managed}Array\")));"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (array, \"null from getter A\");"); + w.AppendLine ($"\t\t\t\tAssert.That (array, Is.Null, \"null from getter A\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = new {v.Managed} [] {{ {v.ManagedNewExpression} }};"); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Array = value;"); w.AppendLine ($"\t\t\t\tarray = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"get{v.Managed}Array\")));"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual ((nuint) value.Length, array.Count, \"getter B\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], {v.FromNSNumberCastExpression}array.GetItem (0){v.Map}, \"getter B element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (array.Count, Is.EqualTo ((nuint) value.Length), \"getter B\");"); + w.AppendLine ($"\t\t\t\tAssert.That ({v.FromNSNumberCastExpression}array.GetItem (0){v.Map}, Is.EqualTo (value [0]), \"getter B element\");"); w.AppendLine (); w.AppendLine ($"\t\t\t}}"); @@ -1236,32 +1236,32 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ("\t\t{"); WriteAsserts (w, v); w.AppendLine ($"\t\t\tusing (var obj = new ObjCRegistrarTest ()) {{"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.P{v.Managed}Value, \"initial null property\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.P{v.Managed}ValueNullable, \"initial nullable null property\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.Get{v.Managed}ValueNullable (), \"initial null method\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Value, Is.Null, \"initial null property\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}ValueNullable, Is.Null, \"initial nullable null property\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}ValueNullable (), Is.Null, \"initial null method\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\t{v.Managed}? value = default ({v.Managed});"); w.AppendLine ($"\t\t\t\tobj.Set{v.Managed}ValueNonNullable (value.Value);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.P{v.Managed}ValueNullable, \"nullable property after setting default value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Value, obj.P{v.Managed}ValueNonNullable, \"non-nullable property after setting default value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.Get{v.Managed}ValueNullable (), \"nullable get method after setting default value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Value, obj.Get{v.Managed}ValueNonNullable (), \"non-nullable get method after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}ValueNullable, Is.EqualTo (value), \"nullable property after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}ValueNonNullable, Is.EqualTo (value.Value), \"non-nullable property after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}ValueNullable (), Is.EqualTo (value), \"nullable get method after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}ValueNonNullable (), Is.EqualTo (value.Value), \"non-nullable get method after setting default value\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tobj.Set{v.Managed}ValueNonNullable (value.Value);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.P{v.Managed}ValueNullable, \"nullable property after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Value, obj.P{v.Managed}ValueNonNullable, \"non-nullable property after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.Get{v.Managed}ValueNullable (), \"nullable get method after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Value, obj.Get{v.Managed}ValueNonNullable (), \"non-nullable get method after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}ValueNullable, Is.EqualTo (value), \"nullable property after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}ValueNonNullable, Is.EqualTo (value.Value), \"non-nullable property after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}ValueNullable (), Is.EqualTo (value), \"nullable get method after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}ValueNonNullable (), Is.EqualTo (value.Value), \"non-nullable get method after setting custom value\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = null;"); w.AppendLine ($"\t\t\t\tobj.Set{v.Managed}ValueNullable (value);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.P{v.Managed}Value, \"null property after setting null value\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.P{v.Managed}ValueNullable, \"nullable null property after setting null value\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.Get{v.Managed}ValueNullable (), \"null method after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Value, Is.Null, \"null property after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}ValueNullable, Is.Null, \"nullable null property after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}ValueNullable (), Is.Null, \"null method after setting null value\");"); w.AppendLine ($"\t\t\t}}"); w.AppendLine ("\t\t}"); w.AppendLine (); @@ -1272,43 +1272,43 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ("\t\t{"); WriteAsserts (w, v); w.AppendLine ($"\t\t\tusing (var obj = new BindAsTestClassGenerated ()) {{"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.{v.Managed}Value, \"initial null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Value, Is.Null, \"initial null\");"); w.AppendLine ($"\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}ValueNullable:\"), IntPtr.Zero);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.{v.Managed}Value, \"null after setting null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Value, Is.Null, \"null after setting null\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Value = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}ValueNullable:\"), IntPtr.Zero);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.{v.Managed}Value, \"null after re-setting null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Value, Is.Null, \"null after re-setting null\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvar value = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tusing (var input = NSValue.{v.MapFrom} (value))"); w.AppendLine ($"\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}ValueNullable:\"), input.Handle);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.{v.Managed}Value, \"after setting A\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Value, Is.EqualTo (value), \"after setting A\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Value = null;"); w.AppendLine ($"\t\t\t\tusing (var input = NSValue.{v.MapFrom} (value))"); w.AppendLine ($"\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}ValueNonNullable:\"), input.Handle);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.{v.Managed}Value, \"after setting B\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Value, Is.EqualTo (value), \"after setting B\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Value = null;"); w.AppendLine ($"\t\t\t\tvar Value = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"get{v.Managed}ValueNullable\")));"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (Value, \"null from getter A\");"); + w.AppendLine ($"\t\t\t\tAssert.That (Value, Is.Null, \"null from getter A\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Value = value;"); w.AppendLine ($"\t\t\t\tValue = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"get{v.Managed}ValueNullable\")));"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, Value{v.Map}, \"getter B\");"); + w.AppendLine ($"\t\t\t\tAssert.That (Value{v.Map}, Is.EqualTo (value), \"getter B\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Value = value;"); w.AppendLine ($"\t\t\t\tValue = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"get{v.Managed}ValueNonNullable\")));"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, Value{v.Map}, \"getter C\");"); + w.AppendLine ($"\t\t\t\tAssert.That (Value{v.Map}, Is.EqualTo (value), \"getter C\");"); w.AppendLine ($"\t\t\t}}"); w.AppendLine ("\t\t}"); @@ -1318,28 +1318,28 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ("\t\t{"); WriteAsserts (w, v); w.AppendLine ($"\t\t\tusing (var obj = new ObjCRegistrarTest ()) {{"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.P{v.Managed}Array, \"initial null property\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.Get{v.Managed}Array (), \"initial null method\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Array, Is.Null, \"initial null property\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}Array (), Is.Null, \"initial null method\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\t{v.Managed}[] value = null;"); w.AppendLine ($"\t\t\t\tobj.Set{v.Managed}Array (value);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.P{v.Managed}Array, \"nullable property after setting default value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.Get{v.Managed}Array (), \"nullable get method after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Array, Is.EqualTo (value), \"nullable property after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}Array (), Is.EqualTo (value), \"nullable get method after setting default value\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = new {v.Managed} [] {{ {v.ManagedNewExpression} }};"); w.AppendLine ($"\t\t\t\tobj.Set{v.Managed}Array (value);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (1, obj.P{v.Managed}Array.Length, \"nullable property after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (1, obj.Get{v.Managed}Array ().Length, \"nullable get method after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], obj.P{v.Managed}Array [0], \"nullable property after setting custom value element\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], obj.Get{v.Managed}Array () [0], \"nullable get method after setting custom value element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Array.Length, Is.EqualTo (1), \"nullable property after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}Array ().Length, Is.EqualTo (1), \"nullable get method after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Array [0], Is.EqualTo (value [0]), \"nullable property after setting custom value element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}Array () [0], Is.EqualTo (value [0]), \"nullable get method after setting custom value element\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = null;"); w.AppendLine ($"\t\t\t\tobj.Set{v.Managed}Array (value);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.P{v.Managed}Array, \"null property after setting null value\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.Get{v.Managed}Array (), \"null method after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.P{v.Managed}Array, Is.Null, \"null property after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.Get{v.Managed}Array (), Is.Null, \"null method after setting null value\");"); w.AppendLine ($"\t\t\t}}"); w.AppendLine ("\t\t}"); w.AppendLine (); @@ -1350,40 +1350,40 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ("\t\t{"); WriteAsserts (w, v); w.AppendLine ($"\t\t\tusing (var obj = new BindAsTestClassGenerated ()) {{"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.{v.Managed}Array, \"initial null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array, Is.Null, \"initial null\");"); w.AppendLine ($"\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}Array:\"), IntPtr.Zero);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.{v.Managed}Array, \"null after setting null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array, Is.Null, \"null after setting null\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Array = new {v.Managed} [] {{ {v.ManagedNewExpression} }};"); w.AppendLine ($"\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}Array:\"), IntPtr.Zero);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.{v.Managed}Array, \"null after re-setting null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array, Is.Null, \"null after re-setting null\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvar value = new {v.Managed} [] {{ {v.ManagedNewExpression} }};"); w.AppendLine ($"\t\t\t\tusing (var input = NSArray.FromNSObjects<{v.Managed}> ((v) => NSValue.{v.MapFrom} (v), value))"); w.AppendLine ($"\t\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}Array:\"), input.Handle);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Length, obj.{v.Managed}Array.Length, \"after setting A\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], obj.{v.Managed}Array [0], \"after setting A element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array.Length, Is.EqualTo (value.Length), \"after setting A\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array [0], Is.EqualTo (value [0]), \"after setting A element\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Array = null;"); w.AppendLine ($"\t\t\t\tusing (var input = NSArray.FromNSObjects<{v.Managed}> ((v) => NSValue.{v.MapFrom} (v), value))"); w.AppendLine ($"\t\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"set{v.Managed}Array:\"), input.Handle);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Length, obj.{v.Managed}Array.Length, \"after setting B\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], obj.{v.Managed}Array [0], \"after setting B element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array.Length, Is.EqualTo (value.Length), \"after setting B\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.{v.Managed}Array [0], Is.EqualTo (value [0]), \"after setting B element\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Array = null;"); w.AppendLine ($"\t\t\t\tvar array = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"get{v.Managed}Array\")));"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (array, \"null from getter A\");"); + w.AppendLine ($"\t\t\t\tAssert.That (array, Is.Null, \"null from getter A\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = new {v.Managed} [] {{ {v.ManagedNewExpression} }};"); w.AppendLine ($"\t\t\t\tobj.{v.Managed}Array = value;"); w.AppendLine ($"\t\t\t\tarray = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"get{v.Managed}Array\")));"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual ((nuint) value.Length, array.Count, \"getter B\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], array.GetItem (0){v.Map}, \"getter B element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (array.Count, Is.EqualTo ((nuint) value.Length), \"getter B\");"); + w.AppendLine ($"\t\t\t\tAssert.That (array.GetItem (0){v.Map}, Is.EqualTo (value [0]), \"getter B element\");"); w.AppendLine ($"\t\t\t}}"); w.AppendLine ("\t\t}"); w.AppendLine (); @@ -1406,28 +1406,28 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ($"\t\t\tusing (var obj = new ObjCRegistrarTest ()) {{"); w.AppendLine ($"\t\t\t\tAssert.Throws (() => {{ Console.WriteLine (obj.PSmart{v.Managed}Property); }}, \"initial zero property\");"); w.AppendLine ($"\t\t\t\tAssert.Throws (() => {{ Console.WriteLine (obj.GetSmart{v.Managed}Value ()); }}, \"initial zero method\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.GetSmartNullable{v.Managed}Value (), \"initial null method\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.GetSmartNullable{v.Managed}Value (), Is.Null, \"initial null method\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\t{v.Managed}? value = default ({v.Managed});"); w.AppendLine ($"\t\t\t\tobj.SetSmartNullable{v.Managed}Value (value);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Value, obj.PSmart{v.Managed}Property, \"zero property after setting default value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Value, obj.GetSmart{v.Managed}Value (), \"non-nullable property after setting default value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.GetSmartNullable{v.Managed}Value (), \"nullable get method after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Property, Is.EqualTo (value.Value), \"zero property after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.GetSmart{v.Managed}Value (), Is.EqualTo (value.Value), \"non-nullable property after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.GetSmartNullable{v.Managed}Value (), Is.EqualTo (value), \"nullable get method after setting default value\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tobj.SetSmart{v.Managed}Value (value.Value);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Value, obj.PSmart{v.Managed}Property, \"non-nullable property after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.GetSmartNullable{v.Managed}Value (), \"nullable get method after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Value, obj.GetSmart{v.Managed}Value (), \"non-nullable get method after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Property, Is.EqualTo (value.Value), \"non-nullable property after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.GetSmartNullable{v.Managed}Value (), Is.EqualTo (value), \"nullable get method after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.GetSmart{v.Managed}Value (), Is.EqualTo (value.Value), \"non-nullable get method after setting custom value\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = null;"); w.AppendLine ($"\t\t\t\tobj.SetSmartNullable{v.Managed}Value (value);"); w.AppendLine ($"\t\t\t\tAssert.Throws (() => {{ Console.WriteLine (obj.PSmart{v.Managed}Property); }}, \"null property after setting null value\");"); w.AppendLine ($"\t\t\t\tAssert.Throws (() => {{ Console.WriteLine (obj.GetSmart{v.Managed}Value ()); }}, \"non-nullable method after setting null value\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.GetSmartNullable{v.Managed}Value (), \"null method after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.GetSmartNullable{v.Managed}Value (), Is.Null, \"null method after setting null value\");"); w.AppendLine ($"\t\t\t}}"); w.AppendLine ("\t\t}"); w.AppendLine (); @@ -1451,30 +1451,30 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ($"\t\t\t\tvar value = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tusing (var input = value.GetConstant ())"); w.AppendLine ($"\t\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"setSmartNullable{v.Managed}Value:\"), input.Handle);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.PSmart{v.Managed}Property, \"after setting A\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Property, Is.EqualTo (value), \"after setting A\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.PSmart{v.Managed}Property = 0;"); w.AppendLine ($"\t\t\t\tusing (var input = value.GetConstant ())"); w.AppendLine ($"\t\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"setSmart{v.Managed}Value:\"), input.Handle);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.PSmart{v.Managed}Property, \"after setting B\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Property, Is.EqualTo (value), \"after setting B\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.PSmart{v.Managed}Property = 0;"); w.AppendLine ($"\t\t\t\tvar Value = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"getSmartNullable{v.Managed}Value\")));"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (default ({v.Managed}).GetConstant ().ToString (), Value.ToString (), \"zero from getter A\");"); + w.AppendLine ($"\t\t\t\tAssert.That (Value.ToString (), Is.EqualTo (default ({v.Managed}).GetConstant ().ToString ()), \"zero from getter A\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tobj.PSmart{v.Managed}Property = value;"); w.AppendLine ($"\t\t\t\tValue = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"getSmartNullable{v.Managed}Value\")));"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, {v.Managed}Extensions.GetValue (Value), \"getter B\");"); + w.AppendLine ($"\t\t\t\tAssert.That ({v.Managed}Extensions.GetValue (Value), Is.EqualTo (value), \"getter B\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = {v.ManagedNewExpression};"); w.AppendLine ($"\t\t\t\tobj.PSmart{v.Managed}Property = value;"); w.AppendLine ($"\t\t\t\tValue = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"getSmart{v.Managed}Value\")));"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, {v.Managed}Extensions.GetValue (Value), \"getter C\");"); + w.AppendLine ($"\t\t\t\tAssert.That ({v.Managed}Extensions.GetValue (Value), Is.EqualTo (value), \"getter C\");"); w.AppendLine ($"\t\t\t}}"); w.AppendLine ("\t\t}"); @@ -1484,28 +1484,28 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ("\t\t{"); WriteAsserts (w, v); w.AppendLine ($"\t\t\tusing (var obj = new ObjCRegistrarTest ()) {{"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.PSmart{v.Managed}Properties, \"initial null property\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.GetSmart{v.Managed}Values (), \"initial null method\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Properties, Is.Null, \"initial null property\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.GetSmart{v.Managed}Values (), Is.Null, \"initial null method\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\t{v.Managed}[] value = null;"); w.AppendLine ($"\t\t\t\tobj.SetSmart{v.Managed}Values (value);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.PSmart{v.Managed}Properties, \"nullable property after setting default value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value, obj.GetSmart{v.Managed}Values (), \"nullable get method after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Properties, Is.EqualTo (value), \"nullable property after setting default value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.GetSmart{v.Managed}Values (), Is.EqualTo (value), \"nullable get method after setting default value\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = new {v.Managed} [] {{ {v.ManagedNewExpression} }};"); w.AppendLine ($"\t\t\t\tobj.SetSmart{v.Managed}Values (value);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (1, obj.PSmart{v.Managed}Properties.Length, \"nullable property after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (1, obj.GetSmart{v.Managed}Values ().Length, \"nullable get method after setting custom value\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], obj.PSmart{v.Managed}Properties [0], \"nullable property after setting custom value element\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], obj.GetSmart{v.Managed}Values () [0], \"nullable get method after setting custom value element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Properties.Length, Is.EqualTo (1), \"nullable property after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.GetSmart{v.Managed}Values ().Length, Is.EqualTo (1), \"nullable get method after setting custom value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Properties [0], Is.EqualTo (value [0]), \"nullable property after setting custom value element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.GetSmart{v.Managed}Values () [0], Is.EqualTo (value [0]), \"nullable get method after setting custom value element\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = null;"); w.AppendLine ($"\t\t\t\tobj.SetSmart{v.Managed}Values (value);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.PSmart{v.Managed}Properties, \"null property after setting null value\");"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.GetSmart{v.Managed}Values (), \"null method after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Properties, Is.Null, \"null property after setting null value\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.GetSmart{v.Managed}Values (), Is.Null, \"null method after setting null value\");"); w.AppendLine ($"\t\t\t}}"); w.AppendLine ("\t\t}"); w.AppendLine (); @@ -1516,40 +1516,40 @@ public partial class RegistrarTestGenerated {"); w.AppendLine ("\t\t{"); WriteAsserts (w, v); w.AppendLine ($"\t\t\tusing (var obj = new BindAsTestClassGenerated ()) {{"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.PSmart{v.Managed}Properties, \"initial null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Properties, Is.Null, \"initial null\");"); w.AppendLine ($"\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"setSmart{v.Managed}Values:\"), IntPtr.Zero);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.PSmart{v.Managed}Properties, \"null after setting null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Properties, Is.Null, \"null after setting null\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.PSmart{v.Managed}Properties = new {v.Managed} [] {{ {v.ManagedNewExpression} }};"); w.AppendLine ($"\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"setSmart{v.Managed}Values:\"), IntPtr.Zero);"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (obj.PSmart{v.Managed}Properties, \"null after re-setting null\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Properties, Is.Null, \"null after re-setting null\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvar value = new {v.Managed} [] {{ {v.ManagedNewExpression} }};"); w.AppendLine ($"\t\t\t\tusing (var input = NSArray.FromNSObjects<{v.Managed}> ((v) => v.GetConstant (), value))"); w.AppendLine ($"\t\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"setSmart{v.Managed}Values:\"), input.Handle);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Length, obj.PSmart{v.Managed}Properties.Length, \"after setting A\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], obj.PSmart{v.Managed}Properties [0], \"after setting A element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Properties.Length, Is.EqualTo (value.Length), \"after setting A\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Properties [0], Is.EqualTo (value [0]), \"after setting A element\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.PSmart{v.Managed}Properties = null;"); w.AppendLine ($"\t\t\t\tusing (var input = NSArray.FromNSObjects<{v.Managed}> ((v) => v.GetConstant (), value))"); w.AppendLine ($"\t\t\t\t\tMessaging.void_objc_msgSend_IntPtr (obj.Handle, Selector.GetHandle (\"setSmart{v.Managed}Values:\"), input.Handle);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value.Length, obj.PSmart{v.Managed}Properties.Length, \"after setting B\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], obj.PSmart{v.Managed}Properties [0], \"after setting B element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Properties.Length, Is.EqualTo (value.Length), \"after setting B\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.PSmart{v.Managed}Properties [0], Is.EqualTo (value [0]), \"after setting B element\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tobj.PSmart{v.Managed}Properties = null;"); w.AppendLine ($"\t\t\t\tvar array = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"getSmart{v.Managed}Values\")));"); - w.AppendLine ($"\t\t\t\tAssert.IsNull (array, \"null from getter A\");"); + w.AppendLine ($"\t\t\t\tAssert.That (array, Is.Null, \"null from getter A\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\tvalue = new {v.Managed} [] {{ {v.ManagedNewExpression} }};"); w.AppendLine ($"\t\t\t\tobj.PSmart{v.Managed}Properties = value;"); w.AppendLine ($"\t\t\t\tarray = Runtime.GetNSObject (Messaging.IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle (\"getSmart{v.Managed}Values\")));"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual ((nuint) value.Length, array.Count, \"getter B\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (value [0], {v.Managed}Extensions.GetValue (array.GetItem (0)), \"getter B element\");"); + w.AppendLine ($"\t\t\t\tAssert.That (array.Count, Is.EqualTo ((nuint) value.Length), \"getter B\");"); + w.AppendLine ($"\t\t\t\tAssert.That ({v.Managed}Extensions.GetValue (array.GetItem (0)), Is.EqualTo (value [0]), \"getter B element\");"); w.AppendLine ($"\t\t\t}}"); w.AppendLine ("\t\t}"); w.AppendLine (); @@ -1720,7 +1720,7 @@ public partial class TrampolineTestGenerated {"); w.AppendLine ($"\t\t\t\t\trv = S{s}_objc_msgSend (obj.Handle, new Selector (\"Test_{s}Struct\").Handle);"); w.AppendLine ($"\t\t\t\t}}"); } - w.AppendLine ($"\t\t\t\tAssert.AreEqual (({GenerateNewExpression (s, 1)}).ToString (), rv.ToString (), \"a\");"); + w.AppendLine ($"\t\t\t\tAssert.That (rv.ToString (), Is.EqualTo (({GenerateNewExpression (s, 1)}).ToString ()), \"a\");"); w.AppendLine (); WriteStretConditions (w, s, out never); @@ -1732,7 +1732,7 @@ public partial class TrampolineTestGenerated {"); w.AppendLine ($"\t\t\t\t\trv = S{s}_objc_msgSend (class_ptr, new Selector (\"Test_Static{s}Struct\").Handle);"); w.AppendLine ($"\t\t\t\t}}"); } - w.AppendLine ($"\t\t\t\tAssert.AreEqual (({GenerateNewExpression (s, 2)}).ToString (), rv.ToString (), \"a\");"); + w.AppendLine ($"\t\t\t\tAssert.That (rv.ToString (), Is.EqualTo (({GenerateNewExpression (s, 2)}).ToString ()), \"a\");"); w.AppendLine (); WriteStretConditions (w, s, out never); @@ -1744,7 +1744,7 @@ public partial class TrampolineTestGenerated {"); w.AppendLine ($"\t\t\t\t\trv = S{s}_objc_msgSend (obj.Handle, new Selector (\"Test_{s}StructProperty\").Handle);"); w.AppendLine ($"\t\t\t\t}}"); } - w.AppendLine ($"\t\t\t\tAssert.AreEqual (({GenerateNewExpression (s, 3)}).ToString (), rv.ToString (), \"a\");"); + w.AppendLine ($"\t\t\t\tAssert.That (rv.ToString (), Is.EqualTo (({GenerateNewExpression (s, 3)}).ToString ()), \"a\");"); w.AppendLine (); WriteStretConditions (w, s, out never); @@ -1756,7 +1756,7 @@ public partial class TrampolineTestGenerated {"); w.AppendLine ($"\t\t\t\t\trv = S{s}_objc_msgSend (class_ptr, new Selector (\"Test_Static{s}StructProperty\").Handle);"); w.AppendLine ($"\t\t\t\t}}"); } - w.AppendLine ($"\t\t\t\tAssert.AreEqual (({GenerateNewExpression (s, 4)}).ToString (), rv.ToString (), \"a\");"); + w.AppendLine ($"\t\t\t\tAssert.That (rv.ToString (), Is.EqualTo (({GenerateNewExpression (s, 4)}).ToString ()), \"a\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\trvd = 0;"); @@ -1769,8 +1769,8 @@ public partial class TrampolineTestGenerated {"); w.AppendLine ($"\t\t\t\t\trv = S{s}_objc_msgSend_out_double (obj.Handle, new Selector (\"Test_{s}Struct_out_double:\").Handle, out rvd);"); w.AppendLine ($"\t\t\t\t}}"); } - w.AppendLine ($"\t\t\t\tAssert.AreEqual (({GenerateNewExpression (s, 5)}).ToString (), rv.ToString (), \"a\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (3.14, rvd, \"double out\");"); + w.AppendLine ($"\t\t\t\tAssert.That (rv.ToString (), Is.EqualTo (({GenerateNewExpression (s, 5)}).ToString ()), \"a\");"); + w.AppendLine ($"\t\t\t\tAssert.That (rvd, Is.EqualTo (3.14), \"double out\");"); w.AppendLine (); w.AppendLine ($"\t\t\t\trvf = 0;"); @@ -1783,8 +1783,8 @@ public partial class TrampolineTestGenerated {"); w.AppendLine ($"\t\t\t\t\trv = S{s}_objc_msgSend_out_float (class_ptr, new Selector (\"Test_Static{s}Struct_out_float:\").Handle, out rvf);"); w.AppendLine ($"\t\t\t\t}}"); } - w.AppendLine ($"\t\t\t\tAssert.AreEqual (({GenerateNewExpression (s, 6)}).ToString (), rv.ToString (), \"a\");"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (3.15f, rvf, \"float out\");"); + w.AppendLine ($"\t\t\t\tAssert.That (rv.ToString (), Is.EqualTo (({GenerateNewExpression (s, 6)}).ToString ()), \"a\");"); + w.AppendLine ($"\t\t\t\tAssert.That (rvf, Is.EqualTo (3.15f), \"float out\");"); w.AppendLine (); w.AppendLine ($"\t\t\t}}"); @@ -1793,7 +1793,7 @@ public partial class TrampolineTestGenerated {"); w.AppendLine ($"\t\t\tusing (var obj = new OverrideRegistrarTest ()) {{"); w.AppendLine ($"\t\t\t\tvar structValue = {GenerateNewExpression (s, 7)};"); w.AppendLine ($"\t\t\t\tvoid_objc_msgSend_{s} (obj.Handle, Selector.GetHandle (\"setProperty{s}:\"), structValue);"); - w.AppendLine ($"\t\t\t\tAssert.AreEqual (structValue.ToString (), obj.V{s}.ToString (), \"SetProperty#1\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.V{s}.ToString (), Is.EqualTo (structValue.ToString ()), \"SetProperty#1\");"); w.AppendLine ($"\t\t\t}}"); w.AppendLine (); @@ -1813,9 +1813,9 @@ public partial class TrampolineTestGenerated {"); for (var x = 1; x <= i + 1; x++) { if (x == i) { - w.AppendLine ($"\t\t\t\tAssert.AreEqual (structValue.ToString (), obj.V{s}.ToString (), \"SetProperty#2-S{x}\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.V{s}.ToString (), Is.EqualTo (structValue.ToString ()), \"SetProperty#2-S{x}\");"); } else { - w.AppendLine ($"\t\t\t\tAssert.AreEqual ((nint) {x}, obj.ManagedVoidArg{x}, \"SetProperty#2-X{x}\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.ManagedVoidArg{x}, Is.EqualTo ((nint) {x}), \"SetProperty#2-X{x}\");"); } } w.AppendLine ($"\t\t\t}}"); @@ -1838,11 +1838,11 @@ public partial class TrampolineTestGenerated {"); for (var x = 1; x <= i + 1; x++) { if (x == 1) { - w.AppendLine ($"\t\t\t\tAssert.AreEqual ((float) {x}, obj.ManagedFloatArg{x}, \"SetProperty#3-X{x}\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.ManagedFloatArg{x}, Is.EqualTo ((float) {x}), \"SetProperty#3-X{x}\");"); } else if (x == i) { - w.AppendLine ($"\t\t\t\tAssert.AreEqual (structValue.ToString (), obj.V{s}.ToString (), \"SetProperty#3-S{x}\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.V{s}.ToString (), Is.EqualTo (structValue.ToString ()), \"SetProperty#3-S{x}\");"); } else { - w.AppendLine ($"\t\t\t\tAssert.AreEqual ((nint) {x}, obj.ManagedVoidArg{x}, \"SetProperty#3-X{x}\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.ManagedVoidArg{x}, Is.EqualTo ((nint) {x}), \"SetProperty#3-X{x}\");"); } } w.AppendLine ($"\t\t\t}}"); @@ -1865,11 +1865,11 @@ public partial class TrampolineTestGenerated {"); for (var x = 1; x <= i + 1; x++) { if (x == 1) { - w.AppendLine ($"\t\t\t\tAssert.AreEqual ((double) {x}, obj.ManagedDoubleArg{x}, \"SetProperty#3-X{x}\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.ManagedDoubleArg{x}, Is.EqualTo ((double) {x}), \"SetProperty#3-X{x}\");"); } else if (x == i) { - w.AppendLine ($"\t\t\t\tAssert.AreEqual (structValue.ToString (), obj.V{s}.ToString (), \"SetProperty#3-S{x}\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.V{s}.ToString (), Is.EqualTo (structValue.ToString ()), \"SetProperty#3-S{x}\");"); } else { - w.AppendLine ($"\t\t\t\tAssert.AreEqual ((nint) {x}, obj.ManagedVoidArg{x}, \"SetProperty#3-X{x}\");"); + w.AppendLine ($"\t\t\t\tAssert.That (obj.ManagedVoidArg{x}, Is.EqualTo ((nint) {x}), \"SetProperty#3-X{x}\");"); } } w.AppendLine ($"\t\t\t}}"); diff --git a/tests/test-libraries/testgenerator.csproj b/tests/test-libraries/testgenerator.csproj index 3a6e60b0eb38..4d13d04df6e0 100644 --- a/tests/test-libraries/testgenerator.csproj +++ b/tests/test-libraries/testgenerator.csproj @@ -4,8 +4,6 @@ Exe net$(BundledNETCoreAppTargetFrameworkVersion) enable - enable - latest false false diff --git a/tests/xcframework-test/XCFrameworkTests.cs b/tests/xcframework-test/XCFrameworkTests.cs index 206951ea19b0..2926ee397ed8 100644 --- a/tests/xcframework-test/XCFrameworkTests.cs +++ b/tests/xcframework-test/XCFrameworkTests.cs @@ -19,14 +19,14 @@ public class FrameworkTests { [Test] public void CFunction () { - Assert.AreEqual (42, CFunctions.theUltimateAnswer (), "a"); + Assert.That (CFunctions.theUltimateAnswer (), Is.EqualTo (42), "a"); } [Test] public void ObjCClass () { using (var obj = new FrameworkTest ()) { - Assert.AreEqual (42, obj.Func (), "a"); + Assert.That (obj.Func (), Is.EqualTo (42), "a"); } } } diff --git a/tests/xcframework-test/dotnet/shared.csproj b/tests/xcframework-test/dotnet/shared.csproj index 1faa644c5b90..d4d6b8c40c14 100644 --- a/tests/xcframework-test/dotnet/shared.csproj +++ b/tests/xcframework-test/dotnet/shared.csproj @@ -13,11 +13,6 @@ true $(DefineConstants);DEBUG - latest - - - true - Nullable diff --git a/tests/xcframework-test/dotnet/tvOS/xcframework-test.csproj b/tests/xcframework-test/dotnet/tvOS/xcframework-test.csproj index 312b279c5d7a..5261f8f1c844 100644 --- a/tests/xcframework-test/dotnet/tvOS/xcframework-test.csproj +++ b/tests/xcframework-test/dotnet/tvOS/xcframework-test.csproj @@ -2,7 +2,6 @@ net$(BundledNETCoreAppTargetFrameworkVersion)-tvos - latest diff --git a/tests/xharness/Jenkins/Reports/HtmlReportWriter.cs b/tests/xharness/Jenkins/Reports/HtmlReportWriter.cs index 670799a45514..38f48645f457 100644 --- a/tests/xharness/Jenkins/Reports/HtmlReportWriter.cs +++ b/tests/xharness/Jenkins/Reports/HtmlReportWriter.cs @@ -124,7 +124,7 @@ public void Write (IList allTasks, StreamWriter writer) writer.WriteLine ("{1}
    ", GetLinkFullPath (log.FullPath.Substring (jenkins.LogDirectory.Length + 1)), log.Description); writer.WriteLine (""); - var headerColor = "black"; + var headerColor = "currentcolor"; if (unfinishedTests.Any ()) { ; // default } else if (failedTests.Any ()) { diff --git a/tests/xharness/Jenkins/TestTasks/AppleTestTask.cs b/tests/xharness/Jenkins/TestTasks/AppleTestTask.cs index 896e9a506d18..851fb2a9d42e 100644 --- a/tests/xharness/Jenkins/TestTasks/AppleTestTask.cs +++ b/tests/xharness/Jenkins/TestTasks/AppleTestTask.cs @@ -35,7 +35,7 @@ public override void SetEnvironmentVariables (Process process) var xcodeRoot = Jenkins.Harness.XcodeRoot; process.StartInfo.EnvironmentVariables ["RootTestsDirectory"] = HarnessConfiguration.RootDirectory; - process.StartInfo.EnvironmentVariables ["MD_APPLE_SDK_ROOT"] = xcodeRoot; + process.StartInfo.EnvironmentVariables ["DEVELOPER_DIR"] = xcodeRoot; foreach (var kvp in Environment) { if (kvp.Value is null) { diff --git a/tests/xharness/Jenkins/TestTasks/ITestTaskExtensions.cs b/tests/xharness/Jenkins/TestTasks/ITestTaskExtensions.cs index 1992fdc66afa..5c68672fe0c3 100644 --- a/tests/xharness/Jenkins/TestTasks/ITestTaskExtensions.cs +++ b/tests/xharness/Jenkins/TestTasks/ITestTaskExtensions.cs @@ -7,7 +7,7 @@ public static class ITestTaskExtensions { public static string GetTestColor (this IEnumerable tests) { if (!tests.Any ()) - return "black"; + return "currentcolor"; var first = tests.First (); if (tests.All ((v) => v.ExecutionResult == first.ExecutionResult)) @@ -23,7 +23,7 @@ public static string GetTestColor (this IEnumerable tests) else if (tests.Any ((v) => v.Failed)) return "red"; else if (tests.Any ((v) => v.NotStarted)) - return "black"; + return "currentcolor"; else if (tests.Any ((v) => v.Ignored)) return "gray"; else if (tests.Any ((v) => v.DeviceNotFound)) @@ -33,13 +33,13 @@ public static string GetTestColor (this IEnumerable tests) else if (tests.All ((v) => v.Succeeded)) return "green"; else - return "black"; + return "currentcolor"; } public static string GetTestColor (this TestTask test) { if (test.NotStarted) { - return "black"; + return "currentcolor"; } else if (test.InProgress) { if (test.Building) { return "darkblue"; diff --git a/tests/xharness/Jenkins/TestVariationsFactory.cs b/tests/xharness/Jenkins/TestVariationsFactory.cs index f7d7a2460eab..00c05d4882c6 100644 --- a/tests/xharness/Jenkins/TestVariationsFactory.cs +++ b/tests/xharness/Jenkins/TestVariationsFactory.cs @@ -59,6 +59,10 @@ IEnumerable GetTestData (RunTestTask test) yield return new TestData { Variation = "Debug (don't bundle original resources)", TestVariation = "do-not-bundle-original-resources" }; } break; + case "monotouch-test": + yield return new TestData { Variation = "Release (link sdk)", TestVariation = "release|linksdk", Ignored = ignore }; + yield return new TestData { Variation = "Release (link all)", TestVariation = "release|linkall", Ignored = ignore }; + break; } switch (test.ProjectPlatform) { @@ -113,6 +117,12 @@ IEnumerable GetTestData (RunTestTask test) yield return new TestData { Variation = "Debug (interpreter)", TestVariation = "interpreter", Ignored = ignore }; yield return new TestData { Variation = "Release (interpreter)", TestVariation = "release|interpreter", Ignored = ignore }; } + yield return new TestData { Variation = $"Release (compat inline Class.GetHandle)", TestVariation = "inline-class-gethandle-compat|release", Ignored = ignore }; + yield return new TestData { Variation = $"Release (strict inline Class.GetHandle)", TestVariation = "inline-class-gethandle-strict|release", Ignored = ignore }; + yield return new TestData { Variation = $"Release (compat inline dlfcn)", TestVariation = "inline-dlfcn-methods-compat|release", Ignored = ignore }; + yield return new TestData { Variation = $"Release (strict inline dlfcn, link sdk)", TestVariation = "inline-dlfcn-methods-strict|linksdk|release", Ignored = ignore }; + if (mac_supports_arm64) + yield return new TestData { Variation = $"Release (NativeAOT, .NET 11 defaults)", TestVariation = "nativeaot-net11-defaults|release", Ignored = ignore, RuntimeIdentifier = arm64_sim_runtime_identifier }; // it's necessary to specify RID, because NativeAOT defaults to building for device break; case "introspection": if (mac_supports_arm64) @@ -148,6 +158,8 @@ IEnumerable GetTestData (RunTestTask test) yield return new TestData { Variation = "Release (NativeAOT)", TestVariation = "release|nativeaot", Ignored = ignore }; yield return new TestData { Variation = "Release (NativeAOT, ARM64)", TestVariation = "release|nativeaot", Ignored = !mac_supports_arm64 ? true : ignore, RuntimeIdentifier = arm64_runtime_identifier }; yield return new TestData { Variation = "Release (NativeAOT, x64)", TestVariation = "release|nativeaot", Ignored = ignore, RuntimeIdentifier = x64_runtime_identifier }; + if (mac_supports_arm64) + yield return new TestData { Variation = $"Release (NativeAOT, .NET 11 defaults)", TestVariation = "release|nativeaot-net11-defaults", Ignored = ignore }; yield return new TestData { Variation = "Release (trimmable static registrar, NativeAOT)", TestVariation = "trimmable-static-registrar|nativeaot|release", Ignored = ignore }; yield return new TestData { Variation = "Release (trimmable static registrar, NativeAOT, ARM64)", TestVariation = "trimmable-static-registrar|nativeaot|release", Ignored = !mac_supports_arm64 ? true : ignore, RuntimeIdentifier = arm64_runtime_identifier }; yield return new TestData { Variation = "Release (trimmable static registrar, NativeAOT, x64)", TestVariation = "trimmable-static-registrar|nativeaot|release", Ignored = ignore, RuntimeIdentifier = x64_runtime_identifier }; @@ -160,6 +172,8 @@ IEnumerable GetTestData (RunTestTask test) yield return new TestData { Variation = "Debug (interpreter)", TestVariation = "interpreter", Ignored = ignore }; yield return new TestData { Variation = "Release (interpreter)", TestVariation = "release|interpreter", Ignored = ignore }; } + yield return new TestData { Variation = $"Release (compat inline dlfcn)", TestVariation = "inline-dlfcn-methods-compat|release", Ignored = ignore }; + yield return new TestData { Variation = $"Release (strict inline dlfcn, link sdk)", TestVariation = "inline-dlfcn-methods-strict|linksdk|release", Ignored = ignore }; break; } break; diff --git a/tests/xharness/xharness.csproj b/tests/xharness/xharness.csproj index 03169bf8a1da..015edc2d1452 100644 --- a/tests/xharness/xharness.csproj +++ b/tests/xharness/xharness.csproj @@ -5,9 +5,6 @@ Exe Xharness xharness - latest - Nullable - enable false
    diff --git a/tests/xharness/xharness.css b/tests/xharness/xharness.css index f00919012edf..6753e130b1e5 100644 --- a/tests/xharness/xharness.css +++ b/tests/xharness/xharness.css @@ -1,3 +1,27 @@ +:root { + color-scheme: light dark; +} + +@media (prefers-color-scheme: dark) { + body { + background-color: #1e1e1e; + color: #d4d4d4; + } + + a { + color: #6db3f2; + } + + a:visited { + color: #b48ead; + } + + #nav ul { + background: #2d2d2d; + border-color: #555; + } +} + .pdiv { display: table; padding-top: 10px; @@ -43,7 +67,7 @@ } #nav ul { - background: #ffffff; + background: Canvas; list-style: none; position: absolute; left: -9999px; diff --git a/tests/xtro-sharpie/UnitTests/UnitTests.csproj b/tests/xtro-sharpie/UnitTests/UnitTests.csproj index d4d02af8f78d..5bd7b152f1f2 100644 --- a/tests/xtro-sharpie/UnitTests/UnitTests.csproj +++ b/tests/xtro-sharpie/UnitTests/UnitTests.csproj @@ -3,17 +3,14 @@ net$(BundledNETCoreAppTargetFrameworkVersion) false $(DefineConstants);NET;TESTS - enable - Nullable - - - + + + - diff --git a/tests/xtro-sharpie/UnitTests/Xtro.cs b/tests/xtro-sharpie/UnitTests/Xtro.cs index 9b4dd819c721..6037f79e44c1 100644 --- a/tests/xtro-sharpie/UnitTests/Xtro.cs +++ b/tests/xtro-sharpie/UnitTests/Xtro.cs @@ -29,7 +29,7 @@ public void RunTest () TestContext.AddTestAttachment (zippedReport, "HTML report (zipped)"); } - Assert.AreEqual (0, rv, "ExitCode"); + Assert.That (rv, Is.EqualTo (0), "ExitCode"); } } } diff --git a/tests/xtro-sharpie/api-annotations-dotnet/macOS-AppKit.ignore b/tests/xtro-sharpie/api-annotations-dotnet/macOS-AppKit.ignore index 268a5aeb27fa..a9a43afadb4c 100644 --- a/tests/xtro-sharpie/api-annotations-dotnet/macOS-AppKit.ignore +++ b/tests/xtro-sharpie/api-annotations-dotnet/macOS-AppKit.ignore @@ -1,9 +1,6 @@ ## https://bugzilla.xamarin.com/show_bug.cgi?id=30717 !duplicate-register! _NSDatePickerCellDelegate exists as both AppKit.NSDatePickerCell/_NSDatePickerCellDelegate and AppKit.NSDatePicker/_NSDatePickerCellDelegate -## Proxy class for NSGraphicsContext internal to AppKit -!unknown-type! NSPrintPreviewGraphicsContext bound - ## In header as old style unnamaed enum !unknown-native-enum! NSModalResponse bound !unknown-native-enum! NSWindowLevel bound diff --git a/tests/xtro-sharpie/u2ignore/u2ignore.csproj b/tests/xtro-sharpie/u2ignore/u2ignore.csproj index aa6791b586ee..5ffd48332e51 100644 --- a/tests/xtro-sharpie/u2ignore/u2ignore.csproj +++ b/tests/xtro-sharpie/u2ignore/u2ignore.csproj @@ -3,7 +3,6 @@ Exe net$(BundledNETCoreAppTargetFrameworkVersion) enable - enable false diff --git a/tests/xtro-sharpie/u2todo/u2todo.csproj b/tests/xtro-sharpie/u2todo/u2todo.csproj index 8e905ed0a453..6c73ffc392da 100644 --- a/tests/xtro-sharpie/u2todo/u2todo.csproj +++ b/tests/xtro-sharpie/u2todo/u2todo.csproj @@ -3,7 +3,6 @@ Exe net$(BundledNETCoreAppTargetFrameworkVersion) enable - enable false diff --git a/tests/xtro-sharpie/xtro-report/xtro-report.csproj b/tests/xtro-sharpie/xtro-report/xtro-report.csproj index 9bcdb596b75e..6c73ffc392da 100644 --- a/tests/xtro-sharpie/xtro-report/xtro-report.csproj +++ b/tests/xtro-sharpie/xtro-report/xtro-report.csproj @@ -3,11 +3,7 @@ Exe net$(BundledNETCoreAppTargetFrameworkVersion) enable - enable false - - Nullable - true diff --git a/tests/xtro-sharpie/xtro-sanity/xtro-sanity.csproj b/tests/xtro-sharpie/xtro-sanity/xtro-sanity.csproj index 2a9d8b0f507e..be79a85c1414 100644 --- a/tests/xtro-sharpie/xtro-sanity/xtro-sanity.csproj +++ b/tests/xtro-sharpie/xtro-sanity/xtro-sanity.csproj @@ -3,11 +3,7 @@ Exe net$(BundledNETCoreAppTargetFrameworkVersion) enable - enable false - - Nullable - true diff --git a/tests/xtro-sharpie/xtro-sharpie/xtro-sharpie.csproj b/tests/xtro-sharpie/xtro-sharpie/xtro-sharpie.csproj index 46a03e54fe0f..92ce38573813 100644 --- a/tests/xtro-sharpie/xtro-sharpie/xtro-sharpie.csproj +++ b/tests/xtro-sharpie/xtro-sharpie/xtro-sharpie.csproj @@ -4,16 +4,11 @@ net$(BundledNETCoreAppTargetFrameworkVersion) Exe false - latest osx-arm64 false - - enable - Nullable - true diff --git a/tools/Makefile b/tools/Makefile index ee73e7c5ba3e..00d896286809 100644 --- a/tools/Makefile +++ b/tools/Makefile @@ -2,7 +2,7 @@ TOP=.. include $(TOP)/Make.config -ifndef IS_LINUX +ifndef NO_XCODE SUBDIRS += sharpie endif diff --git a/tools/api-tools/mono-api-html/ApiChange.cs b/tools/api-tools/mono-api-html/ApiChange.cs index a7c0218142fd..18cc90285b5c 100644 --- a/tools/api-tools/mono-api-html/ApiChange.cs +++ b/tools/api-tools/mono-api-html/ApiChange.cs @@ -7,9 +7,10 @@ namespace Mono.ApiTools { class ApiChange { - public string Header; + public string Header = ""; public TextChunk Member = new TextChunk (); public bool AnyChange; + public bool IsNullabilityChange; public string SourceDescription; public State State; @@ -45,6 +46,76 @@ public ApiChange AppendModified (string old, string @new) AnyChange = true; return this; } + + // Renders a type change: uses inline nullability rendering if the only + // difference is '?' annotations, otherwise falls back to full modification. + public ApiChange AppendTypeModified (string old, string @new) + { + if (Helper.DiffersOnlyByNullability (old, @new)) + return AppendNullabilityModified (old, @new); + return AppendModified (old, @new); + } + + // Renders a type modification where only nullability annotations ('?') differ. + // Only the added/removed '?' characters are highlighted; the rest is plain text. + public ApiChange AppendNullabilityModified (string old, string @new) + { + int si = 0; + int ti = 0; + while (si < old.Length && ti < @new.Length) { + if (old [si] == @new [ti]) { + Member.Append (old [si]); + si++; + ti++; + } else if (old [si] == '?' && IsNullabilitySuffix (old, si)) { + State.Formatter.DiffRemoval (Member, "?"); + AnyChange = true; + si++; + } else if (@new [ti] == '?' && IsNullabilitySuffix (@new, ti)) { + State.Formatter.DiffAddition (Member, "?"); + AnyChange = true; + ti++; + } else { + // Shouldn't happen for nullability-only diffs, fall back to full modification + State.Formatter.DiffModification (Member, old.Substring (si), @new.Substring (ti)); + AnyChange = true; + return this; + } + } + // Handle remaining characters + while (si < old.Length) { + if (old [si] == '?' && IsNullabilitySuffix (old, si)) { + State.Formatter.DiffRemoval (Member, "?"); + AnyChange = true; + si++; + } else { + Member.Append (old [si]); + si++; + } + } + while (ti < @new.Length) { + if (@new [ti] == '?' && IsNullabilitySuffix (@new, ti)) { + State.Formatter.DiffAddition (Member, "?"); + AnyChange = true; + ti++; + } else { + Member.Append (@new [ti]); + ti++; + } + } + return this; + } + + static bool IsNullabilitySuffix (string text, int index) + { + // A '?' is a nullability suffix if it's at the end, or before a type separator. + // The input type names are already formatted (via GetTypeName + Formatter), so generic + // brackets appear as HTML entities (< / >). A '?' before '&' catches the > case. + if (index + 1 >= text.Length) + return true; + char next = text [index + 1]; + return next == ']' || next == ',' || next == '>' || next == '&' || next == ' '; + } } class ApiChanges : Dictionary> { @@ -61,13 +132,66 @@ public void Add (XElement source, XElement target, ApiChange change) if (!change.AnyChange) return; - List list; - if (!TryGetValue (change.Header, out list)) { + // Detect if this change is nullability-only + if (DiffersOnlyByNullability (source, target)) + change.IsNullabilityChange = true; + + if (!TryGetValue (change.Header, out List? list)) { list = new List (); base.Add (change.Header, list); } list.Add (change); } + + static bool DiffersOnlyByNullability (XElement source, XElement target) + { + // Compare all attributes, stripping nullability from type-related attributes + var typeAttributes = new HashSet { "returntype", "fieldtype", "ptype", "eventtype", "type" }; + + if (source.Name != target.Name) + return false; + + // Check that all non-type-related attributes are the same + var srcAttrs = source.Attributes ().ToDictionary (a => a.Name.LocalName, a => a.Value); + var tgtAttrs = target.Attributes ().ToDictionary (a => a.Name.LocalName, a => a.Value); + + if (srcAttrs.Count != tgtAttrs.Count) + return false; + + bool hasNullabilityDiff = false; + foreach (var kvp in srcAttrs) { + if (!tgtAttrs.TryGetValue (kvp.Key, out var tgtValue)) + return false; + + if (kvp.Value == tgtValue) + continue; + + if (typeAttributes.Contains (kvp.Key)) { + if (Helper.DiffersOnlyByNullability (kvp.Value, tgtValue)) + hasNullabilityDiff = true; + else + return false; + } else { + return false; + } + } + + // Always check child elements — a non-nullability child diff means this + // is not a nullability-only change, even if the parent attributes differ only by nullability. + var srcChildren = source.Elements ().ToList (); + var tgtChildren = target.Elements ().ToList (); + if (srcChildren.Count != tgtChildren.Count) + return false; + + for (int i = 0; i < srcChildren.Count; i++) { + if (XNode.DeepEquals (srcChildren [i], tgtChildren [i])) + continue; + if (!DiffersOnlyByNullability (srcChildren [i], tgtChildren [i])) + return false; + hasNullabilityDiff = true; + } + + return hasNullabilityDiff; + } } } - diff --git a/tools/api-tools/mono-api-html/ApiDiff.cs b/tools/api-tools/mono-api-html/ApiDiff.cs index 7e28b8e96d3b..421091445367 100644 --- a/tools/api-tools/mono-api-html/ApiDiff.cs +++ b/tools/api-tools/mono-api-html/ApiDiff.cs @@ -42,17 +42,17 @@ namespace Mono.ApiTools { class State { - public Formatter Formatter { get; set; } - public Formatter [] Formatters { get; set; } - public string Assembly { get; set; } - public string Namespace { get; set; } - public string Type { get; set; } - public string BaseType { get; set; } - public string Parent { get; set; } + public Formatter Formatter { get; set; } = null!; + public Formatter [] Formatters { get; set; } = []; + public string Assembly { get; set; } = ""; + public string Namespace { get; set; } = ""; + public string Type { get; set; } = ""; + public string BaseType { get; set; } = ""; + public string Parent { get; set; } = ""; public bool Colorize { get; set; } = true; public int Verbosity { get; set; } - public string SourceFile; - public string TargetFile; + public string SourceFile = ""; + public string TargetFile = ""; public void LogDebugMessage (string value) { @@ -70,7 +70,7 @@ class Program { public static int Main (string [] args) { var showHelp = false; - List extra = null; + List? extra = null; var config = new ApiDiffFormattedConfig (); var options = new Mono.Options.OptionSet { @@ -130,9 +130,9 @@ public static int Main (string [] args) #endif public class ApiDiffFormattedConfig { - public string HtmlOutput { get; set; } - public string HtmlHeader { get; set; } - public string MarkdownOutput { get; set; } + public string? HtmlOutput { get; set; } + public string? HtmlHeader { get; set; } + public string? MarkdownOutput { get; set; } // public bool IgnoreDuplicateXml { get; set; } public bool Colorize { get; set; } = true; @@ -140,7 +140,7 @@ public class ApiDiffFormattedConfig { } public static class ApiDiffFormatted { - public static void Generate (string firstInfo, string secondInfo, ApiDiffFormattedConfig config = null) + public static void Generate (string firstInfo, string secondInfo, ApiDiffFormattedConfig? config = null) { var state = CreateState (config, firstInfo, secondInfo); var ac = new AssemblyComparer (state); @@ -171,14 +171,14 @@ static void Generate (AssemblyComparer ac, State state) } } - static State CreateState (ApiDiffFormattedConfig config, string firstInfo, string secondInfo) + static State CreateState (ApiDiffFormattedConfig? config, string firstInfo, string secondInfo) { if (config is null) config = new ApiDiffFormattedConfig (); var state = new State { Colorize = config.Colorize, - Formatter = null, + Formatter = null!, SourceFile = firstInfo, TargetFile = secondInfo, @@ -187,9 +187,9 @@ static State CreateState (ApiDiffFormattedConfig config, string firstInfo, strin var formatters = new List (); if (!string.IsNullOrWhiteSpace (config.HtmlOutput)) - formatters.Add (new HtmlFormatter (state) { OutputPath = config.HtmlOutput, Header = config.HtmlHeader }); + formatters.Add (new HtmlFormatter (state) { OutputPath = config.HtmlOutput!, Header = config.HtmlHeader ?? "" }); if (!string.IsNullOrWhiteSpace (config.MarkdownOutput)) - formatters.Add (new MarkdownFormatter (state) { OutputPath = config.MarkdownOutput }); + formatters.Add (new MarkdownFormatter (state) { OutputPath = config.MarkdownOutput! }); if (formatters.Count > 1) { state.Formatter = new MultiplexedFormatter (state, formatters.ToArray ()); } else if (formatters.Count == 0) { diff --git a/tools/api-tools/mono-api-html/AssemblyComparer.cs b/tools/api-tools/mono-api-html/AssemblyComparer.cs index f1d053142483..6eff7d44e0eb 100644 --- a/tools/api-tools/mono-api-html/AssemblyComparer.cs +++ b/tools/api-tools/mono-api-html/AssemblyComparer.cs @@ -58,18 +58,18 @@ public override string ElementName { get { return "assembly"; } } - public string SourceAssembly { get; private set; } - public string TargetAssembly { get; private set; } + public string SourceAssembly { get; private set; } = ""; + public string TargetAssembly { get; private set; } = ""; public void Compare () { - Compare (source.Element ("assemblies").Elements ("assembly"), - target.Element ("assemblies").Elements ("assembly")); + Compare (source.Element ("assemblies")!.Elements ("assembly"), + target.Element ("assemblies")!.Elements ("assembly")); } public override void SetContext (XElement current) { - State.Assembly = current.GetAttribute ("name"); + State.Assembly = current.GetAttribute ("name") ?? ""; } public override void Added (XElement target, bool wasParentAdded) @@ -79,13 +79,13 @@ public override void Added (XElement target, bool wasParentAdded) public override void Modified (XElement source, XElement target, ApiChanges diff) { - SourceAssembly = source.GetAttribute ("name"); - TargetAssembly = target.GetAttribute ("name"); + SourceAssembly = source.GetAttribute ("name") ?? ""; + TargetAssembly = target.GetAttribute ("name") ?? ""; var sb = source.GetAttribute ("version"); var tb = target.GetAttribute ("version"); if (sb != tb) { - Output.WriteLine ("

    Assembly Version Changed: {0} -> {1}

    ", sb, tb); + Output.WriteLine ("

    Assembly Version Changed: {0} -> {1}

    ", sb ?? "", tb ?? ""); Output.WriteLine (); } diff --git a/tools/api-tools/mono-api-html/ClassComparer.cs b/tools/api-tools/mono-api-html/ClassComparer.cs index b258ea02aa1d..8afdd03be192 100644 --- a/tools/api-tools/mono-api-html/ClassComparer.cs +++ b/tools/api-tools/mono-api-html/ClassComparer.cs @@ -43,7 +43,7 @@ class ClassComparer : Comparer { PropertyComparer pcomparer; EventComparer ecomparer; MethodComparer mcomparer; - ClassComparer kcomparer; + ClassComparer? kcomparer; public ClassComparer (State state) : base (state) @@ -66,8 +66,8 @@ public override string ElementName { public override void SetContext (XElement current) { - State.Type = current.GetAttribute ("name"); - State.BaseType = current.GetAttribute ("base"); + State.Type = current.GetAttribute ("name") ?? ""; + State.BaseType = current.GetAttribute ("base") ?? ""; } public void Compare (XElement source, XElement target) @@ -76,7 +76,7 @@ public void Compare (XElement source, XElement target) var t = target.Element ("classes"); if (XNode.DeepEquals (s, t)) return; - Compare (s.Elements ("class"), t.Elements ("class")); + Compare (s!.Elements ("class"), t!.Elements ("class")); } public override void Added (XElement target, bool wasParentAdded) @@ -92,7 +92,7 @@ public void AddedInner (XElement target) if (target.IsTrue ("serializable")) Indent ().WriteLine ("[Serializable]"); - var type = target.Attribute ("type").Value; + var type = target.Attribute ("type")!.Value; WriteAttributes (target); @@ -112,7 +112,7 @@ public void AddedInner (XElement target) Output.Write (' '); Output.Write (type); Output.Write (' '); - Output.Write (target.GetAttribute ("name")); + Output.Write (target.GetAttribute ("name") ?? ""); var baseclass = target.GetAttribute ("base"); if ((type != "enum") && (type != "struct")) { @@ -206,7 +206,7 @@ static Dictionary CreateClassHierarchyMap (string xml) foreach (var @assembly in assemblies.Elements ("assembly")) { foreach (var e in assembly.Elements ("namespaces")) { foreach (var nsElement in e.Elements ("namespace")) { - var ns = nsElement.GetAttribute ("name"); + var ns = nsElement.GetAttribute ("name") ?? ""; foreach (var classesElement in nsElement.Elements ("classes")) { MapClasses (rv, ns, string.Empty, classesElement); } @@ -219,8 +219,8 @@ static Dictionary CreateClassHierarchyMap (string xml) static void MapClasses (Dictionary dictionary, string @namespace, string declaringType, XElement classes) { foreach (var classElement in classes.Elements ("class")) { - var className = classElement.GetAttribute ("name"); - var baseType = classElement.GetAttribute ("base"); + var className = classElement.GetAttribute ("name") ?? ""; + var baseType = classElement.GetAttribute ("base") ?? ""; string fullname; if (string.IsNullOrEmpty (@namespace)) { // nested type @@ -255,7 +255,7 @@ public override void Modified (XElement source, XElement target, ApiChanges diff State.LogDebugMessage ($"Possible -r value: {rm}"); if (sb != tb) { Formatter.BeginMemberModification ("Modified base type"); - var apichange = new ApiChange ($"{State.Namespace}.{State.Type}", State).AppendModified (sb, tb); + var apichange = new ApiChange ($"{State.Namespace}.{State.Type}", State).AppendModified (sb ?? "", tb ?? ""); Formatter.Diff (apichange); Formatter.EndMemberModification (); } @@ -272,7 +272,7 @@ public override void Modified (XElement source, XElement target, ApiChanges diff var ti = target.Element ("classes"); kcomparer = new NestedClassComparer (State); State.Parent = State.Type; - kcomparer.Compare (si.Elements ("class"), ti is null ? null : ti.Elements ("class")); + kcomparer.Compare (si.Elements ("class"), ti?.Elements ("class")); State.Type = State.Parent; } @@ -293,7 +293,7 @@ public override void Removed (XElement source) Formatter.EndTypeRemoval (); } - public virtual string GetTypeName (XElement type) + public virtual string? GetTypeName (XElement type) { return type.GetAttribute ("name"); } @@ -308,11 +308,11 @@ public NestedClassComparer (State state) public override void SetContext (XElement current) { - State.Type = State.Parent + "." + current.GetAttribute ("name"); - State.BaseType = current.GetAttribute ("base"); + State.Type = State.Parent + "." + (current.GetAttribute ("name") ?? ""); + State.BaseType = current.GetAttribute ("base") ?? ""; } - public override string GetTypeName (XElement type) + public override string? GetTypeName (XElement type) { return State.Parent + "." + base.GetTypeName (type); } diff --git a/tools/api-tools/mono-api-html/Comparer.cs b/tools/api-tools/mono-api-html/Comparer.cs index add7414cf948..11517e7da80d 100644 --- a/tools/api-tools/mono-api-html/Comparer.cs +++ b/tools/api-tools/mono-api-html/Comparer.cs @@ -156,14 +156,14 @@ public virtual bool Equals (XElement source, XElement target, ApiChanges changes public abstract void SetContext (XElement current); - public virtual void Compare (IEnumerable source, IEnumerable target) + public virtual void Compare (IEnumerable source, IEnumerable? target) { removed.Clear (); modified.Clear (); foreach (var s in source) { SetContext (s); - string sn = s.GetAttribute ("name"); + string? sn = s.GetAttribute ("name"); var t = target is null ? null : target.SingleOrDefault (x => x.GetAttribute ("name") == sn); if (t is null) { // not in target, it was removed diff --git a/tools/api-tools/mono-api-html/ConstructorComparer.cs b/tools/api-tools/mono-api-html/ConstructorComparer.cs index b6adfa6401c3..5ae44bf7ee6d 100644 --- a/tools/api-tools/mono-api-html/ConstructorComparer.cs +++ b/tools/api-tools/mono-api-html/ConstructorComparer.cs @@ -50,7 +50,7 @@ public override string ElementName { public override bool Find (XElement e) { - return (e.Attribute ("name").Value == Source.Attribute ("name").Value); + return (e.Attribute ("name")!.Value == Source.Attribute ("name")!.Value); } void RenderReturnType (XElement source, XElement target, ApiChange change) @@ -59,7 +59,7 @@ void RenderReturnType (XElement source, XElement target, ApiChange change) var tgtType = target.GetTypeName ("returntype", State); if (srcType != tgtType) { - change.AppendModified (srcType, tgtType); + change.AppendTypeModified (srcType ?? "", tgtType ?? ""); change.Append (" "); } else if (srcType is not null) { // ctor don't have a return type @@ -114,7 +114,7 @@ public override string GetDescription (XElement e) } } - string name = e.GetAttribute ("name"); + string name = e.GetAttribute ("name") ?? ""; var r = e.GetTypeName ("returntype", State); if (r is not null) { @@ -133,7 +133,7 @@ public override string GetDescription (XElement e) if (genericp is not null) { var list = new List (); foreach (var p in genericp.Elements ("generic-parameter")) { - list.Add (p.GetTypeName ("name", State)); + list.Add (p.GetTypeName ("name", State) ?? ""); } sb.Append (Formatter.LesserThan).Append (String.Join (", ", list)).Append (Formatter.GreaterThan); } diff --git a/tools/api-tools/mono-api-html/EventComparer.cs b/tools/api-tools/mono-api-html/EventComparer.cs index 8433e6c52d87..123cfe850897 100644 --- a/tools/api-tools/mono-api-html/EventComparer.cs +++ b/tools/api-tools/mono-api-html/EventComparer.cs @@ -55,16 +55,16 @@ public override bool Equals (XElement source, XElement target, ApiChanges change RenderAttributes (source, target, change); change.Append ("public event "); - var srcEventType = source.GetTypeName ("eventtype", State); - var tgtEventType = target.GetTypeName ("eventtype", State); + var srcEventType = source.GetTypeName ("eventtype", State) ?? ""; + var tgtEventType = target.GetTypeName ("eventtype", State) ?? ""; if (srcEventType != tgtEventType) { - change.AppendModified (srcEventType, tgtEventType); + change.AppendTypeModified (srcEventType, tgtEventType); } else { change.Append (srcEventType); } change.Append (" "); - change.Append (source.GetAttribute ("name")).Append (";"); + change.Append (source.GetAttribute ("name") ?? "").Append (";"); return false; } @@ -73,8 +73,8 @@ public override string GetDescription (XElement e) var sb = new StringBuilder (); // TODO: attribs sb.Append ("public event "); - sb.Append (e.GetTypeName ("eventtype", State)).Append (' '); - sb.Append (e.GetAttribute ("name")).Append (';'); + sb.Append (e.GetTypeName ("eventtype", State) ?? "").Append (' '); + sb.Append (e.GetAttribute ("name") ?? "").Append (';'); return sb.ToString (); } } diff --git a/tools/api-tools/mono-api-html/FieldComparer.cs b/tools/api-tools/mono-api-html/FieldComparer.cs index fb1587c74fa5..d0b6169cbf73 100644 --- a/tools/api-tools/mono-api-html/FieldComparer.cs +++ b/tools/api-tools/mono-api-html/FieldComparer.cs @@ -106,15 +106,15 @@ void RenderFieldAttributes (FieldAttributes source, FieldAttributes target, ApiC string GetFullName (XElement element) { - var rv = element.GetAttribute ("name"); - element = element.Parent; + var rv = element.GetAttribute ("name") ?? ""; + element = element.Parent!; while (element is not null) { if (element.Name.LocalName == "assembly") break; var name = element.GetAttribute ("name"); if (!string.IsNullOrEmpty (name)) rv = name + "." + rv; - element = element.Parent; + element = element.Parent!; } return rv; } @@ -124,7 +124,7 @@ public override bool Equals (XElement source, XElement target, ApiChanges change if (base.Equals (source, target, changes)) return true; - var name = source.GetAttribute ("name"); + var name = source.GetAttribute ("name") ?? ""; var srcValue = source.GetAttribute ("value"); var tgtValue = target.GetAttribute ("value"); var change = new ApiChange (GetDescription (source), State); @@ -135,18 +135,18 @@ public override bool Equals (XElement source, XElement target, ApiChanges change if (State.BaseType == "System.Enum") { change.Append (name).Append (" = "); if (srcValue != tgtValue) { - change.AppendModified (srcValue, tgtValue); + change.AppendModified (srcValue ?? "", tgtValue ?? ""); } else { - change.Append (srcValue); + change.Append (srcValue ?? ""); } } else { RenderFieldAttributes (source.GetFieldAttributes (), target.GetFieldAttributes (), change); - var srcType = source.GetTypeName ("fieldtype", State); - var tgtType = target.GetTypeName ("fieldtype", State); + var srcType = source.GetTypeName ("fieldtype", State) ?? ""; + var tgtType = target.GetTypeName ("fieldtype", State) ?? ""; if (srcType != tgtType) { - change.AppendModified (srcType, tgtType); + change.AppendTypeModified (srcType, tgtType); } else { change.Append (srcType); } @@ -183,8 +183,8 @@ public override string GetDescription (XElement e) { var sb = new StringBuilder (); - string name = e.GetAttribute ("name"); - string value = e.GetAttribute ("value"); + string name = e.GetAttribute ("name") ?? ""; + string? value = e.GetAttribute ("value"); if (State.BaseType == "System.Enum") { sb.Append (name).Append (" = ").Append (value).Append (','); @@ -205,8 +205,8 @@ public override string GetDescription (XElement e) sb.Append ("const "); } - string ftype = e.GetTypeName ("fieldtype", State); - sb.Append (ftype).Append (' '); + string? ftype = e.GetTypeName ("fieldtype", State); + sb.Append (ftype ?? "").Append (' '); sb.Append (name); if (ftype == "string" && e.Attribute ("value") is not null) { if (value is null) diff --git a/tools/api-tools/mono-api-html/Formatter.cs b/tools/api-tools/mono-api-html/Formatter.cs index 4ca489bfb750..0fce910fc46c 100644 --- a/tools/api-tools/mono-api-html/Formatter.cs +++ b/tools/api-tools/mono-api-html/Formatter.cs @@ -33,11 +33,11 @@ namespace Mono.ApiTools { abstract class Formatter { - public string OutputPath { get; set; } + public string OutputPath { get; set; } = ""; - Stack<(StringBuilder, TextWriter)> builders; - public StringBuilder StringBuilder { get; private set; } - protected TextWriter output; + Stack<(StringBuilder, TextWriter)> builders = null!; + public StringBuilder StringBuilder { get; private set; } = null!; + protected TextWriter output = null!; protected int IndentLevel { get; set; } @@ -211,6 +211,13 @@ public void Append (string value) cachedOutput.Append (value); } + public void Append (char value) + { + foreach (var kvp in stringbuilders) + kvp.StringBuilder.Append (value); + cachedOutput.Append (value); + } + public override string ToString () { throw new InvalidOperationException (); diff --git a/tools/api-tools/mono-api-html/Helpers.cs b/tools/api-tools/mono-api-html/Helpers.cs index a7d0a3fdb61f..9a98857a0826 100644 --- a/tools/api-tools/mono-api-html/Helpers.cs +++ b/tools/api-tools/mono-api-html/Helpers.cs @@ -39,7 +39,7 @@ public static bool IsTrue (this XElement self, string name) return (self.GetAttribute (name) == "true"); } - public static string GetAttribute (this XElement self, string name) + public static string? GetAttribute (this XElement self, string name) { var n = self.Attribute (name); if (n is null) @@ -47,7 +47,7 @@ public static string GetAttribute (this XElement self, string name) return n.Value; } - public static IEnumerable EnumerateAttributes (this XElement self, string attributeName = null) + public static IEnumerable EnumerateAttributes (this XElement self, string? attributeName = null) { if (self is null) yield break; @@ -63,7 +63,7 @@ public static IEnumerable EnumerateAttributes (this XElement self, str } } - static bool TryGetAttributeProperty (this XElement self, string attributeName, bool recursive, out string firstArgument) + static bool TryGetAttributeProperty (this XElement? self, string attributeName, bool recursive, out string? firstArgument) { firstArgument = null; @@ -89,16 +89,16 @@ static bool TryGetAttributeProperty (this XElement self, string attributeName, b } // null == no obsolete, String.Empty == no description - public static string GetObsoleteMessage (this XElement self) + public static string? GetObsoleteMessage (this XElement self) { - if (TryGetAttributeProperty (self, "System.ObsoleteAttribute", false, out string message)) + if (TryGetAttributeProperty (self, "System.ObsoleteAttribute", false, out string? message)) return message ?? String.Empty; return null; } - public static IEnumerable Descendants (this XElement self, params string [] names) + public static IEnumerable? Descendants (this XElement self, params string [] names) { - XElement el = self; + XElement? el = self; if (el is null) return null; @@ -110,7 +110,7 @@ public static IEnumerable Descendants (this XElement self, params stri return el.Elements (names [names.Length - 1]); } - public static List DescendantList (this XElement self, params string [] names) + public static List? DescendantList (this XElement self, params string [] names) { var descendants = self.Descendants (names); if (descendants is null) @@ -119,14 +119,15 @@ public static List DescendantList (this XElement self, params string [ } // make it beautiful (.NET -> C#) - public static string GetTypeName (this XElement self, string name, State state) + public static string? GetTypeName (this XElement self, string name, State state) { - string type = self.GetAttribute (name); + string? type = self.GetAttribute (name); if (type is null) return null; - StringBuilder sb = null; + StringBuilder sb = null!; bool is_nullable = false; + bool is_nullable_ref = false; if (type.StartsWith ("System.Nullable`1[", StringComparison.Ordinal)) { is_nullable = true; sb = new StringBuilder (type, 18, type.Length - 19, 1024); @@ -134,6 +135,12 @@ public static string GetTypeName (this XElement self, string name, State state) sb = new StringBuilder (type); } + // Handle nullable reference type annotation (trailing '?' added by mono-api-info) + if (!is_nullable && sb.Length > 0 && sb [sb.Length - 1] == '?') { + is_nullable_ref = true; + sb.Remove (sb.Length - 1, 1); + } + bool is_ref = (sb [sb.Length - 1] == '&'); if (is_ref) sb.Remove (sb.Length - 1, 1); @@ -159,6 +166,8 @@ public static string GetTypeName (this XElement self, string name, State state) sb.Append ("[]"); if (is_nullable) sb.Append ('?'); + if (is_nullable_ref) + sb.Append ('?'); if (is_pointer) sb.Append ('*'); return sb.ToString (); @@ -245,5 +254,32 @@ public static FieldAttributes GetFieldAttributes (this XElement element) var srcAttribs = element.Attribute ("attrib"); return (FieldAttributes) (srcAttribs is not null ? Int32.Parse (srcAttribs.Value) : 0); } + + // Strips trailing '?' nullability annotations from a type name for comparison purposes. + // Handles both top-level (System.String?) and nested generics (List`1[System.String?]). + public static string? StripNullability (string? type) + { + if (type is null) + return null; + // Remove all '?' that appear before ']', at end of string, before ',', + // before '>' or '&' (HTML entities like >), or before ' ' (before param name) + var sb = new StringBuilder (type.Length); + for (int i = 0; i < type.Length; i++) { + if (type [i] == '?') { + if (i + 1 >= type.Length || type [i + 1] == ']' || type [i + 1] == ',' || type [i + 1] == '>' || type [i + 1] == '&' || type [i + 1] == ' ') + continue; + } + sb.Append (type [i]); + } + return sb.ToString (); + } + + // Returns true if two type names differ only in nullability annotations. + public static bool DiffersOnlyByNullability (string? source, string? target) + { + if (source == target) + return false; + return StripNullability (source) == StripNullability (target); + } } } diff --git a/tools/api-tools/mono-api-html/InterfaceComparer.cs b/tools/api-tools/mono-api-html/InterfaceComparer.cs index a0eee9de0c48..2ec155a5c1b5 100644 --- a/tools/api-tools/mono-api-html/InterfaceComparer.cs +++ b/tools/api-tools/mono-api-html/InterfaceComparer.cs @@ -46,7 +46,7 @@ public override string ElementName { public override string GetDescription (XElement e) { - return e.GetTypeName ("name", State); + return e.GetTypeName ("name", State) ?? ""; } } } diff --git a/tools/api-tools/mono-api-html/MemberComparer.cs b/tools/api-tools/mono-api-html/MemberComparer.cs index 7fa20dbfb49c..f0f5915c384b 100644 --- a/tools/api-tools/mono-api-html/MemberComparer.cs +++ b/tools/api-tools/mono-api-html/MemberComparer.cs @@ -51,7 +51,7 @@ public void Compare (XElement source, XElement target) return; if (s is null) { - Add (t.Elements (ElementName)); + Add (t!.Elements (ElementName)); } else if (t is null) { Remove (s.Elements (ElementName)); } else { @@ -65,7 +65,7 @@ public override void SetContext (XElement current) string GetContainingType (XElement el) { - return el.Ancestors ("class").First ().Attribute ("type").Value; + return el.Ancestors ("class").First ().Attribute ("type")!.Value; } bool IsInInterface (XElement el) @@ -73,19 +73,19 @@ bool IsInInterface (XElement el) return GetContainingType (el) == "interface"; } - public XElement Source { get; set; } + public XElement Source { get; set; } = null!; public virtual bool Find (XElement e) { return e.GetAttribute ("name") == Source.GetAttribute ("name"); } - XElement Find (IEnumerable target) + XElement? Find (IEnumerable target) { return target.SingleOrDefault (Find); } - public override void Compare (IEnumerable source, IEnumerable target) + public override void Compare (IEnumerable source, IEnumerable? target) { removed.Clear (); modified.Clear (); @@ -93,7 +93,7 @@ public override void Compare (IEnumerable source, IEnumerable source, IEnumerable elements) @@ -133,11 +134,24 @@ void Add (IEnumerable elements) void Modify (ApiChanges modified) { foreach (var changes in modified) { - Formatter.BeginMemberModification (changes.Key); - foreach (var element in changes.Value) { - Formatter.Diff (element); + var nonNullability = changes.Value.Where (c => !c.IsNullabilityChange).ToList (); + var nullabilityOnly = changes.Value.Where (c => c.IsNullabilityChange).ToList (); + + if (nonNullability.Count > 0) { + Formatter.BeginMemberModification (changes.Key); + foreach (var element in nonNullability) { + Formatter.Diff (element); + } + Formatter.EndMemberModification (); + } + + if (nullabilityOnly.Count > 0) { + Formatter.BeginMemberModification (changes.Key + " (nullability)"); + foreach (var element in nullabilityOnly) { + Formatter.Diff (element); + } + Formatter.EndMemberModification (); } - Formatter.EndMemberModification (); } } @@ -162,7 +176,7 @@ void Remove (IEnumerable elements) protected StringBuilder GetObsoleteMessage (XElement e) { var sb = new StringBuilder (); - string o = e.GetObsoleteMessage (); + string? o = e.GetObsoleteMessage (); if (o is not null) { sb.Append ("[Obsolete"); if (o.Length > 0) @@ -237,12 +251,12 @@ protected void RenderGenericParameters (XElement source, XElement target, ApiCha if (i > 0) change.Append (", "); if (i >= srcCount) { - change.AppendAdded (RenderGenericParameter (tgt [i])); + change.AppendAdded (RenderGenericParameter (tgt! [i])); } else if (i >= tgtCount) { - change.AppendRemoved (RenderGenericParameter (src [i])); + change.AppendRemoved (RenderGenericParameter (src! [i])); } else { - var srcName = RenderGenericParameter (src [i]); - var tgtName = RenderGenericParameter (tgt [i]); + var srcName = RenderGenericParameter (src! [i]); + var tgtName = RenderGenericParameter (tgt! [i]); if (srcName != tgtName) { change.AppendModified (srcName, tgtName); @@ -254,7 +268,7 @@ protected void RenderGenericParameters (XElement source, XElement target, ApiCha change.Append (Formatter.GreaterThan); } - protected string FormatValue (string type, string value) + protected string FormatValue (string? type, string? value) { if (value is null) return "null"; @@ -287,8 +301,8 @@ protected void RenderParameters (XElement source, XElement target, ApiChange cha if (i > 0) change.Append (", "); - string mods_tgt = tgt [i].GetAttribute ("direction") ?? ""; - string mods_src = src [i].GetAttribute ("direction") ?? ""; + string mods_tgt = tgt! [i].GetAttribute ("direction") ?? ""; + string mods_src = src! [i].GetAttribute ("direction") ?? ""; if (mods_tgt.Length > 0) mods_tgt = mods_tgt + " "; @@ -297,12 +311,12 @@ protected void RenderParameters (XElement source, XElement target, ApiChange cha mods_src = mods_src + " "; if (i >= srcCount) { - change.AppendAdded (mods_tgt + tgt [i].GetTypeName ("type", State) + " " + tgt [i].GetAttribute ("name")); + change.AppendAdded (mods_tgt + tgt! [i].GetTypeName ("type", State) + " " + tgt [i].GetAttribute ("name")); } else if (i >= tgtCount) { - change.AppendRemoved (mods_src + src [i].GetTypeName ("type", State) + " " + src [i].GetAttribute ("name")); + change.AppendRemoved (mods_src + src! [i].GetTypeName ("type", State) + " " + src [i].GetAttribute ("name")); } else { - var paramSourceType = src [i].GetTypeName ("type", State); - var paramTargetType = tgt [i].GetTypeName ("type", State); + var paramSourceType = src! [i].GetTypeName ("type", State); + var paramTargetType = tgt! [i].GetTypeName ("type", State); var paramSourceName = src [i].GetAttribute ("name"); var paramTargetName = tgt [i].GetAttribute ("name"); @@ -314,15 +328,15 @@ protected void RenderParameters (XElement source, XElement target, ApiChange cha } if (paramSourceType != paramTargetType) { - change.AppendModified (paramSourceType, paramTargetType); + change.AppendTypeModified (paramSourceType ?? "", paramTargetType ?? ""); } else { - change.Append (paramSourceType); + change.Append (paramSourceType ?? ""); } change.Append (" "); if (paramSourceName != paramTargetName) { - change.AppendModified (paramSourceName, paramTargetName); + change.AppendModified (paramSourceName ?? "", paramTargetName ?? ""); } else { - change.Append (paramSourceName); + change.Append (paramSourceName ?? ""); } var optSource = src [i].Attribute ("optional"); @@ -467,13 +481,13 @@ protected void RemoveInternalFromProtectedInternal (XElement element) // Changing between 'protected' and 'protected internal' is not visible in the API, so remove the 'internal' part. if ((attrib & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem) { attrib = (attrib & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Family; - element.Attribute ("attrib").Value = ((int) attrib).ToString (); + element.Attribute ("attrib")!.Value = ((int) attrib).ToString (); } } protected void RenderName (XElement source, XElement target, ApiChange change) { - var name = target.GetAttribute ("name"); + var name = target.GetAttribute ("name") ?? ""; // show the constructor as it would be defined in C# name = name.Replace (".ctor", State.Type); diff --git a/tools/api-tools/mono-api-html/MethodComparer.cs b/tools/api-tools/mono-api-html/MethodComparer.cs index 9d9d58ce7266..6846c1cf6b4f 100644 --- a/tools/api-tools/mono-api-html/MethodComparer.cs +++ b/tools/api-tools/mono-api-html/MethodComparer.cs @@ -52,7 +52,7 @@ public override bool Find (XElement e) if (e.GetAttribute ("name") != Source.GetAttribute ("name")) return false; - if (e.GetAttribute ("returntype") != Source.GetAttribute ("returntype")) + if (Helper.StripNullability (e.GetAttribute ("returntype")) != Helper.StripNullability (Source.GetAttribute ("returntype"))) return false; var eGP = e.Element ("generic-parameters"); @@ -63,8 +63,8 @@ public override bool Find (XElement e) else if (eGP is null ^ sGP is null) return false; else { - var eGPs = eGP.Elements ("generic-parameter"); - var sGPs = sGP.Elements ("generic-parameter"); + var eGPs = eGP!.Elements ("generic-parameter"); + var sGPs = sGP!.Elements ("generic-parameter"); return eGPs.Count () == sGPs.Count (); } } diff --git a/tools/api-tools/mono-api-html/NamespaceComparer.cs b/tools/api-tools/mono-api-html/NamespaceComparer.cs index c2b65bba7463..e0d01e579302 100644 --- a/tools/api-tools/mono-api-html/NamespaceComparer.cs +++ b/tools/api-tools/mono-api-html/NamespaceComparer.cs @@ -56,20 +56,20 @@ public void Compare (XElement source, XElement target) var t = target.Element ("namespaces"); if (XNode.DeepEquals (s, t)) return; - Compare (s.Elements ("namespace"), t.Elements ("namespace")); + Compare (s!.Elements ("namespace"), t!.Elements ("namespace")); } public override void SetContext (XElement current) { - State.Namespace = current.Attribute ("name").Value; + State.Namespace = current.Attribute ("name")!.Value; } public override void Added (XElement target, bool wasParentAdded) { Formatter.BeginNamespace ("New "); // list all new types - foreach (var addedType in target.Element ("classes").Elements ("class")) { - State.Type = addedType.Attribute ("name").Value; + foreach (var addedType in target.Element ("classes")!.Elements ("class")) { + State.Type = addedType.Attribute ("name")!.Value; comparer.Added (addedType, true); } Formatter.EndNamespace (); @@ -96,8 +96,8 @@ public override void Removed (XElement source) Formatter.BeginNamespace ("Removed "); Output.WriteLine (); // list all removed types - foreach (var removedType in source.Element ("classes").Elements ("class")) { - State.Type = comparer.GetTypeName (removedType); + foreach (var removedType in source.Element ("classes")!.Elements ("class")) { + State.Type = comparer.GetTypeName (removedType) ?? ""; comparer.Removed (removedType); } Formatter.EndNamespace (); diff --git a/tools/api-tools/mono-api-html/PropertyComparer.cs b/tools/api-tools/mono-api-html/PropertyComparer.cs index d0ab5d616114..a2783f0782d0 100644 --- a/tools/api-tools/mono-api-html/PropertyComparer.cs +++ b/tools/api-tools/mono-api-html/PropertyComparer.cs @@ -55,7 +55,7 @@ public override bool Find (XElement e) return e.GetAttribute ("params") == Source.GetAttribute ("params"); } - void GetAccessors (XElement element, out XElement getter, out XElement setter) + void GetAccessors (XElement element, out XElement? getter, out XElement? setter) { var methods = element.Element ("methods"); @@ -66,7 +66,7 @@ void GetAccessors (XElement element, out XElement getter, out XElement setter) return; foreach (var m in methods.Elements ("method")) { - var n = m.GetAttribute ("name"); + var n = m.GetAttribute ("name") ?? ""; if (n.StartsWith ("get_", StringComparison.Ordinal)) { getter = m; } else if (n.StartsWith ("set_", StringComparison.Ordinal)) { @@ -75,10 +75,10 @@ void GetAccessors (XElement element, out XElement getter, out XElement setter) } } - MethodAttributes GetMethodAttributes (XElement getter, XElement setter) + MethodAttributes GetMethodAttributes (XElement? getter, XElement? setter) { if (getter is null) - return setter.GetMethodAttributes (); + return setter!.GetMethodAttributes (); else if (setter is null) return getter.GetMethodAttributes (); @@ -97,18 +97,18 @@ MethodAttributes GetMethodAttributes (XElement getter, XElement setter) void RenderPropertyType (XElement source, XElement target, ApiChange change) { - var srcType = source.GetTypeName ("ptype", State); - var tgtType = target.GetTypeName ("ptype", State); + var srcType = source.GetTypeName ("ptype", State) ?? ""; + var tgtType = target.GetTypeName ("ptype", State) ?? ""; if (srcType == tgtType) { change.Append (tgtType); } else { - change.AppendModified (srcType, tgtType); + change.AppendTypeModified (srcType, tgtType); } change.Append (" "); } - void RenderAccessors (XElement srcGetter, XElement tgtGetter, XElement srcSetter, XElement tgtSetter, ApiChange change) + void RenderAccessors (XElement? srcGetter, XElement? tgtGetter, XElement? srcSetter, XElement? tgtSetter, ApiChange change) { // FIXME: this doesn't render changes in the accessor visibility (a protected setter can become public for instance). change.Append (" {"); @@ -145,17 +145,17 @@ void RenderIndexers (List srcIndexers, List tgtIndexers, Api if (i > 0) change.Append (", "); - var srcType = source.GetTypeName ("type", State); - var tgtType = target.GetTypeName ("type", State); + var srcType = source.GetTypeName ("type", State) ?? ""; + var tgtType = target.GetTypeName ("type", State) ?? ""; if (srcType == tgtType) { change.Append (tgtType); } else { - change.AppendModified (srcType, tgtType); + change.AppendTypeModified (srcType, tgtType); } change.Append (" "); - var srcName = source.GetAttribute ("name"); - var tgtName = target.GetAttribute ("name"); + var srcName = source.GetAttribute ("name") ?? ""; + var tgtName = target.GetAttribute ("name") ?? ""; if (srcName == tgtName) { change.Append (tgtName); } else { @@ -170,17 +170,17 @@ public override bool Equals (XElement source, XElement target, ApiChanges change if (base.Equals (source, target, changes)) return true; - XElement srcGetter, srcSetter; - XElement tgtGetter, tgtSetter; + XElement? srcGetter, srcSetter; + XElement? tgtGetter, tgtSetter; GetAccessors (source, out srcGetter, out srcSetter); GetAccessors (target, out tgtGetter, out tgtSetter); - List srcIndexers = null; - List tgtIndexers = null; + List? srcIndexers = null; + List? tgtIndexers = null; bool isIndexer = false; if (srcGetter is not null) { srcIndexers = srcGetter.DescendantList ("parameters", "parameter"); - tgtIndexers = tgtGetter.DescendantList ("parameters", "parameter"); + tgtIndexers = tgtGetter?.DescendantList ("parameters", "parameter"); isIndexer = srcIndexers is not null && srcIndexers.Count > 0; } @@ -189,8 +189,8 @@ public override bool Equals (XElement source, XElement target, ApiChanges change RenderAttributes (source, target, change); RenderMethodAttributes (source, target, GetMethodAttributes (srcGetter, srcSetter), GetMethodAttributes (tgtGetter, tgtSetter), change); RenderPropertyType (source, target, change); - if (isIndexer) { - RenderIndexers (srcIndexers, tgtIndexers, change); + if (isIndexer && tgtIndexers is not null) { + RenderIndexers (srcIndexers!, tgtIndexers, change); } else { RenderName (source, target, change); } @@ -211,10 +211,10 @@ void GetProperties (XElement e, out bool @virtual, out bool @override, out bool foreach (var m in methods.Elements ("method")) { @virtual |= m.IsTrue ("virtual"); @static |= m.IsTrue ("static"); - var n = m.GetAttribute ("name"); + var n = m.GetAttribute ("name") ?? ""; getter |= n.StartsWith ("get_", StringComparison.Ordinal); setter |= n.StartsWith ("set_", StringComparison.Ordinal); - var attribs = (MethodAttributes) Int32.Parse (m.GetAttribute ("attrib")); + var attribs = (MethodAttributes) Int32.Parse (m.GetAttribute ("attrib") ?? "0"); family = ((attribs & MethodAttributes.Public) != MethodAttributes.Public); @override |= (attribs & MethodAttributes.NewSlot) == 0; } @@ -223,8 +223,8 @@ void GetProperties (XElement e, out bool @virtual, out bool @override, out bool public override string GetDescription (XElement e) { - string name = e.Attribute ("name").Value; - string ptype = e.GetTypeName ("ptype", State); + string name = e.Attribute ("name")!.Value; + string ptype = e.GetTypeName ("ptype", State) ?? ""; bool virt = false; bool over = false; diff --git a/tools/api-tools/mono-api-info/Util.cs b/tools/api-tools/mono-api-info/Util.cs index bd4f7270700f..43e222825594 100644 --- a/tools/api-tools/mono-api-info/Util.cs +++ b/tools/api-tools/mono-api-info/Util.cs @@ -90,7 +90,7 @@ internal IEnumerable GetInterfaces (TypeReference type) return ifaces.Values; } - internal TypeDefinition GetBaseType (TypeDefinition child) + internal TypeDefinition? GetBaseType (TypeDefinition child) { if (child.BaseType is null) return null; @@ -102,7 +102,7 @@ internal TypeDefinition GetBaseType (TypeDefinition child) } } - internal MethodDefinition GetMethod (MethodReference method) + internal MethodDefinition? GetMethod (MethodReference method) { if (method is null) throw new ArgumentNullException (nameof (method)); @@ -134,14 +134,14 @@ bool IsOverride (MethodDefinition method) return method.IsVirtual && !method.IsNewSlot; } - public MethodDefinition GetBaseMethodInTypeHierarchy (MethodDefinition method) + public MethodDefinition? GetBaseMethodInTypeHierarchy (MethodDefinition method) { if (!IsOverride (method)) return method; var @base = GetBaseType (method.DeclaringType); while (@base is not null) { - MethodDefinition base_method = TryMatchMethod (@base.Resolve (), method); + MethodDefinition? base_method = TryMatchMethod (@base.Resolve (), method); if (base_method is not null) return GetBaseMethodInTypeHierarchy (base_method) ?? base_method; @@ -151,7 +151,7 @@ public MethodDefinition GetBaseMethodInTypeHierarchy (MethodDefinition method) return method; } - MethodDefinition TryMatchMethod (TypeDefinition type, MethodDefinition method) + MethodDefinition? TryMatchMethod (TypeDefinition type, MethodDefinition method) { if (!type.HasMethods) return null; diff --git a/tools/api-tools/mono-api-info/WellFormedXmlWriter.cs b/tools/api-tools/mono-api-info/WellFormedXmlWriter.cs index 259176e4347a..754f198a84b1 100644 --- a/tools/api-tools/mono-api-info/WellFormedXmlWriter.cs +++ b/tools/api-tools/mono-api-info/WellFormedXmlWriter.cs @@ -77,8 +77,12 @@ public WellFormedXmlWriter (XmlWriter writer) : base (writer) { } - public override void WriteString (string text) + public override void WriteString (string? text) { + if (text is null) { + Writer.WriteString (text); + return; + } int i = IndexOfInvalid (text, true); if (i >= 0) { char [] arr = text.ToCharArray (); @@ -131,7 +135,7 @@ public override void Flush () writer.Flush (); } - public override string LookupPrefix (string ns) + public override string? LookupPrefix (string ns) { return writer.LookupPrefix (ns); } @@ -146,7 +150,7 @@ public override void WriteBinHex (byte [] buffer, int index, int count) writer.WriteBinHex (buffer, index, count); } - public override void WriteCData (string text) + public override void WriteCData (string? text) { writer.WriteCData (text); } @@ -161,12 +165,12 @@ public override void WriteChars (char [] buffer, int index, int count) writer.WriteChars (buffer, index, count); } - public override void WriteComment (string text) + public override void WriteComment (string? text) { writer.WriteComment (text); } - public override void WriteDocType (string name, string pubid, string sysid, string subset) + public override void WriteDocType (string name, string? pubid, string? sysid, string? subset) { writer.WriteDocType (name, pubid, sysid, subset); } @@ -211,12 +215,12 @@ public override void WriteNode (XmlReader reader, bool defattr) writer.WriteNode (reader, defattr); } - public override void WriteProcessingInstruction (string name, string text) + public override void WriteProcessingInstruction (string name, string? text) { writer.WriteProcessingInstruction (name, text); } - public override void WriteQualifiedName (string localName, string ns) + public override void WriteQualifiedName (string localName, string? ns) { writer.WriteQualifiedName (localName, ns); } @@ -231,7 +235,7 @@ public override void WriteRaw (char [] buffer, int index, int count) writer.WriteRaw (buffer, index, count); } - public override void WriteStartAttribute (string prefix, string localName, string ns) + public override void WriteStartAttribute (string? prefix, string localName, string? ns) { writer.WriteStartAttribute (prefix, localName, ns); } @@ -246,12 +250,12 @@ public override void WriteStartDocument () writer.WriteStartDocument (); } - public override void WriteStartElement (string prefix, string localName, string ns) + public override void WriteStartElement (string? prefix, string localName, string? ns) { writer.WriteStartElement (prefix, localName, ns); } - public override void WriteString (string text) + public override void WriteString (string? text) { writer.WriteString (text); } @@ -261,7 +265,7 @@ public override void WriteSurrogateCharEntity (char lowChar, char highChar) writer.WriteSurrogateCharEntity (lowChar, highChar); } - public override void WriteWhitespace (string ws) + public override void WriteWhitespace (string? ws) { writer.WriteWhitespace (ws); } @@ -272,7 +276,7 @@ public override WriteState WriteState { } } - public override string XmlLang { + public override string? XmlLang { get { return writer.XmlLang; } diff --git a/tools/api-tools/mono-api-info/mono-api-info.cs b/tools/api-tools/mono-api-info/mono-api-info.cs index 07d6c3791c3b..1b22201ef597 100644 --- a/tools/api-tools/mono-api-info/mono-api-info.cs +++ b/tools/api-tools/mono-api-info/mono-api-info.cs @@ -29,8 +29,8 @@ class Driver { public static int Main (string [] args) { bool showHelp = false; - string output = null; - List asms = null; + string? output = null; + List? asms = null; ApiInfoConfig config = new ApiInfoConfig (); var options = new Mono.Options.OptionSet { @@ -82,7 +82,7 @@ public static int Main (string [] args) return showHelp ? 0 : 1; } - TextWriter outputStream = null; + TextWriter? outputStream = null; try { if (!string.IsNullOrEmpty (output)) outputStream = new StreamWriter (output); @@ -116,7 +116,7 @@ class State { public List ResolveStreams { get; } = new List (); - public TypeHelper TypeHelper { get; private set; } + public TypeHelper TypeHelper { get; private set; } = null!; public void ResolveTypes () { @@ -156,7 +156,7 @@ public class ApiInfoConfig { } public static class ApiInfo { - public static void Generate (string assemblyPath, TextWriter outStream, ApiInfoConfig config = null) + public static void Generate (string assemblyPath, TextWriter outStream, ApiInfoConfig? config = null) { if (assemblyPath is null) throw new ArgumentNullException (nameof (assemblyPath)); @@ -164,7 +164,7 @@ public static void Generate (string assemblyPath, TextWriter outStream, ApiInfoC Generate (new [] { assemblyPath }, null, outStream, config); } - public static void Generate (Stream assemblyStream, TextWriter outStream, ApiInfoConfig config = null) + public static void Generate (Stream assemblyStream, TextWriter outStream, ApiInfoConfig? config = null) { if (assemblyStream is null) throw new ArgumentNullException (nameof (assemblyStream)); @@ -172,17 +172,17 @@ public static void Generate (Stream assemblyStream, TextWriter outStream, ApiInf Generate (null, new [] { assemblyStream }, outStream, config); } - public static void Generate (IEnumerable assemblyPaths, TextWriter outStream, ApiInfoConfig config = null) + public static void Generate (IEnumerable assemblyPaths, TextWriter outStream, ApiInfoConfig? config = null) { Generate (assemblyPaths, null, outStream, config); } - public static void Generate (IEnumerable assemblyStreams, TextWriter outStream, ApiInfoConfig config = null) + public static void Generate (IEnumerable assemblyStreams, TextWriter outStream, ApiInfoConfig? config = null) { Generate (null, assemblyStreams, outStream, config); } - public static void Generate (IEnumerable assemblyPaths, IEnumerable assemblyStreams, TextWriter outStream, ApiInfoConfig config = null) + public static void Generate (IEnumerable? assemblyPaths, IEnumerable? assemblyStreams, TextWriter outStream, ApiInfoConfig? config = null) { if (outStream is null) throw new ArgumentNullException (nameof (outStream)); @@ -204,7 +204,7 @@ public static void Generate (IEnumerable assemblyPaths, IEnumerable assemblyFiles, IEnumerable assemblyStreams, TextWriter outStream, State state = null) + internal static void Generate (IEnumerable? assemblyFiles, IEnumerable? assemblyStreams, TextWriter outStream, State? state = null) { if (outStream is null) throw new ArgumentNullException (nameof (outStream)); @@ -295,7 +295,7 @@ public static string CleanupTypeName (string t) } class AssemblyCollection { - XmlWriter writer; + XmlWriter writer = null!; List assemblies = new List (); State state; @@ -384,7 +384,7 @@ public override void DoOutput () continue; writer.WriteStartElement ("attribute"); - AddAttribute ("name", typeof (TypeForwardedToAttribute).FullName); + AddAttribute ("name", typeof (TypeForwardedToAttribute).FullName!); writer.WriteStartElement ("properties"); writer.WriteStartElement ("property"); AddAttribute ("name", "Destination"); @@ -497,7 +497,7 @@ public MemberData (XmlWriter writer, MemberReference [] members, State state) this.members = members; } - protected virtual ICustomAttributeProvider GetAdditionalCustomAttributeProvider (MemberReference member) + protected virtual ICustomAttributeProvider? GetAdditionalCustomAttributeProvider (MemberReference member) { return null; } @@ -510,10 +510,14 @@ public override void DoOutput () writer.WriteStartElement (Tag); AddAttribute ("name", GetName (member)); if (!NoMemberAttributes) - AddAttribute ("attrib", GetMemberAttributes (member)); + AddAttribute ("attrib", GetMemberAttributes (member) ?? ""); AddExtraAttributes (member); - AttributeData.OutputAttributes (writer, state, (ICustomAttributeProvider) member, GetAdditionalCustomAttributeProvider (member)); + var additionalProvider = GetAdditionalCustomAttributeProvider (member); + if (additionalProvider is not null) + AttributeData.OutputAttributes (writer, state, (ICustomAttributeProvider) member, additionalProvider); + else + AttributeData.OutputAttributes (writer, state, (ICustomAttributeProvider) member); AddExtraData (member); writer.WriteEndElement (); // Tag @@ -535,7 +539,7 @@ protected virtual string GetName (MemberReference memberDefenition) return "NoNAME"; } - protected virtual string GetMemberAttributes (MemberReference memberDefenition) + protected virtual string? GetMemberAttributes (MemberReference memberDefenition) { return null; } @@ -596,7 +600,7 @@ class TypeData : MemberData { TypeDefinition type; public TypeData (XmlWriter writer, TypeDefinition type, State state) - : base (writer, null, state) + : base (writer, [], state) { this.type = type; } @@ -625,7 +629,7 @@ public override void DoOutput () string charSet = GetCharSet (type); AddAttribute ("charset", charSet); - string layout = GetLayout (type); + string? layout = GetLayout (type); if (layout is not null) AddAttribute ("layout", layout); @@ -732,7 +736,7 @@ public override void DoOutput () writer.WriteEndElement (); // class } - static FieldReference GetEnumValueField (TypeDefinition type) + static FieldReference? GetEnumValueField (TypeDefinition type) { foreach (FieldDefinition field in type.Fields) if (field.IsSpecialName && field.Name == "value__") @@ -793,7 +797,7 @@ static string GetCharSet (TypeDefinition type) return CharSet.None.ToString (); } - static string GetLayout (TypeDefinition type) + static string? GetLayout (TypeDefinition type) { TypeAttributes maskedLayout = type.Attributes & TypeAttributes.LayoutMask; if (maskedLayout == TypeAttributes.AutoLayout) @@ -926,8 +930,10 @@ private MethodDefinition [] GetMethods (TypeDefinition type, bool fullAPI) } sealed class ParameterComparer : IEqualityComparer { - public bool Equals (ParameterDefinition x, ParameterDefinition y) + public bool Equals (ParameterDefinition? x, ParameterDefinition? y) { + if (x is null || y is null) + return x is null && y is null; return x.ParameterType.Name == y.ParameterType.Name; } @@ -1008,11 +1014,13 @@ protected override void AddExtraAttributes (MemberReference memberDefinition) base.AddExtraAttributes (memberDefinition); FieldDefinition field = (FieldDefinition) memberDefinition; - AddAttribute ("fieldtype", Utils.CleanupTypeName (field.FieldType)); + var fieldTypeName = Utils.CleanupTypeName (field.FieldType); + fieldTypeName = NullabilityHelper.AppendNullabilityToTypeName (fieldTypeName, field.FieldType, field, field.DeclaringType); + AddAttribute ("fieldtype", fieldTypeName); if (field.IsLiteral) { object value = field.Constant;//object value = field.GetValue (null); - string stringValue = null; + string? stringValue = null; //if (value is Enum) { // // FIXME: when Mono bug #60090 has been // // fixed, we should just be able to use @@ -1049,21 +1057,21 @@ protected override string GetName (MemberReference memberDefenition) return prop.Name; } - MethodDefinition [] GetMethods (PropertyDefinition prop, out bool haveParameters) + MethodDefinition []? GetMethods (PropertyDefinition prop, out bool haveParameters) { MethodDefinition _get = prop.GetMethod; MethodDefinition _set = prop.SetMethod; bool haveGet = (_get is not null && TypeData.MustDocumentMethod (_get)); bool haveSet = (_set is not null && TypeData.MustDocumentMethod (_set)); - haveParameters = haveGet || (haveSet && _set.Parameters.Count > 1); + haveParameters = haveGet || (haveSet && _set!.Parameters.Count > 1); MethodDefinition [] methods; if (haveGet && haveSet) { - methods = new MethodDefinition [] { _get, _set }; + methods = new MethodDefinition [] { _get!, _set! }; } else if (haveGet) { - methods = new MethodDefinition [] { _get }; + methods = new MethodDefinition [] { _get! }; } else if (haveSet) { - methods = new MethodDefinition [] { _set }; + methods = new MethodDefinition [] { _set! }; } else { //odd return null; @@ -1077,10 +1085,12 @@ protected override void AddExtraAttributes (MemberReference memberDefinition) base.AddExtraAttributes (memberDefinition); PropertyDefinition prop = (PropertyDefinition) memberDefinition; - AddAttribute ("ptype", Utils.CleanupTypeName (prop.PropertyType)); + var ptypeName = Utils.CleanupTypeName (prop.PropertyType); + ptypeName = NullabilityHelper.AppendNullabilityToTypeName (ptypeName, prop.PropertyType, prop, prop.DeclaringType); + AddAttribute ("ptype", ptypeName); bool haveParameters; - MethodDefinition [] methods = GetMethods ((PropertyDefinition) memberDefinition, out haveParameters); + MethodDefinition []? methods = GetMethods ((PropertyDefinition) memberDefinition, out haveParameters); if (methods is not null && haveParameters) { string parms = Parameters.GetSignature (methods [0].Parameters); @@ -1095,7 +1105,7 @@ protected override void AddExtraData (MemberReference memberDefenition) base.AddExtraData (memberDefenition); bool haveParameters; - MethodDefinition [] methods = GetMethods ((PropertyDefinition) memberDefenition, out haveParameters); + MethodDefinition []? methods = GetMethods ((PropertyDefinition) memberDefenition, out haveParameters); if (methods is null) return; @@ -1143,7 +1153,9 @@ protected override void AddExtraAttributes (MemberReference memberDefinition) base.AddExtraAttributes (memberDefinition); EventDefinition evt = (EventDefinition) memberDefinition; - AddAttribute ("eventtype", Utils.CleanupTypeName (evt.EventType)); + var evtTypeName = Utils.CleanupTypeName (evt.EventType); + evtTypeName = NullabilityHelper.AppendNullabilityToTypeName (evtTypeName, evt.EventType, evt, evt.DeclaringType); + AddAttribute ("eventtype", evtTypeName); } public override string ParentTag { @@ -1211,8 +1223,10 @@ protected override void AddExtraAttributes (MemberReference memberDefinition) AddAttribute ("is-override", "true"); } string rettype = Utils.CleanupTypeName (mbase.MethodReturnType.ReturnType); - if (rettype != "System.Void" || !mbase.IsConstructor) + if (rettype != "System.Void" || !mbase.IsConstructor) { + rettype = NullabilityHelper.AppendNullabilityToTypeName (rettype, mbase.MethodReturnType.ReturnType, mbase.MethodReturnType, mbase); AddAttribute ("returntype", (rettype)); + } // // if (mbase.MethodReturnType.HasCustomAttributes) // AttributeData.OutputAttributes (writer, mbase.MethodReturnType); @@ -1296,12 +1310,12 @@ public override void DoOutput () pt = brt.ElementType; } - AddAttribute ("type", Utils.CleanupTypeName (pt)); + AddAttribute ("type", NullabilityHelper.AppendNullabilityToTypeName (Utils.CleanupTypeName (pt), pt, parameter, parameter.Method as ICustomAttributeProvider)); if (parameter.IsOptional) { AddAttribute ("optional", "true"); if (parameter.HasConstant) - AddAttribute ("defaultValue", parameter.Constant is null ? "NULL" : parameter.Constant.ToString ()); + AddAttribute ("defaultValue", parameter.Constant is null ? "NULL" : parameter.Constant.ToString () ?? ""); } if (direction != "in") @@ -1450,11 +1464,138 @@ public static string GetSignature (IList infos) } + static class NullabilityHelper { + const string NullableAttributeName = "System.Runtime.CompilerServices.NullableAttribute"; + const string NullableContextAttributeName = "System.Runtime.CompilerServices.NullableContextAttribute"; + + // Returns the nullability flag for the top-level type: + // 0 = oblivious, 1 = not-null, 2 = nullable + public static byte GetTopLevelNullability (ICustomAttributeProvider provider, ICustomAttributeProvider? context) + { + // Check for NullableAttribute directly on the member/parameter/return type + var flag = GetNullableFlagFromProvider (provider); + if (flag.HasValue) + return flag.Value; + + // Fall back to NullableContextAttribute on the containing method/type + if (context is not null) { + var contextFlag = GetNullableContextFlag (context); + if (contextFlag.HasValue) + return contextFlag.Value; + } + + return 0; // oblivious + } + + // Gets the NullableContextAttribute flag from a method or type + public static byte? GetNullableContextFlag (ICustomAttributeProvider provider) + { + if (provider is null) + return null; + + if (!provider.HasCustomAttributes) + return GetNullableContextFromParent (provider); + + foreach (var attr in provider.CustomAttributes) { + if (attr.AttributeType.FullName != NullableContextAttributeName) + continue; + if (attr.ConstructorArguments.Count == 1 && attr.ConstructorArguments [0].Value is byte b) + return b; + } + + return GetNullableContextFromParent (provider); + } + + static byte? GetNullableContextFromParent (ICustomAttributeProvider? provider) + { + if (provider is MethodDefinition method) + return GetNullableContextFlag (method.DeclaringType); + if (provider is PropertyDefinition prop) + return GetNullableContextFlag (prop.DeclaringType); + if (provider is FieldDefinition field) + return GetNullableContextFlag (field.DeclaringType); + if (provider is EventDefinition evt) + return GetNullableContextFlag (evt.DeclaringType); + if (provider is TypeDefinition type) { + if (type.DeclaringType is not null) + return GetNullableContextFlag (type.DeclaringType); + // Fall back to module-level NullableContextAttribute + return GetNullableContextFlagFromAttributes (type.Module); + } + return null; + } + + static byte? GetNullableContextFlagFromAttributes (ICustomAttributeProvider? provider) + { + if (provider is null || !provider.HasCustomAttributes) + return null; + + foreach (var attr in provider.CustomAttributes) { + if (attr.AttributeType.FullName != NullableContextAttributeName) + continue; + if (attr.ConstructorArguments.Count == 1 && attr.ConstructorArguments [0].Value is byte b) + return b; + } + return null; + } + + static byte? GetNullableFlagFromProvider (ICustomAttributeProvider provider) + { + if (!provider.HasCustomAttributes) + return null; + + foreach (var attr in provider.CustomAttributes) { + if (attr.AttributeType.FullName != NullableAttributeName) + continue; + if (attr.ConstructorArguments.Count != 1) + continue; + + var arg = attr.ConstructorArguments [0]; + if (arg.Value is byte b) + return b; + if (arg.Value is CustomAttributeArgument [] arr && arr.Length > 0 && arr [0].Value is byte b2) + return b2; + } + + return null; + } + + public static bool IsNullableReferenceType (TypeReference type, ICustomAttributeProvider provider, ICustomAttributeProvider? context) + { + if (type is null) + return false; + + // Value types use Nullable for nullability, not annotations + if (type.IsValueType) + return false; + + // ByReference types (ref/out parameters): check the element type + if (type.IsByReference) { + var elementType = ((ByReferenceType) type).ElementType; + if (elementType.IsValueType) + return false; + } + + var flag = GetTopLevelNullability (provider, context); + return flag == 2; + } + + public static string AppendNullabilityToTypeName (string typeName, TypeReference type, ICustomAttributeProvider provider, ICustomAttributeProvider? context) + { + if (IsNullableReferenceType (type, provider, context)) + return typeName + "?"; + return typeName; + } + } + class TypeReferenceComparer : IComparer { public static TypeReferenceComparer Default = new TypeReferenceComparer (); - public int Compare (TypeReference a, TypeReference b) + public int Compare (TypeReference? a, TypeReference? b) { + if (a is null && b is null) return 0; + if (a is null) return -1; + if (b is null) return 1; int result = String.Compare (a.Namespace, b.Namespace, StringComparison.Ordinal); if (result != 0) return result; @@ -1466,8 +1607,11 @@ public int Compare (TypeReference a, TypeReference b) class MemberReferenceComparer : IComparer { public static MemberReferenceComparer Default = new MemberReferenceComparer (); - public int Compare (object a, object b) + public int Compare (object? a, object? b) { + if (a is null && b is null) return 0; + if (a is null) return -1; + if (b is null) return 1; MemberReference ma = (MemberReference) a; MemberReference mb = (MemberReference) b; return String.Compare (ma.Name, mb.Name, StringComparison.Ordinal); @@ -1477,8 +1621,11 @@ public int Compare (object a, object b) class PropertyDefinitionComparer : IComparer { public static PropertyDefinitionComparer Default = new PropertyDefinitionComparer (); - public int Compare (PropertyDefinition ma, PropertyDefinition mb) + public int Compare (PropertyDefinition? ma, PropertyDefinition? mb) { + if (ma is null && mb is null) return 0; + if (ma is null) return -1; + if (mb is null) return 1; int res = String.Compare (ma.Name, mb.Name, StringComparison.Ordinal); if (res != 0) return res; @@ -1499,8 +1646,11 @@ public int Compare (PropertyDefinition ma, PropertyDefinition mb) class MethodDefinitionComparer : IComparer { public static MethodDefinitionComparer Default = new MethodDefinitionComparer (); - public int Compare (object a, object b) + public int Compare (object? a, object? b) { + if (a is null && b is null) return 0; + if (a is null) return -1; + if (b is null) return 1; MethodDefinition ma = (MethodDefinition) a; MethodDefinition mb = (MethodDefinition) b; int res = String.Compare (ma.Name, mb.Name, StringComparison.Ordinal); diff --git a/tools/class-redirector/class-redirector-tests/class-redirector-tests.csproj b/tools/class-redirector/class-redirector-tests/class-redirector-tests.csproj index acbfba419dfc..fa0748e81827 100644 --- a/tools/class-redirector/class-redirector-tests/class-redirector-tests.csproj +++ b/tools/class-redirector/class-redirector-tests/class-redirector-tests.csproj @@ -4,7 +4,6 @@ net7.0 class_redirector_tests enable - enable false diff --git a/tools/class-redirector/class-redirector/class-redirector.csproj b/tools/class-redirector/class-redirector/class-redirector.csproj index 93aabb3f2186..7e987df7f028 100644 --- a/tools/class-redirector/class-redirector/class-redirector.csproj +++ b/tools/class-redirector/class-redirector/class-redirector.csproj @@ -5,7 +5,6 @@ net7.0 class_redirector enable - enable diff --git a/tools/common/Application.cs b/tools/common/Application.cs index 87fba1263280..6aad8900c70c 100644 --- a/tools/common/Application.cs +++ b/tools/common/Application.cs @@ -68,7 +68,7 @@ public enum RegistrarMode { TrimmableStatic, } - public partial class Application { + public partial class Application : IToolLog { public Cache? Cache; public string AppDirectory = "."; public bool DeadStrip = true; @@ -158,6 +158,7 @@ public bool IsDefaultMarshalManagedExceptionMode { public bool SkipMarkingNSObjectsInUserAssemblies { get; set; } // How Mono should be embedded into the app. +#if !LEGACY_TOOLS AssemblyBuildTarget? libmono_link_mode; public AssemblyBuildTarget LibMonoLinkMode { get { @@ -192,6 +193,7 @@ public AssemblyBuildTarget LibMonoNativeLinkMode { return libmono_link_mode.Value; } } +#endif // !LEGACY_TOOLS bool RequiresXcodeHeaders { get { @@ -228,7 +230,7 @@ public bool IsDeviceBuild { public bool IsSimulatorBuild { get { - if (!string.IsNullOrEmpty (RuntimeIdentifier)) + if (!StringUtils.IsNullOrEmpty (RuntimeIdentifier)) return RuntimeIdentifier.IndexOf ("simulator", StringComparison.OrdinalIgnoreCase) >= 0; switch (Platform) { @@ -263,6 +265,14 @@ public bool PackageManagedDebugSymbols { public Version GetMacCatalystiOSVersion (Version macOSVersion) { +#if LEGACY_TOOLS + if (macOSVersion.Major >= 26 && Driver.SdkRoot is null) { + // this shouldn't happen for normal builds, nor for customers, so just show an internal 99 warning. + ErrorHelper.Warning (this, 99, Errors.MX0099, $"No Xcode configured, assuming the macOS version {macOSVersion} is identical to the Mac Catalyst/iOS version."); + return macOSVersion; + } +#endif + if (!MacCatalystSupport.TryGetiOSVersion (Driver.GetFrameworkDirectory (this), macOSVersion, out var value, out var knownMacOSVersions)) throw ErrorHelper.CreateError (184, Errors.MX0184 /* Could not map the macOS version {0} to a corresponding Mac Catalyst version. Valid macOS versions are: {1} */, macOSVersion.ToString (), string.Join (", ", knownMacOSVersions.OrderBy (v => v))); @@ -276,12 +286,15 @@ public Application (LinkerConfiguration configuration) this.LinkContext = new Tuner.DerivedLinkContext (configuration, this); #endif this.StaticRegistrar = new StaticRegistrar (this); + this.Resolver = new PlatformResolver (this); } +#if !LEGACY_TOOLS public void CreateCache (string [] arguments) { Cache = new Cache (arguments); } +#endif // !LEGACY_TOOLS public bool DynamicRegistrationSupported { get { @@ -289,6 +302,7 @@ public bool DynamicRegistrationSupported { } } +#if !LEGACY_TOOLS public void ParseCustomLinkFlags (string value, string value_name) { if (!StringUtils.TryParseArguments (value, out var lf, out var ex)) @@ -310,7 +324,9 @@ public void UnsetInterpreter () UseInterpreter = false; InterpretedAssemblies.Clear (); } +#endif // !LEGACY_TOOLS +#if !LEGACY_TOOLS public bool IsTodayExtension { get { return ExtensionIdentifier == "com.apple.widget-extension"; @@ -359,12 +375,14 @@ public string InfoPListPath { info_plistpath = value; } } +#endif // !LEGACY_TOOLS // This is just a name for this app to show in log/error messages, etc. public string Name { get { return Path.GetFileNameWithoutExtension (AppDirectory); } } +#if !LEGACY_TOOLS bool? requires_pinvoke_wrappers; public bool RequiresPInvokeWrappers { get { @@ -377,6 +395,7 @@ public bool RequiresPInvokeWrappers { requires_pinvoke_wrappers = value; } } +#endif // !LEGACY_TOOLS #if !LEGACY_TOOLS public bool RequireLinkWithAttributeForObjectiveCClassSearch; @@ -401,9 +420,9 @@ public string PlatformName { } } - public static bool IsUptodate (string source, string target, bool check_contents = false, bool check_stamp = true) + public static bool IsUptodate (IToolLog log, string source, string target, bool check_contents = false, bool check_stamp = true) { - return FileCopier.IsUptodate (source, target, check_contents, check_stamp); + return FileCopier.IsUptodate (log, source, target, check_contents, check_stamp); } public static void RemoveResource (ModuleDefinition module, string name) @@ -475,14 +494,14 @@ public static bool ExtractResource (ModuleDefinition module, string name, string // // If check_stamp is true, the function will use the timestamp of a "target".stamp file // if it's later than the timestamp of the "target" file itself. - public static bool IsUptodate (IEnumerable sources, IEnumerable targets, bool check_stamp = true) + public static bool IsUptodate (IToolLog log, IEnumerable sources, IEnumerable targets, bool check_stamp = true) { - return FileCopier.IsUptodate (sources, targets, check_stamp); + return FileCopier.IsUptodate (log, sources, targets, check_stamp); } - public static void UpdateDirectory (string source, string target) + public static void UpdateDirectory (IToolLog log, string source, string target) { - FileCopier.UpdateDirectory (source, target); + FileCopier.UpdateDirectory (log, source, target); } public void InitializeCommon () @@ -521,13 +540,13 @@ public void InitializeCommon () if (!package_managed_debug_symbols.HasValue) { package_managed_debug_symbols = EnableDebug; } else if (package_managed_debug_symbols.Value && IsLLVM) { - ErrorHelper.Warning (3007, Errors.MX3007); + ErrorHelper.Warning (this, 3007, Errors.MX3007); } Optimizations.Initialize (this, out var messages); - ErrorHelper.Show (messages); - if (Driver.Verbosity > 3) - Driver.Log (4, $"Enabled optimizations: {Optimizations}"); + ErrorHelper.Show (this, messages); + if (this.Verbosity > 3) + this.Log (4, $"Enabled optimizations: {Optimizations}"); } void InitializeDeploymentTarget () @@ -557,7 +576,7 @@ public void RunRegistrar () throw ErrorHelper.CreateError (99, "RegistrarOutputLibrary must be specified."); var RootAssembly = RootAssemblies [0]; var resolvedAssemblies = new Dictionary (); - var resolver = new PlatformResolver () { + var resolver = new PlatformResolver (this) { RootDirectory = Path.GetDirectoryName (RootAssembly), }; resolver.Configure (); @@ -565,7 +584,7 @@ public void RunRegistrar () var ps = new ReaderParameters (); ps.AssemblyResolver = resolver; foreach (var reference in References) { - var r = resolver.Load (reference); + var r = resolver.Load (this, reference); if (r is null) throw ErrorHelper.CreateError (2002, Errors.MT2002, reference); } @@ -580,21 +599,21 @@ public void RunRegistrar () try { AssemblyDefinition lastAssembly = ps.AssemblyResolver.Resolve (AssemblyNameReference.Parse (rootName), new ReaderParameters ()); if (lastAssembly is null) { - ErrorHelper.Warning (7, Errors.MX0007, rootName); + ErrorHelper.Warning (this, 7, Errors.MX0007, rootName); continue; } if (resolvedAssemblies.TryGetValue (rootName, out var previousAssembly)) { if (lastAssembly.MainModule.RuntimeVersion != previousAssembly.MainModule.RuntimeVersion) { - Driver.Log (2, "Attemping to load an assembly another time {0} (previous {1})", lastAssembly.FullName, previousAssembly.FullName); + this.Log (2, "Attemping to load an assembly another time {0} (previous {1})", lastAssembly.FullName, previousAssembly.FullName); } continue; } resolvedAssemblies.Add (rootName, lastAssembly); - Driver.Log (3, "Loaded {0}", lastAssembly.MainModule.FileName); + this.Log (3, "Loaded {0}", lastAssembly.MainModule.FileName); } catch (Exception ex) { - ErrorHelper.Warning (9, ex, Errors.MX0009, $"{rootName}: {ex.Message}"); + ErrorHelper.Warning (this, 9, ex, Errors.MX0009, $"{rootName}: {ex.Message}"); continue; } } @@ -625,6 +644,7 @@ public static bool IsArchEnabled (Abi abi, Abi arch) return (abi & arch) != 0; } +#if !LEGACY_TOOLS public void ValidateAbi () { var validAbis = new List (); @@ -662,6 +682,7 @@ public void ClearAbi () { abi = default; } +#endif // !LEGACY_TOOLS public void ParseAbi (string abi) { @@ -686,6 +707,9 @@ public void ParseAbi (string abi) #if !LEGACY_TOOLS public void ParseRegistrar (string v) { + if (StringUtils.IsNullOrEmpty (v)) + return; + var split = v.Split ('='); var name = split [0]; var value = split.Length > 1 ? split [1] : string.Empty; @@ -727,16 +751,7 @@ public void ParseRegistrar (string v) } #endif // !LEGACY_TOOLS - public static string GetArchitectures (IEnumerable abis) - { - var res = new List (); - - foreach (var abi in abis) - res.Add (abi.AsArchString ()); - - return string.Join (", ", res.ToArray ()); - } - +#if !LEGACY_TOOLS public string MonoGCParams { get { switch (Platform) { @@ -763,15 +778,17 @@ public string MonoGCParams { } } } +#endif // !LEGACY_TOOLS - public bool IsFrameworkAvailableInSimulator (string framework) + public bool IsFrameworkUnavailable (string @namespace) { - if (!Driver.GetFrameworks (this).TryGetValue (framework, out var fw)) - return true; // Unknown framework, assume it's valid for the simulator + if (!Driver.GetFrameworks (this).TryGetValue (@namespace, out var fw)) + return false; // Unknown framework, assume it's valid - return fw.IsFrameworkAvailableInSimulator (this); + return fw.IsFrameworkUnavailable (this); } +#if !LEGACY_TOOLS public static bool TryParseManagedExceptionMode (string value, out MarshalManagedExceptionMode mode) { mode = MarshalManagedExceptionMode.Default; @@ -827,6 +844,7 @@ public static bool TryParseObjectiveCExceptionMode (string value, out MarshalObj } return true; } +#endif // !LEGACY_TOOLS public void SetManagedExceptionMode () { @@ -1161,6 +1179,7 @@ public bool UseDlsym (string assembly) } #endif // !LEGACY_TOOLS +#if !LEGACY_TOOLS public bool VerifyDynamicFramework (string framework_path) { var framework_filename = Path.Combine (framework_path, Path.GetFileNameWithoutExtension (framework_path)); @@ -1173,10 +1192,11 @@ public bool VerifyDynamicFramework (string framework_path) } if (!dynamic) - Driver.Log (1, "The framework {0} is a framework of static libraries, and will not be copied to the app.", framework_path); + this.Log (1, "The framework {0} is a framework of static libraries, and will not be copied to the app.", framework_path); return dynamic; } +#endif // !LEGACY_TOOLS static Application () { @@ -1190,5 +1210,31 @@ public static void SetDefaultHiddenWarnings () ErrorHelper.ParseWarningLevel (ErrorHelper.WarningLevel.Disable, "4189"); // The class '{0}' will not be registered because it has been removed from the {1} SDK. ErrorHelper.ParseWarningLevel (ErrorHelper.WarningLevel.Disable, "4190"); // The class '{0}' will not be registered because the {1} framework has been deprecated from the {2} SDK. } + + public void Log (string message) + { + Console.WriteLine (message); + } + + public void LogError (string message) + { + Console.Error.WriteLine (message); + } + + public void LogError (Exception exception) + { + ErrorHelper.Show (this, exception); + } + + public void LogException (Exception exception) + { + ErrorHelper.Show (this, exception); + } + + int verbosity = Driver.GetDefaultVerbosity (); + public int Verbosity { + get => verbosity; + set => verbosity = value; + } } } diff --git a/tools/common/Assembly.cs b/tools/common/Assembly.cs index 28f4d9a98f7b..6ad8d9141958 100644 --- a/tools/common/Assembly.cs +++ b/tools/common/Assembly.cs @@ -69,7 +69,7 @@ public string FullPath { #if !LEGACY_TOOLS is_framework_assembly = App.Configuration.FrameworkAssemblies.Contains (GetIdentity (full_path)); #else - var real_full_path = Application.GetRealPath (full_path); + var real_full_path = Application.GetRealPath (App, full_path); is_framework_assembly = real_full_path.StartsWith (Path.GetDirectoryName (Path.GetDirectoryName (App.Resolver.FrameworkDirectory))!, StringComparison.Ordinal); #endif } @@ -132,7 +132,7 @@ public void LoadSymbols () } } catch { // do not let stale file crash us - Driver.Log (3, "Invalid debugging symbols for {0} ignored", FullPath); + App.Log (3, "Invalid debugging symbols for {0} ignored", FullPath); } } @@ -155,12 +155,12 @@ public void ExtractNativeLinkInfo () string resourceBundlePath = Path.ChangeExtension (FullPath, ".resources"); if (Directory.Exists (resourceBundlePath)) { - Driver.Log (3, $"Found a binding resource package for the assembly '{FullPath}' in {resourceBundlePath}, so not looking for any libraries embedded in the assembly."); + App.Log (3, $"Found a binding resource package for the assembly '{FullPath}' in {resourceBundlePath}, so not looking for any libraries embedded in the assembly."); return; } var zipPath = resourceBundlePath + ".zip"; if (File.Exists (zipPath)) { - Driver.Log (3, $"Found a binding resource package for the assembly '{FullPath}' in {zipPath}, so not looking for any libraries embedded in the assembly."); + App.Log (3, $"Found a binding resource package for the assembly '{FullPath}' in {zipPath}, so not looking for any libraries embedded in the assembly."); return; } @@ -178,38 +178,6 @@ public void ExtractNativeLinkInfo () } } - IEnumerable ReadManifest (string manifestPath) - { - var document = new XmlDocument (); - document.LoadWithoutNetworkAccess (manifestPath); - - foreach (XmlNode referenceNode in document.GetElementsByTagName ("NativeReference")) { - - var metadata = new NativeReferenceMetadata (); - metadata.LibraryName = Path.Combine (Path.GetDirectoryName (manifestPath)!, referenceNode.Attributes? ["Name"]?.Value!); - - var attributes = new Dictionary (); - foreach (XmlNode attribute in referenceNode.ChildNodes) - attributes [attribute.Name] = attribute.InnerText; - - metadata.ForceLoad = ParseAttributeWithDefault (attributes ["ForceLoad"], false); - metadata.Frameworks = attributes ["Frameworks"]; - metadata.WeakFrameworks = attributes ["WeakFrameworks"]; - metadata.LinkerFlags = attributes ["LinkerFlags"]; - metadata.NeedsGccExceptionHandling = ParseAttributeWithDefault (attributes ["NeedsGccExceptionHandling"], false); - metadata.IsCxx = ParseAttributeWithDefault (attributes ["IsCxx"], false); - metadata.LinkWithSwiftSystemLibraries = ParseAttributeWithDefault (attributes ["LinkWithSwiftSystemLibraries"], false); - metadata.SmartLink = ParseAttributeWithDefault (attributes ["SmartLink"], true); - - // TODO - The project attributes do not contain these bits, is that OK? - //metadata.LinkTarget = (LinkTarget) Enum.Parse (typeof (LinkTarget), attributes ["LinkTarget"]); - //metadata.Dlsym = (DlsymOption)Enum.Parse (typeof (DlsymOption), attributes ["Dlsym"]); - yield return metadata; - } - } - - static bool ParseAttributeWithDefault (string attribute, bool defaultValue) => string.IsNullOrEmpty (attribute) ? defaultValue : bool.Parse (attribute); - void ProcessLinkWithAttributes (AssemblyDefinition assembly) { // @@ -242,12 +210,12 @@ void ProcessLinkWithAttributes (AssemblyDefinition assembly) continue; // Remove the resource from the assembly at a later stage. - if (!string.IsNullOrEmpty (metadata.LibraryName)) + if (!StringUtils.IsNullOrEmpty (metadata.LibraryName)) AddResourceToBeRemoved (metadata.LibraryName); ProcessNativeReferenceOptions (metadata); - if (!string.IsNullOrEmpty (linkWith.LibraryName)) { + if (!StringUtils.IsNullOrEmpty (linkWith.LibraryName)) { switch (Path.GetExtension (linkWith.LibraryName).ToLowerInvariant ()) { case ".framework": { // TryExtractFramework prints a error/warning if something goes wrong, so no need for us to have an error handling path. @@ -274,7 +242,7 @@ void ProcessNativeReferenceOptions (NativeReferenceMetadata metadata) { // We can't add -dead_strip if there are any LinkWith attributes where smart linking is disabled. if (!metadata.SmartLink) { - Driver.Log (3, $"The library '{metadata.LibraryName}', shipped with the assembly '{FullPath}', sets SmartLink=false, which will disable passing -dead_strip to the native linker (and make the app bigger)."); + App.Log (3, $"The library '{metadata.LibraryName}', shipped with the assembly '{FullPath}', sets SmartLink=false, which will disable passing -dead_strip to the native linker (and make the app bigger)."); App.DeadStrip = false; } @@ -282,7 +250,7 @@ void ProcessNativeReferenceOptions (NativeReferenceMetadata metadata) if (metadata.ForceLoad && !(metadata.SmartLink && (App.Registrar == RegistrarMode.Static || App.Registrar == RegistrarMode.ManagedStatic || App.Registrar == RegistrarMode.TrimmableStatic))) ForceLoad = true; - if (!string.IsNullOrEmpty (metadata.LinkerFlags)) { + if (!StringUtils.IsNullOrEmpty (metadata.LinkerFlags)) { if (LinkerFlags is null) LinkerFlags = new List (); if (!StringUtils.TryParseArguments (metadata.LinkerFlags, out var args, out var ex)) @@ -290,7 +258,7 @@ void ProcessNativeReferenceOptions (NativeReferenceMetadata metadata) LinkerFlags.AddRange (args); } - if (!string.IsNullOrEmpty (metadata.Frameworks)) { + if (!StringUtils.IsNullOrEmpty (metadata.Frameworks)) { foreach (var f in metadata.Frameworks.Split (new char [] { ' ' })) { if (Frameworks is null) Frameworks = new HashSet (); @@ -298,7 +266,7 @@ void ProcessNativeReferenceOptions (NativeReferenceMetadata metadata) } } - if (!string.IsNullOrEmpty (metadata.WeakFrameworks)) { + if (!StringUtils.IsNullOrEmpty (metadata.WeakFrameworks)) { foreach (var f in metadata.WeakFrameworks.Split (new char [] { ' ' })) { if (WeakFrameworks is null) WeakFrameworks = new HashSet (); @@ -322,23 +290,23 @@ bool TryExtractNativeLibrary (AssemblyDefinition assembly, NativeReferenceMetada library = null; return false; } - var path = Path.Combine (App.Cache.Location, metadata.LibraryName); + var path = Path.Combine (App.Cache.GetLocation (App), metadata.LibraryName); library = null; - if (!Application.IsUptodate (FullPath, path)) { + if (!Application.IsUptodate (App, FullPath, path)) { if (!Application.ExtractResource (assembly.MainModule, metadata.LibraryName, path, false)) { - ErrorHelper.Warning (1308, Errors.MX1308 /* Could not extract the native library '{0}' from the assembly '{1}', because it doesn't contain the resource '{2}'. */, metadata.LibraryName, FullPath, metadata.LibraryName); + ErrorHelper.Warning (App, 1308, Errors.MX1308 /* Could not extract the native library '{0}' from the assembly '{1}', because it doesn't contain the resource '{2}'. */, metadata.LibraryName, FullPath, metadata.LibraryName); return false; } - Driver.Log (3, "Extracted third-party binding '{0}' from '{1}' to '{2}'", metadata.LibraryName, FullPath, path); + App.Log (3, "Extracted third-party binding '{0}' from '{1}' to '{2}'", metadata.LibraryName, FullPath, path); LogNativeReference (metadata); } else { - Driver.Log (3, "Target '{0}' is up-to-date.", path); + App.Log (3, "Target '{0}' is up-to-date.", path); } if (!File.Exists (path)) - ErrorHelper.Warning (1302, Errors.MT1302, metadata.LibraryName, path); + ErrorHelper.Warning (App, 1302, Errors.MT1302, metadata.LibraryName, path); library = path; return true; @@ -350,39 +318,39 @@ bool TryExtractFramework (AssemblyDefinition assembly, NativeReferenceMetadata m framework = null; return false; } - var path = Path.Combine (App.Cache.Location, metadata.LibraryName); + var path = Path.Combine (App.Cache.GetLocation (App), metadata.LibraryName); var zipPath = path + ".zip"; framework = null; - if (!Application.IsUptodate (FullPath, zipPath)) { + if (!Application.IsUptodate (App, FullPath, zipPath)) { if (!Application.ExtractResource (assembly.MainModule, metadata.LibraryName, zipPath, false)) { - ErrorHelper.Warning (1307, Errors.MX1307 /* Could not extract the native framework '{0}' from the assembly '{1}', because it doesn't contain the resource '{2}'. */, metadata.LibraryName, FullPath, metadata.LibraryName); + ErrorHelper.Warning (App, 1307, Errors.MX1307 /* Could not extract the native framework '{0}' from the assembly '{1}', because it doesn't contain the resource '{2}'. */, metadata.LibraryName, FullPath, metadata.LibraryName); return false; } - Driver.Log (3, "Extracted third-party framework '{0}' from '{1}' to '{2}'", metadata.LibraryName, FullPath, zipPath); + App.Log (3, "Extracted third-party framework '{0}' from '{1}' to '{2}'", metadata.LibraryName, FullPath, zipPath); LogNativeReference (metadata); } else { - Driver.Log (3, "Target '{0}' is up-to-date.", path); + App.Log (3, "Target '{0}' is up-to-date.", path); } if (!File.Exists (zipPath)) { - ErrorHelper.Warning (1302, Errors.MT1302, metadata.LibraryName, FullPath); + ErrorHelper.Warning (App, 1302, Errors.MT1302, metadata.LibraryName, FullPath); if (assembly.MainModule.HasResources) { - Driver.Log (3, $"The assembly {FullPath} has {assembly.MainModule.Resources.Count} resources:"); + App.Log (3, $"The assembly {FullPath} has {assembly.MainModule.Resources.Count} resources:"); foreach (var res in assembly.MainModule.Resources) { - Driver.Log (3, $" {res.ResourceType}: {res.Name}"); + App.Log (3, $" {res.ResourceType}: {res.Name}"); } } else { - Driver.Log (3, $"The assembly {FullPath} does not have any resources."); + App.Log (3, $"The assembly {FullPath} does not have any resources."); } } else { if (!Directory.Exists (path)) Directory.CreateDirectory (path); - if (Driver.RunCommand ("/usr/bin/unzip", "-u", "-o", "-d", path, zipPath) != 0) + if (Driver.RunCommand (App, "/usr/bin/unzip", "-u", "-o", "-d", path, zipPath) != 0) throw ErrorHelper.CreateError (1303, Errors.MT1303, metadata.LibraryName, zipPath); } @@ -390,19 +358,19 @@ bool TryExtractFramework (AssemblyDefinition assembly, NativeReferenceMetadata m return true; } - static void LogNativeReference (NativeReferenceMetadata metadata) + void LogNativeReference (NativeReferenceMetadata metadata) { - Driver.Log (3, " LibraryName: {0}", metadata.LibraryName); - Driver.Log (3, " From: {0}", metadata.Attribute is not null ? "LinkWith" : "Binding Manifest"); - Driver.Log (3, " ForceLoad: {0}", metadata.ForceLoad); - Driver.Log (3, " Frameworks: {0}", metadata.Frameworks); - Driver.Log (3, " IsCxx: {0}", metadata.IsCxx); - Driver.Log (3, " LinkWithSwiftSystemLibraries: {0}", metadata.LinkWithSwiftSystemLibraries); - Driver.Log (3, " LinkerFlags: {0}", metadata.LinkerFlags); - Driver.Log (3, " LinkTarget: {0}", metadata.LinkTarget); - Driver.Log (3, " NeedsGccExceptionHandling: {0}", metadata.NeedsGccExceptionHandling); - Driver.Log (3, " SmartLink: {0}", metadata.SmartLink); - Driver.Log (3, " WeakFrameworks: {0}", metadata.WeakFrameworks); + App.Log (3, " LibraryName: {0}", metadata.LibraryName); + App.Log (3, " From: {0}", metadata.Attribute is not null ? "LinkWith" : "Binding Manifest"); + App.Log (3, " ForceLoad: {0}", metadata.ForceLoad); + App.Log (3, " Frameworks: {0}", metadata.Frameworks); + App.Log (3, " IsCxx: {0}", metadata.IsCxx); + App.Log (3, " LinkWithSwiftSystemLibraries: {0}", metadata.LinkWithSwiftSystemLibraries); + App.Log (3, " LinkerFlags: {0}", metadata.LinkerFlags); + App.Log (3, " LinkTarget: {0}", metadata.LinkTarget); + App.Log (3, " NeedsGccExceptionHandling: {0}", metadata.NeedsGccExceptionHandling); + App.Log (3, " SmartLink: {0}", metadata.SmartLink); + App.Log (3, " WeakFrameworks: {0}", metadata.WeakFrameworks); } public static LinkWithAttribute GetLinkWithAttribute (CustomAttribute attr) @@ -469,13 +437,13 @@ public static LinkWithAttribute GetLinkWithAttribute (CustomAttribute attr) void AddFramework (string file) { if (Driver.GetFrameworks (App).TryGetValue (file, out var framework)) { - if (framework.Unavailable) { - ErrorHelper.Warning (182, Errors.MX0182 /* Not linking with the framework {0} (referenced by a module reference in {1}) because it's not available on the current platform ({2}). */, framework.Name, FileName, App.PlatformName); + if (framework.IsFrameworkUnavailable (App)) { + ErrorHelper.Warning (App, 182, Errors.MX0182 /* Not linking with the framework {0} (referenced by a module reference in {1}) because it's not available on the current platform ({2}). */, framework.Name, FileName, App.PlatformName); return; } if (framework.Version > App.SdkVersion) { - ErrorHelper.Warning (135, Errors.MX0135, file, FileName, App.PlatformName, framework.Version, App.SdkVersion); + ErrorHelper.Warning (App, 135, Errors.MX0135, file, FileName, App.PlatformName, framework.Version, App.SdkVersion); return; } } @@ -483,10 +451,10 @@ void AddFramework (string file) var strong = (framework is null) || (App.DeploymentTarget >= (App.IsSimulatorBuild ? framework.VersionAvailableInSimulator ?? framework.Version : framework.Version)); if (strong) { if (Frameworks.Add (file)) - Driver.Log (3, "Linking with the framework {0} because it's referenced by a module reference in {1}", file, FileName); + App.Log (3, "Linking with the framework {0} because it's referenced by a module reference in {1}", file, FileName); } else { if (WeakFrameworks.Add (file)) - Driver.Log (3, "Linking (weakly) with the framework {0} because it's referenced by a module reference in {1}", file, FileName); + App.Log (3, "Linking (weakly) with the framework {0} because it's referenced by a module reference in {1}", file, FileName); } } @@ -522,8 +490,8 @@ public void ComputeLinkerFlags () string file = Path.GetFileNameWithoutExtension (name); - if (App.IsSimulatorBuild && !App.IsFrameworkAvailableInSimulator (file)) { - Driver.Log (3, "Not linking with {0} (referenced by a module reference in {1}) because it's not available in the simulator.", file, FileName); + if (App.IsFrameworkUnavailable (file)) { + App.Log (3, "Not linking with {0} (referenced by a module reference in {1}) because it's not available in the current SDK.", file, FileName); continue; } @@ -542,12 +510,12 @@ public void ComputeLinkerFlags () break; case "sqlite3": LinkerFlags.Add ("-lsqlite3"); - Driver.Log (3, "Linking with {0} because it's referenced by a module reference in {1}", file, FileName); + App.Log (3, "Linking with {0} because it's referenced by a module reference in {1}", file, FileName); break; case "libsqlite3": // remove lib prefix LinkerFlags.Add ("-l" + file.Substring (3)); - Driver.Log (3, "Linking with {0} because it's referenced by a module reference in {1}", file, FileName); + App.Log (3, "Linking with {0} because it's referenced by a module reference in {1}", file, FileName); break; case "libcompression": LinkerFlags.Add (GetCompressionLinkingFlag ()); @@ -556,22 +524,22 @@ public void ComputeLinkerFlags () case "libGLESv2": // special case for OpenGLES.framework if (Frameworks.Add ("OpenGLES")) - Driver.Log (3, "Linking with the framework OpenGLES because {0} is referenced by a module reference in {1}", file, FileName); + App.Log (3, "Linking with the framework OpenGLES because {0} is referenced by a module reference in {1}", file, FileName); break; case "vImage": case "vecLib": // sub-frameworks if (Frameworks.Add ("Accelerate")) - Driver.Log (3, "Linking with the framework Accelerate because {0} is referenced by a module reference in {1}", file, FileName); + App.Log (3, "Linking with the framework Accelerate because {0} is referenced by a module reference in {1}", file, FileName); break; case "openal32": if (Frameworks.Add ("OpenAL")) - Driver.Log (3, "Linking with the framework OpenAL because {0} is referenced by a module reference in {1}", file, FileName); + App.Log (3, "Linking with the framework OpenAL because {0} is referenced by a module reference in {1}", file, FileName); break; #if !LEGACY_TOOLS case "Carbon": if (App.Platform != ApplePlatform.MacOSX) { - Driver.Log (3, $"Not linking with the framework {file} (referenced by a module reference in {FileName}) because it doesn't exist on the target platform."); + App.Log (3, $"Not linking with the framework {file} (referenced by a module reference in {FileName}) because it doesn't exist on the target platform."); break; } break; @@ -585,13 +553,13 @@ public void ComputeLinkerFlags () // CoreServices has multiple sub-frameworks that can be used by customer code if (path.StartsWith ("/System/Library/Frameworks/CoreServices.framework/", StringComparison.Ordinal)) { if (Frameworks.Add ("CoreServices")) - Driver.Log (3, "Linking with the framework CoreServices because {0} is referenced by a module reference in {1}", file, FileName); + App.Log (3, "Linking with the framework CoreServices because {0} is referenced by a module reference in {1}", file, FileName); break; } // ApplicationServices has multiple sub-frameworks that can be used by customer code if (path.StartsWith ("/System/Library/Frameworks/ApplicationServices.framework/", StringComparison.Ordinal)) { if (Frameworks.Add ("ApplicationServices")) - Driver.Log (3, "Linking with the framework ApplicationServices because {0} is referenced by a module reference in {1}", file, FileName); + App.Log (3, "Linking with the framework ApplicationServices because {0} is referenced by a module reference in {1}", file, FileName); break; } } @@ -604,7 +572,7 @@ public void ComputeLinkerFlags () if (UnresolvedModuleReferences is null) UnresolvedModuleReferences = new HashSet (); UnresolvedModuleReferences.Add (mr); - Driver.Log (3, "Could not resolve the module reference {0} in {1}", file, FileName); + App.Log (3, "Could not resolve the module reference {0} in {1}", file, FileName); } break; } @@ -730,14 +698,14 @@ public void Update (Application app, IEnumerable assemblies) // new assembly var asm = new Assembly (app, assembly); Add (asm); - Driver.Log (1, "The linker added the assembly '{0}' to '{1}' to satisfy a reference.", asm.Identity, app.Name); + app.Log (1, "The linker added the assembly '{0}' to '{1}' to satisfy a reference.", asm.Identity, app.Name); } else { this [identity].AssemblyDefinition = assembly; } } foreach (var removed in current) { - Driver.Log (1, "The linker removed the assembly '{0}' from '{1}' since there is no more reference to it.", this [removed].Identity, app.Name); + app.Log (1, "The linker removed the assembly '{0}' from '{1}' since there is no more reference to it.", this [removed].Identity, app.Name); Remove (removed); } } diff --git a/tools/common/CompilerFlags.cs b/tools/common/CompilerFlags.cs index 1138c4ca917f..1181f05a6943 100644 --- a/tools/common/CompilerFlags.cs +++ b/tools/common/CompilerFlags.cs @@ -55,7 +55,7 @@ public void ReferenceSymbols (IEnumerable symbols, Abi abi) foreach (var symbol in symbols) { if (symbol.ValidAbis.HasValue && (symbol.ValidAbis.Value & abi) == 0) continue; - UnresolvedSymbols.Add (symbol.Prefix + symbol.Name); + UnresolvedSymbols.Add (Symbol.Prefix + symbol.Name); } } diff --git a/tools/common/CoreResolver.cs b/tools/common/CoreResolver.cs index 458da5cf086c..b35f575c9fc1 100644 --- a/tools/common/CoreResolver.cs +++ b/tools/common/CoreResolver.cs @@ -60,7 +60,7 @@ protected ReaderParameters CreateDefaultReaderParameters (string path) return parameters; } - public virtual AssemblyDefinition? Load (string fileName) + public virtual AssemblyDefinition? Load (IToolLog log, string fileName) { if (!File.Exists (fileName)) return null; @@ -70,7 +70,7 @@ protected ReaderParameters CreateDefaultReaderParameters (string path) return assembly; try { - fileName = Application.GetRealPath (fileName); + fileName = Application.GetRealPath (log, fileName); // Check the architecture-specific directory if (Path.GetDirectoryName (fileName) == FrameworkDirectory && !string.IsNullOrEmpty (ArchDirectory)) { @@ -89,14 +89,14 @@ protected ReaderParameters CreateDefaultReaderParameters (string path) // Warn about this. var pdb = Path.ChangeExtension (fileName, "pdb"); if (File.Exists (pdb)) - ErrorHelper.Show (ErrorHelper.CreateWarning (178, Errors.MX0178, fileName)); + ErrorHelper.Show (log, ErrorHelper.CreateWarning (178, Errors.MX0178, fileName)); } // Don't load native .pdb symbols, because we won't be able to write them back out again (so just drop them) if (assembly.MainModule?.SymbolReader?.GetType ()?.FullName == "Mono.Cecil.Pdb.NativePdbReader") { parameters.ReadSymbols = false; parameters.SymbolReaderProvider = null; assembly = ModuleDefinition.ReadModule (fileName, parameters).Assembly; - ErrorHelper.Show (ErrorHelper.CreateWarning (178, Errors.MX0178, fileName)); + ErrorHelper.Show (log, ErrorHelper.CreateWarning (178, Errors.MX0178, fileName)); } } catch (IOException ex) when (ex.GetType ().FullName == "Microsoft.Cci.Pdb.PdbException") { // Microsoft.Cci.Pdb.PdbException is not public, so we have to check the runtime type :/ symbolLoadFailure = true; @@ -108,7 +108,7 @@ protected ReaderParameters CreateDefaultReaderParameters (string path) parameters.SymbolReaderProvider = null; assembly = ModuleDefinition.ReadModule (fileName, parameters).Assembly; // only report the warning (on symbols) if we can actually load the assembly itself (otherwise it's more confusing than helpful) - ErrorHelper.Show (ErrorHelper.CreateWarning (129, Errors.MX0129, fileName)); + ErrorHelper.Show (log, ErrorHelper.CreateWarning (129, Errors.MX0129, fileName)); } } catch (Exception e) { throw new ProductException (9, true, e, Errors.MX0009, fileName); @@ -126,23 +126,23 @@ public AssemblyDefinition CacheAssembly (AssemblyDefinition assembly) return assembly; } - protected AssemblyDefinition? SearchDirectory (string name, string directory, string extension = ".dll") + protected AssemblyDefinition? SearchDirectory (IToolLog log, string name, string directory, string extension = ".dll") { if (!Directory.Exists (directory)) return null; - var file = DirectoryGetFile (directory, name + extension); + var file = DirectoryGetFile (log, directory, name + extension); if (file.Length > 0) - return Load (file); + return Load (log, file); return null; } - static string DirectoryGetFile (string directory, string file) + static string DirectoryGetFile (IToolLog log, string directory, string file) { var files = Directory.GetFiles (directory, file); if (files is not null && files.Length > 0) { if (files.Length > 1) { - ErrorHelper.Warning (133, Errors.MX0133, file, Environment.NewLine, string.Join ("\n", files)); + ErrorHelper.Warning (log, 133, Errors.MX0133, file, Environment.NewLine, string.Join ("\n", files)); } return files [0]; } diff --git a/tools/common/DerivedLinkContext.cs b/tools/common/DerivedLinkContext.cs index 8e679a69de81..0f639be2e7b5 100644 --- a/tools/common/DerivedLinkContext.cs +++ b/tools/common/DerivedLinkContext.cs @@ -9,6 +9,7 @@ using Mono.Tuner; using Xamarin.Bundler; using Xamarin.Linker; +using Xamarin.Utils; #if !LEGACY_TOOLS using LinkContext = Xamarin.Bundler.DotNetLinkContext; @@ -40,6 +41,9 @@ public class DerivedLinkContext : LinkContext { // true/false = corresponding constant value Dictionary? isdirectbinding_value; + // A map from Objective-C class name to C# type + Dictionary? objectiveCTypeInfo; + // Store interfaces the linker has linked away so that the static registrar can access them. public Dictionary> ProtocolImplementations { get; private set; } = new Dictionary> (); // Store types the linker has linked away so that the static registrar can access them. @@ -72,6 +76,7 @@ public AssemblyDefinition Corlib { return corlib; } } + public HashSet? CachedIsNSObject { get { return cached_isnsobject; } set { cached_isnsobject = value; } @@ -82,6 +87,11 @@ public HashSet? CachedIsNSObject { set { isdirectbinding_value = value; } } + public Dictionary? ObjectiveCTypeInfo { + get { return objectiveCTypeInfo; } + set { objectiveCTypeInfo = value; } + } + public IList DataContract { get { return srs_data_contract; @@ -236,6 +246,101 @@ public void AddLinkedAwayType (TypeDefinition td) } #if !LEGACY_TOOLS + public bool HasAvailabilityAttributesShowingUnavailableInSimulator (ICustomAttributeProvider? provider, MethodDefinition? methodForErrorReporting = null) + { + if (provider is null) + return false; + + if (!App.IsSimulatorBuild) { + LinkerConfiguration.Report (LinkerConfiguration.Context, ErrorHelper.CreateError (99, "HasAvailabilityAttributesShowingUnavailableInSimulator should not be called when not building for the simulator. Please file an issue at https://github.com/dotnet/macios/issues.")); + return false; + } + + if (!provider.HasCustomAttributes) + return false; // no attributes to say otherwise, so available + + string platformName; + + switch (App.Platform) { + case ApplePlatform.iOS: + platformName = "ios"; + break; + case ApplePlatform.TVOS: + platformName = "tvos"; + break; + default: + LinkerConfiguration.Report (LinkerConfiguration.Context, ErrorHelper.CreateWarning (App, 99, methodForErrorReporting, "Unexpected platform '{0}'. Please file an issue at https://github.com/dotnet/macios/issues.", App.Platform)); + return false; + } + + // Pass 1: check for any matching UnsupportedSimulator attribute — if found, it's unavailable. + var hasUnsupported = false; + foreach (var attrib in provider.CustomAttributes) { + if (!attrib.AttributeType.Is ("ObjCRuntime", "UnsupportedSimulatorAttribute")) + continue; + if (attrib.ConstructorArguments.Count == 1 && attrib.ConstructorArguments [0].Value is string unsupportedPlatform) { + if (string.Equals (unsupportedPlatform, platformName, StringComparison.OrdinalIgnoreCase)) + hasUnsupported = true; + } else { + LinkerConfiguration.Report (LinkerConfiguration.Context, ErrorHelper.CreateWarning (App, 2258, methodForErrorReporting, Errors.MX2258, provider.AsString (), attrib.RenderAttribute ())); + } + } + + // Pass 2: check for any matching SupportedSimulator attributes — evaluate as OR across versions. + var hasSupported = false; + var supportedCount = 0; + var isAvailable = false; + foreach (var attrib in provider.CustomAttributes) { + if (!attrib.AttributeType.Is ("ObjCRuntime", "SupportedSimulatorAttribute")) + continue; + if (attrib.ConstructorArguments.Count == 1 && attrib.ConstructorArguments [0].Value is string supportedPlatform) { + if (!supportedPlatform.StartsWith (platformName, StringComparison.OrdinalIgnoreCase)) + continue; + + hasSupported = true; + supportedCount++; + var osVersion = supportedPlatform.Substring (platformName.Length); + if (string.IsNullOrEmpty (osVersion)) { + // no version constraint: available in the simulator + isAvailable = true; + } else if (Version.TryParse (osVersion, out var version)) { + var simulatorVersion = App.DeploymentTarget; + if (simulatorVersion is null) { + LinkerConfiguration.Report (LinkerConfiguration.Context, ErrorHelper.CreateWarning (App, 99, methodForErrorReporting, "No deployment target available. Please file an issue at https://github.com/dotnet/macios/issues.")); + continue; + } + if (simulatorVersion >= version) + isAvailable = true; + } else { + LinkerConfiguration.Report (LinkerConfiguration.Context, ErrorHelper.CreateWarning (App, 2259, methodForErrorReporting, Errors.MX2259, provider.AsString (), attrib.RenderAttribute ())); + } + } else { + LinkerConfiguration.Report (LinkerConfiguration.Context, ErrorHelper.CreateWarning (App, 2258, methodForErrorReporting, Errors.MX2258, provider.AsString (), attrib.RenderAttribute ())); + } + } + + // Conflicting attributes: both Supported and Unsupported for the same platform + if (hasUnsupported && hasSupported) { + LinkerConfiguration.Report (LinkerConfiguration.Context, ErrorHelper.CreateError (App, 2260, methodForErrorReporting, Errors.MX2260, provider.AsString (), platformName)); + return true; // treat as unavailable + } + + // Multiple SupportedSimulator attributes for the same platform + if (supportedCount > 1) { + LinkerConfiguration.Report (LinkerConfiguration.Context, ErrorHelper.CreateError (App, 2261, methodForErrorReporting, Errors.MX2261, provider.AsString (), platformName)); + return true; // treat as unavailable + } + + if (hasUnsupported) + return true; + + if (hasSupported) + return !isAvailable; + + // No matching attributes: assume available + return false; + } + class AttributeStorage : ICustomAttribute { public CustomAttribute Attribute { get; } public TypeReference AttributeType { get; set; } diff --git a/tools/common/Driver.cs b/tools/common/Driver.cs index 0e8bf7f3621a..c04f81cd0221 100644 --- a/tools/common/Driver.cs +++ b/tools/common/Driver.cs @@ -27,12 +27,12 @@ public static int Main (string [] args) { try { Console.OutputEncoding = new UTF8Encoding (false, false); - SetCurrentLanguage (); + SetCurrentLanguage (ConsoleLog.Instance); return Main2 (args); } catch (Exception e) { - ErrorHelper.Show (e); + ErrorHelper.Show (ConsoleLog.Instance, e); } finally { - Watch ("Total time", 0); + Watch (ConsoleLog.Instance, "Total time", 0); } return 0; } @@ -40,8 +40,8 @@ public static int Main (string [] args) // Returns true if the process should exit (with a 0 exit code; failures are propagated using exceptions) static void ParseOptions (Application app, Mono.Options.OptionSet options, string [] args) { - options.Add ("v|verbose", "Specify how verbose the output should be. This can be passed multiple times to increase the verbosity.", v => Verbosity++); - options.Add ("q|quiet", "Specify how quiet the output should be. This can be passed multiple times to increase the silence.", v => Verbosity--); + options.Add ("v|verbose", "Specify how verbose the output should be. This can be passed multiple times to increase the verbosity.", v => app.Verbosity++); + options.Add ("q|quiet", "Specify how quiet the output should be. This can be passed multiple times to increase the silence.", v => app.Verbosity--); options.Add ("reference=", "Add an assembly to be processed.", v => app.References.Add (v)); options.Add ("sdkroot=", "Specify the location of Apple SDKs, default to 'xcode-select' value.", v => sdk_root = v); options.Add ("sdk=", "Specifies the SDK version to compile against (version, for example \"10.9\"). For Mac Catalyst, this is the macOS version of the SDK.", v => { @@ -69,6 +69,11 @@ static void ParseOptions (Application app, Mono.Options.OptionSet options, strin options.Add ("rid=", "The runtime identifier we're building for", v => { app.RuntimeIdentifier = v; }); + options.Add ("xcode-version=", "The Xcode version we're building with", v => { + if (!Version.TryParse (v, out var xcodeVersion)) + throw ErrorHelper.CreateError (26, Errors.MX0026, $"xcode-version:{v}", "Expected a valid version string."); + Driver.XcodeVersion = xcodeVersion; + }); try { app.RootAssemblies.AddRange (options.Parse (args)); @@ -80,17 +85,7 @@ static void ParseOptions (Application app, Mono.Options.OptionSet options, strin } #endif // !LEGACY_TOOLS - public static int Verbosity { - get { return ErrorHelper.Verbosity; } - set { ErrorHelper.Verbosity = value; } - } - - static Driver () - { - Verbosity = GetDefaultVerbosity (); - } - - static int GetDefaultVerbosity () + public static int GetDefaultVerbosity () { var v = 0; var fn = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.UserProfile), $".{NAME}-verbosity"); @@ -102,35 +97,6 @@ static int GetDefaultVerbosity () return v; } - public static void Log (string value) - { - Log (0, value); - } - - public static void Log (string format, params object? [] args) - { - Log (0, format, args); - } - - public static void Log (int min_verbosity, string value) - { - if (min_verbosity > Verbosity) - return; - - Console.WriteLine (value); - } - - public static void Log (int min_verbosity, string format, params object? [] args) - { - if (min_verbosity > Verbosity) - return; - - if (args.Length > 0) - Console.WriteLine (format, args); - else - Console.WriteLine (format); - } - static TargetFramework targetFramework; public static TargetFramework TargetFramework { @@ -144,7 +110,7 @@ static void FileMove (string source, string target) File.Move (source, target); } - static void MoveIfDifferent (string path, string tmp, bool use_stamp = false) + static void MoveIfDifferent (IToolLog log, string path, string tmp, bool use_stamp = false) { // Don't read the entire file into memory, it can be quite big in certain cases. @@ -153,10 +119,10 @@ static void MoveIfDifferent (string path, string tmp, bool use_stamp = false) using (var fs1 = new FileStream (path, FileMode.Open, FileAccess.Read)) { using (var fs2 = new FileStream (tmp, FileMode.Open, FileAccess.Read)) { if (fs1.Length != fs2.Length) { - Log (3, "New file '{0}' has different length, writing new file.", path); + log.Log (3, "New file '{0}' has different length, writing new file.", path); move = true; } else { - move = !Cache.CompareStreams (fs1, fs2); + move = !Cache.CompareStreams (log, fs1, fs2); } } } @@ -164,13 +130,13 @@ static void MoveIfDifferent (string path, string tmp, bool use_stamp = false) if (move) { FileMove (tmp, path); } else { - Log (3, "Target {0} is up-to-date.", path); + log.Log (3, "Target {0} is up-to-date.", path); if (use_stamp) - Driver.Touch (path + ".stamp"); + Driver.Touch (log, path + ".stamp"); } } - public static void WriteIfDifferent (string path, string contents, bool use_stamp = false) + public static void WriteIfDifferent (IToolLog log, string path, string contents, bool use_stamp = false) { var tmp = path + ".tmp"; @@ -180,36 +146,36 @@ public static void WriteIfDifferent (string path, string contents, bool use_stam if (!string.IsNullOrEmpty (dir)) Directory.CreateDirectory (dir); File.WriteAllText (path, contents); - Log (3, "File '{0}' does not exist, creating it.", path); + log.Log (3, "File '{0}' does not exist, creating it.", path); return; } File.WriteAllText (tmp, contents); - MoveIfDifferent (path, tmp, use_stamp); + MoveIfDifferent (log, path, tmp, use_stamp); } catch (Exception e) { File.WriteAllText (path, contents); - ErrorHelper.Warning (1014, e, Errors.MT1014, path, e.Message); + ErrorHelper.Warning (log, 1014, e, Errors.MT1014, path, e.Message); } finally { File.Delete (tmp); } } - public static void WriteIfDifferent (string path, byte [] contents, bool use_stamp = false) + public static void WriteIfDifferent (IToolLog log, string path, byte [] contents, bool use_stamp = false) { var tmp = path + ".tmp"; try { if (!File.Exists (path)) { File.WriteAllBytes (path, contents); - Log (3, "File '{0}' does not exist, creating it.", path); + log.Log (3, "File '{0}' does not exist, creating it.", path); return; } File.WriteAllBytes (tmp, contents); - MoveIfDifferent (path, tmp, use_stamp); + MoveIfDifferent (log, path, tmp, use_stamp); } catch (Exception e) { File.WriteAllBytes (path, contents); - ErrorHelper.Warning (1014, e, Errors.MT1014, path, e.Message); + ErrorHelper.Warning (log, 1014, e, Errors.MT1014, path, e.Message); } finally { File.Delete (tmp); } @@ -230,11 +196,16 @@ public static string? XcodeProductVersion { static Version? xcode_version; public static Version XcodeVersion { get { - return xcode_version!; + if (xcode_version is null) + throw ErrorHelper.CreateError (99, Errors.MX0099, "The Xcode version has not been configured. Pass --xcode-version or configure an Xcode installation."); + return xcode_version; + } + set { + xcode_version = value; } } - static void SetCurrentLanguage () + static void SetCurrentLanguage (IToolLog log) { // There's no way to change the current culture from the command-line // without changing the system settings, so honor LANG if set. @@ -259,14 +230,14 @@ static void SetCurrentLanguage () var culture = CultureInfo.GetCultureInfo (lang); if (culture is not null) { CultureInfo.DefaultThreadCurrentCulture = culture; - Log (2, $"The current language was set to '{culture.DisplayName}' according to the LANG environment variable (LANG={lang_variable})."); + log.Log (2, $"The current language was set to '{culture.DisplayName}' according to the LANG environment variable (LANG={lang_variable})."); } } catch (Exception e) { - ErrorHelper.Warning (124, e, Errors.MT0124, lang, lang_variable, e.Message); + ErrorHelper.Warning (log, 124, e, Errors.MT0124, lang, lang_variable, e.Message); } } - public static void Touch (IEnumerable filenames, DateTime? timestamp = null) + public static void Touch (IToolLog log, IEnumerable filenames, DateTime? timestamp = null) { if (timestamp is null) timestamp = DateTime.Now; @@ -280,14 +251,14 @@ public static void Touch (IEnumerable filenames, DateTime? timestamp = n } fi.LastWriteTime = timestamp.Value; } catch (Exception e) { - ErrorHelper.Warning (128, Errors.MT0128, filename, e.Message); + ErrorHelper.Warning (log, 128, Errors.MT0128, filename, e.Message); } } } - public static void Touch (params string [] filenames) + public static void Touch (IToolLog log, params string [] filenames) { - Touch ((IEnumerable) filenames); + Touch (log, (IEnumerable) filenames); } static int watch_level; @@ -304,36 +275,34 @@ public static int WatchLevel { } } - public static void Watch (string msg, int level) + public static void Watch (IToolLog log, string msg, int level) { if ((watch is null) || (level > WatchLevel)) return; - for (int i = 0; i < level; i++) - Console.Write ("!"); - Console.WriteLine ("Timestamp {0}: {1} ms", msg, watch.ElapsedMilliseconds); + log.Log ($"{new string ('!', level)}Timestamp {msg}: {watch.ElapsedMilliseconds} ms"); } internal static PDictionary? FromPList (string name) { if (!File.Exists (name)) throw ErrorHelper.CreateError (24, Errors.MT0024, name); - return PDictionary.FromFile (name); + return PDictionary.OpenFile (name); } const string XcodeDefault = "/Applications/Xcode.app"; - static string? FindSystemXcode () + static string? FindSystemXcode (IToolLog log) { var output = new StringBuilder (); - if (Driver.RunCommand ("xcode-select", new [] { "-p" }, output: output) != 0) { - ErrorHelper.Warning (59, Errors.MX0059, output.ToString ()); + if (Driver.RunCommand (log, "xcode-select", new [] { "-p" }, output: output) != 0) { + ErrorHelper.Warning (log, 59, Errors.MX0059, output.ToString ()); return null; } return output.ToString ().Trim (); } static string? sdk_root; - static string? developer_directory; + static string? developer_directory = null; public static string? SdkRoot { get => sdk_root; @@ -417,31 +386,31 @@ public static string GetProductAssembly (Application app) public static void ValidateXcode (Application app, bool accept_any_xcode_version, bool warn_if_not_found) { if (sdk_root is null) { - sdk_root = FindSystemXcode (); + sdk_root = FindSystemXcode (app); if (sdk_root is null) { // FindSystemXcode showed a warning in this case. In particular do not use 'string.IsNullOrEmpty' here, // because FindSystemXcode may return an empty string (with no warning printed) if the xcode-select command // succeeds, but returns nothing. sdk_root = null; } else if (!Directory.Exists (sdk_root)) { - ErrorHelper.Warning (60, Errors.MX0060, sdk_root); + ErrorHelper.Warning (app, 60, Errors.MX0060, sdk_root); sdk_root = null; } else { if (!accept_any_xcode_version) - ErrorHelper.Warning (61, Errors.MT0061, sdk_root); + ErrorHelper.Warning (app, 61, Errors.MT0061, sdk_root); } if (sdk_root is null) { sdk_root = XcodeDefault; if (!Directory.Exists (sdk_root)) { if (warn_if_not_found) { // mmp: and now we give up, but don't throw like mtouch, because we don't want to change behavior (this sometimes worked it appears) - ErrorHelper.Warning (56, Errors.MX0056); + ErrorHelper.Warning (app, 56, Errors.MX0056); return; // Can't validate the version below if we can't even find Xcode... } throw ErrorHelper.CreateError (56, Errors.MX0056); } - ErrorHelper.Warning (62, Errors.MT0062, sdk_root); + ErrorHelper.Warning (app, 62, Errors.MT0062, sdk_root); } } else if (!Directory.Exists (sdk_root)) { throw ErrorHelper.CreateError (55, Errors.MT0055, sdk_root); @@ -471,7 +440,7 @@ public static void ValidateXcode (Application app, bool accept_any_xcode_version throw ErrorHelper.CreateError (58, Errors.MT0058, Path.GetDirectoryName (Path.GetDirectoryName (DeveloperDirectory)), plist_path); } - Driver.Log (1, "Using Xcode {0} ({2}) found in {1}", XcodeVersion, sdk_root, XcodeProductVersion); + app.Log (1, "Using Xcode {0} ({2}) found in {1}", XcodeVersion, sdk_root, XcodeProductVersion); } internal static bool TryParseBool (string value, out bool result) @@ -507,6 +476,7 @@ internal static bool ParseBool (string value, string name, bool show_error = tru return result; } +#if !LEGACY_TOOLS static readonly Dictionary tools = new Dictionary (); static string FindTool (Application app, string tool) { @@ -596,7 +566,7 @@ static bool XcrunFind (Application app, ApplePlatform platform, bool is_simulato // We also want to print out what happened if something went wrong, and in that case we don't want stdout // and stderr captured separately, because related lines could end up printed far from eachother in time, // and that's confusing. So capture stdout and stderr by themselves, and also capture both together. - int ret = RunCommand ("xcrun", args, env, + int ret = RunCommand (app, "xcrun", args, env, (v) => { lock (both) { both.AppendLine (v); @@ -613,11 +583,11 @@ static bool XcrunFind (Application app, ApplePlatform platform, bool is_simulato if (ret == 0) { path = stdout.ToString ().Trim (); if (!File.Exists (path)) { - ErrorHelper.Warning (5315, Errors.MX5315 /* The tool xcrun failed to return a valid result (the file {0} does not exist). Check build log for details. */, tool, path); + ErrorHelper.Warning (app, 5315, Errors.MX5315 /* The tool xcrun failed to return a valid result (the file {0} does not exist). Check build log for details. */, tool, path); return false; } } else { - Log (1, "Failed to locate the developer tool '{0}', 'xcrun {1}' returned with the exit code {2}:\n{3}", tool, string.Join (" ", args), ret, both.ToString ()); + app.Log (1, "Failed to locate the developer tool '{0}', 'xcrun {1}' returned with the exit code {2}:\n{3}", tool, string.Join (" ", args), ret, both.ToString ()); } return ret == 0; @@ -631,7 +601,7 @@ public static void RunXcodeTool (Application app, string tool, params string [] public static void RunXcodeTool (Application app, string tool, IList arguments) { var executable = FindTool (app, tool); - var rv = RunCommand (executable, arguments); + var rv = RunCommand (app, executable, arguments); if (rv != 0) throw ErrorHelper.CreateError (5309, Errors.MX5309 /* Failed to execute the tool '{0}', it failed with an error code '{1}'. Please check the build log for details. */, tool, rv); } @@ -684,7 +654,7 @@ public static void RunLipoAndCreateDsym (Application app, string output, IEnumer if (Directory.Exists (outputDsymDir)) Directory.Delete (outputDsymDir, true); Directory.Move (dsymFolders [0], outputDsymDir); - RunCommand ("/usr/bin/mdimport", outputDsymDir); + RunCommand (app, "/usr/bin/mdimport", outputDsymDir); } } @@ -696,7 +666,7 @@ public static void RunLipo (Application app, IList options) public static void CreateDsym (Application app, string output_dir, string appname, string dsym_dir) { RunDsymUtil (app, Path.Combine (output_dir, appname), "-num-threads", "4", "-z", "-o", dsym_dir); - RunCommand ("/usr/bin/mdimport", dsym_dir); + RunCommand (app, "/usr/bin/mdimport", dsym_dir); } public static void RunDsymUtil (Application app, params string [] options) @@ -708,6 +678,7 @@ public static void RunStrip (Application app, IList options) { RunXcodeTool (app, "strip", options); } +#endif // !LEGACY_TOOLS public static string CorlibName { get { diff --git a/tools/common/Driver.execution.cs b/tools/common/Driver.execution.cs index bb576ccec230..72c09d3a3d7f 100644 --- a/tools/common/Driver.execution.cs +++ b/tools/common/Driver.execution.cs @@ -18,76 +18,76 @@ namespace Xamarin.Bundler { public partial class Driver { - public static int RunCommand (string path, IList args, Dictionary? env, out StringBuilder output, bool suppressPrintOnErrors, int verbose) + public static int RunCommand (IToolLog log, string path, IList args, Dictionary? env, out StringBuilder output, bool suppressPrintOnErrors, int verbose) { output = new StringBuilder (); - return RunCommand (path, args, env, output, suppressPrintOnErrors, verbose); + return RunCommand (log, path, args, env, output, suppressPrintOnErrors, verbose); } - public static int RunCommand (string path, IList args, Dictionary? env, out StringBuilder output, bool suppressPrintOnErrors) + public static int RunCommand (IToolLog log, string path, IList args, Dictionary? env, out StringBuilder output, bool suppressPrintOnErrors) { output = new StringBuilder (); - return RunCommand (path, args, env, output, suppressPrintOnErrors, Verbosity); + return RunCommand (log, path, args, env, output, suppressPrintOnErrors, log.Verbosity); } - public static int RunCommand (string path, IList args, Dictionary? env, StringBuilder output, bool suppressPrintOnErrors, int verbosity) + public static int RunCommand (IToolLog log, string path, IList args, Dictionary? env, StringBuilder output, bool suppressPrintOnErrors, int verbosity) { - return RunCommand (path, args, env, output, output, suppressPrintOnErrors, verbosity); + return RunCommand (log, path, args, env, output, output, suppressPrintOnErrors, verbosity); } - public static int RunCommand (string path, IList args, Dictionary? env, StringBuilder output, bool suppressPrintOnErrors = false) + public static int RunCommand (IToolLog log, string path, IList args, Dictionary? env, StringBuilder output, bool suppressPrintOnErrors = false) { - return RunCommand (path, args, env, output, output, suppressPrintOnErrors, Verbosity); + return RunCommand (log, path, args, env, output, output, suppressPrintOnErrors, log.Verbosity); } - public static int RunCommand (string path, params string [] args) + public static int RunCommand (IToolLog log, string path, params string [] args) { - return RunCommand (path, args, null, (Action?) null, (Action?) null, false, Verbosity); + return RunCommand (log, path, args, null, (Action?) null, (Action?) null, false, log.Verbosity); } - public static int RunCommand (string path, IList args) + public static int RunCommand (IToolLog log, string path, IList args) { - return RunCommand (path, args, null, (Action?) null, (Action?) null, false, Verbosity); + return RunCommand (log, path, args, null, (Action?) null, (Action?) null, false, log.Verbosity); } - public static int RunCommand (string path, IList args, StringBuilder? output) + public static int RunCommand (IToolLog log, string path, IList args, StringBuilder? output) { - return RunCommand (path, args, null, output, output, false, Verbosity); + return RunCommand (log, path, args, null, output, output, false, log.Verbosity); } - public static int RunCommand (string path, IList args, StringBuilder? output, bool suppressPrintOnErrors) + public static int RunCommand (IToolLog log, string path, IList args, StringBuilder? output, bool suppressPrintOnErrors) { - return RunCommand (path, args, null, output, output, suppressPrintOnErrors, Verbosity); + return RunCommand (log, path, args, null, output, output, suppressPrintOnErrors, log.Verbosity); } - public static int RunCommand (string path, IList args, StringBuilder? output, StringBuilder? error) + public static int RunCommand (IToolLog log, string path, IList args, StringBuilder? output, StringBuilder? error) { - return RunCommand (path, args, null, output, error, false, Verbosity); + return RunCommand (log, path, args, null, output, error, false, log.Verbosity); } - public static int RunCommand (string path, IList args, StringBuilder? output, StringBuilder? error, bool suppressPrintOnErrors) + public static int RunCommand (IToolLog log, string path, IList args, StringBuilder? output, StringBuilder? error, bool suppressPrintOnErrors) { - return RunCommand (path, args, null, output, error, suppressPrintOnErrors, Verbosity); + return RunCommand (log, path, args, null, output, error, suppressPrintOnErrors, log.Verbosity); } - public static int RunCommand (string path, IList args, Dictionary? env, StringBuilder? output, StringBuilder? error, bool suppressPrintOnErrors, int verbosity) + public static int RunCommand (IToolLog log, string path, IList args, Dictionary? env, StringBuilder? output, StringBuilder? error, bool suppressPrintOnErrors, int verbosity) { var output_received = output is null ? null : new Action ((v) => { if (v is not null) output.AppendLine (v); }); var error_received = error is null ? null : new Action ((v) => { if (v is not null) error.AppendLine (v); }); - return RunCommand (path, args, env, output_received, error_received, suppressPrintOnErrors, verbosity); + return RunCommand (log, path, args, env, output_received, error_received, suppressPrintOnErrors, verbosity); } - static int RunCommand (string path, IList args, Dictionary? env, Action? output_received, bool suppressPrintOnErrors) + static int RunCommand (IToolLog log, string path, IList args, Dictionary? env, Action? output_received, bool suppressPrintOnErrors) { - return RunCommand (path, args, env, output_received, output_received, suppressPrintOnErrors, Verbosity); + return RunCommand (log, path, args, env, output_received, output_received, suppressPrintOnErrors, log.Verbosity); } - static int RunCommand (string path, IList args, Dictionary? env, Action? output_received, Action? error_received) + static int RunCommand (IToolLog log, string path, IList args, Dictionary? env, Action? output_received, Action? error_received) { - return RunCommand (path, args, env, output_received, error_received, false, Verbosity); + return RunCommand (log, path, args, env, output_received, error_received, false, log.Verbosity); } - static int RunCommand (string path, IList args, Dictionary? env, Action? output_received, Action? error_received, bool suppressPrintOnErrors, int verbosity) + static int RunCommand (IToolLog log, string path, IList args, Dictionary? env, Action? output_received, Action? error_received, bool suppressPrintOnErrors, int verbosity) { var output = new StringBuilder (); var outputCallback = new Action ((line) => { @@ -103,8 +103,7 @@ static int RunCommand (string path, IList args, Dictionary 0) - Console.WriteLine ($"{path} {StringUtils.FormatArguments (args)}"); + log.Log (1, $"{path} {StringUtils.FormatArguments (args)}"); var p = Execution.RunWithCallbacksAsync (path, args, env, outputCallback, errorCallback).Result; @@ -118,33 +117,27 @@ static int RunCommand (string path, IList args, Dictionary 0 && output?.Length > 0 && !suppressPrintOnErrors) { - Console.WriteLine (output.ToString ()); + log.Log (output.ToString ()); } return p.ExitCode; } - public static Task RunCommandAsync (string path, IList args, Dictionary? env = null, Action? output_received = null, bool suppressPrintOnErrors = false, int? verbosity = null) + public static Task RunCommandAsync (IToolLog log, string path, IList args, Dictionary? env = null, Action? output_received = null, bool suppressPrintOnErrors = false, int? verbosity = null) { - return Task.Run (() => RunCommand (path, args, env, output_received, output_received, suppressPrintOnErrors, verbosity ?? Verbosity)); + return Task.Run (() => RunCommand (log, path, args, env, output_received, output_received, suppressPrintOnErrors, verbosity ?? log.Verbosity)); } - public static Task RunCommandAsync (string path, IList args, Dictionary? env = null, StringBuilder? output = null, bool suppressPrintOnErrors = false, int? verbosity = null) + public static Task RunCommandAsync (IToolLog log, string path, IList args, Dictionary? env = null, StringBuilder? output = null, bool suppressPrintOnErrors = false, int? verbosity = null) { - return Task.Run (() => RunCommand (path, args, env, output, output, suppressPrintOnErrors, verbosity ?? Verbosity)); + return Task.Run (() => RunCommand (log, path, args, env, output, output, suppressPrintOnErrors, verbosity ?? log.Verbosity)); } - -#if BGENERATOR - internal static int Verbosity => ErrorHelper.Verbosity; -#elif !LEGACY_TOOLS && !BUNDLER - internal static int Verbosity; -#endif } } diff --git a/tools/common/ErrorHelper.tools.cs b/tools/common/ErrorHelper.tools.cs index cbfef0ddb7d0..275f0d04a894 100644 --- a/tools/common/ErrorHelper.tools.cs +++ b/tools/common/ErrorHelper.tools.cs @@ -39,7 +39,6 @@ public enum WarningLevel { } static Dictionary? warning_levels; - public static int Verbosity { get; set; } #pragma warning disable 649 public static Func? IsExpectedException; @@ -253,18 +252,18 @@ public static ProductException Create (Application app, int code, bool error, Ex return e; } - public static void Warning (int code, string message, params object [] args) + public static void Warning (IToolLog log, int code, string message, params object [] args) { - Show (new ProductException (code, false, message, args)); + Show (log, new ProductException (code, false, message, args)); } - public static void Warning (int code, Exception innerException, string message, params object [] args) + public static void Warning (IToolLog log, int code, Exception innerException, string message, params object [] args) { - Show (new ProductException (code, false, innerException, message, args)); + Show (log, new ProductException (code, false, innerException, message, args)); } // Shows any warnings, and if there are any errors, throws an AggregateException. - public static void ThrowIfErrors (IList exceptions) + public static void ThrowIfErrors (IToolLog log, IList exceptions) { if (exceptions?.Any () != true) return; @@ -274,28 +273,28 @@ public static void ThrowIfErrors (IList exceptions) var warnings = grouped.SingleOrDefault ((v) => v.Key); if (warnings?.Any () == true) - Show (warnings); + Show (log, warnings); var errors = grouped.SingleOrDefault ((v) => !v.Key); if (errors?.Any () == true) throw new AggregateException (errors); } - public static void Show (IEnumerable list) + public static void Show (IToolLog log, IEnumerable list) { var exceptions = CollectExceptions (list); bool error = false; foreach (var ex in exceptions) - error |= ShowInternal (ex); + error |= ShowInternal (log, ex); if (error) Exit (1); } - public static void Show (Exception e) + public static void Show (IToolLog log, Exception e) { - Show (new Exception [] { e }); + Show (log, new Exception [] { e }); } static void Exit (int exitCode) @@ -305,7 +304,7 @@ static void Exit (int exitCode) Environment.Exit (exitCode); } - static bool ShowInternal (Exception e) + static bool ShowInternal (IToolLog log, Exception e) { var mte = e as ProductException; bool error = true; @@ -316,39 +315,39 @@ static bool ShowInternal (Exception e) if (!error && GetWarningLevel (mte.Code) == WarningLevel.Disable) return false; // This is an ignored warning. - Console.Error.WriteLine (mte.ToString ()); + log.LogError (mte.ToString ()); - ShowInner (e); + ShowInner (log, e); - if (Verbosity > 2 && !string.IsNullOrEmpty (e.StackTrace)) - Console.Error.WriteLine (e.StackTrace); + if (log.Verbosity > 2 && !string.IsNullOrEmpty (e.StackTrace)) + log.LogError (e.StackTrace); } else if (IsExpectedException is null || !IsExpectedException (e)) { - Console.Error.WriteLine ("error " + Prefix + "0000: Unexpected error - Please file a bug report at https://github.com/dotnet/macios/issues/new"); - Console.Error.WriteLine (e.ToString ()); + log.LogError ("error " + Prefix + "0000: Unexpected error - Please file a bug report at https://github.com/dotnet/macios/issues/new"); + log.LogError (e.ToString ()); } else { - Console.Error.WriteLine (e.ToString ()); - ShowInner (e); - if (Verbosity > 2 && !string.IsNullOrEmpty (e.StackTrace)) - Console.Error.WriteLine (e.StackTrace); + log.LogError (e.ToString ()); + ShowInner (log, e); + if (log.Verbosity > 2 && !string.IsNullOrEmpty (e.StackTrace)) + log.LogError (e.StackTrace); } return error; } - static void ShowInner (Exception e) + static void ShowInner (IToolLog log, Exception e) { var ie = e.InnerException; if (ie is null) return; - if (Verbosity > 3) { - Console.Error.WriteLine ("--- inner exception"); - Console.Error.WriteLine (ie); - Console.Error.WriteLine ("---"); - } else if (Verbosity > 0 || ie is ProductException) { - Console.Error.WriteLine ("\t{0}", ie.Message); + if (log.Verbosity > 3) { + log.LogError ("--- inner exception"); + log.LogError (ie.ToString ()); + log.LogError ("---"); + } else if (log.Verbosity > 0 || ie is ProductException) { + log.LogError ($"\t{ie.Message}"); } - ShowInner (ie); + ShowInner (log, ie); } } } diff --git a/tools/common/FileCopier.cs b/tools/common/FileCopier.cs index 98a8e1a27f5d..d10e93b59827 100644 --- a/tools/common/FileCopier.cs +++ b/tools/common/FileCopier.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.InteropServices; @@ -27,6 +28,7 @@ enum CopyFileFlags : uint { enum CopyFileState : uint { StatusCB = 6, + StatusCtx = 7, } enum CopyFileStep { @@ -57,81 +59,39 @@ enum CopyFileWhat { [DllImport ("/usr/lib/libSystem.dylib")] static extern int copyfile_state_free (IntPtr state); +#if NET [DllImport ("/usr/lib/libSystem.dylib")] - static extern int copyfile_state_set (IntPtr state, CopyFileState flag, IntPtr value); - + static extern unsafe int copyfile_state_set (IntPtr state, CopyFileState flag, delegate* unmanaged value); +#else delegate CopyFileResult CopyFileCallbackDelegate (CopyFileWhat what, CopyFileStep stage, IntPtr state, string src, string dst, IntPtr ctx); +#endif + + [DllImport ("/usr/lib/libSystem.dylib")] + static extern unsafe int copyfile_state_set (IntPtr state, CopyFileState flag, IntPtr value); [DllImport ("/usr/lib/libSystem.dylib", SetLastError = true)] static extern int copyfile (string @from, string @to, IntPtr state, CopyFileFlags flags); - // This code is shared between our packaging tools (mmp\mtouch) and msbuild tasks - public delegate void LogCallback (int verbosity, string format, params object? [] arguments); - public delegate void ReportErrorCallback (int code, string format, params object? [] arguments); - - [ThreadStatic] - static LogCallback? logCallback; - - [ThreadStatic] - static ReportErrorCallback? reportErrorCallback; - - static void Log (int min_verbosity, string format, params object? [] arguments) + static void ReportError (IToolLog log, int code, string format, params object? [] arguments) { - if (logCallback is not null) { - logCallback (min_verbosity, format, arguments); - return; - } - #if LEGACY_TOOLS || BUNDLER - // LogMessage and LogError are instance objects on the tasks themselves and bubbling an event up is not ideal - Driver.Log (min_verbosity, format, arguments); + log.LogError (ErrorHelper.CreateError (code, format, arguments)); #else - Console.WriteLine (format, arguments); + log.LogError (new Exception ($"{code} {string.Format (format, arguments)}")); #endif } - static void ReportError (int code, string format, params object? [] arguments) - { - if (reportErrorCallback is not null) { - reportErrorCallback (code, format, arguments); - return; - } - -#if LEGACY_TOOLS || BUNDLER - throw ErrorHelper.CreateError (code, format, arguments); -#else - // msbuild handles uncaught exceptions as a task error - throw new Exception ($"{code} {string.Format (format, arguments)}"); -#endif - } - - public static void UpdateDirectory (string source, string target, ReportErrorCallback reportErrorCallback, LogCallback logCallback) - { - try { - FileCopier.reportErrorCallback = reportErrorCallback; - FileCopier.logCallback = logCallback; - UpdateDirectory (source, target); - } finally { - FileCopier.reportErrorCallback = null; - FileCopier.logCallback = null; - } - } - -#if LEGACY_TOOLS || BUNDLER - public static void UpdateDirectory (string source, string target) -#else - static void UpdateDirectory (string source, string target) -#endif + public static void UpdateDirectory (IToolLog log, string source, string target) { // first chance, try to update existing content inside `target` - if (TryUpdateDirectory (source, target, out var err)) + if (TryUpdateDirectory (log, source, target, out var err)) return; // 2nd chance, remove `target` then copy everything - Log (1, "Could not update `{0}` content (error #{1} : {2}), trying to overwrite everything...", target, err, strerror (err)); + log.Log (1, "Could not update `{0}` content (error #{1} : {2}), trying to overwrite everything...", target, err, strerror (err)); Directory.Delete (target, true); - if (!TryUpdateDirectory (source, target, out err)) - ReportError (1022, Errors.MT1022, source, target, err, strerror (err)); + if (!TryUpdateDirectory (log, source, target, out err)) + ReportError (log, 1022, Errors.MT1022, source, target, err, strerror (err)); } static bool? use_managed_copying; @@ -150,16 +110,16 @@ static bool UseManagedCopying { } } - static bool TryUpdateDirectory (string source, string target, out int errno) + static bool TryUpdateDirectory (IToolLog log, string source, string target, out int errno) { if (UseManagedCopying) - return TryUpdateDirectoryWindows (source, target, out errno); - return TryUpdateDirectoryMacOS (source, target, out errno); + return TryUpdateDirectoryWindows (log, source, target, out errno); + return TryUpdateDirectoryMacOS (log, source, target, out errno); } - static bool TryUpdateDirectoryWindows (string source, string target, out int errno) + static bool TryUpdateDirectoryWindows (IToolLog log, string source, string target, out int errno) { - Log (1, $"Copying {source} to {target} recursively"); + log.Log (1, $"Copying {source} to {target} recursively"); errno = 0; Directory.CreateDirectory (target); @@ -170,39 +130,47 @@ static bool TryUpdateDirectoryWindows (string source, string target, out int err foreach (var sourceFile in dir.GetFiles ()) { var sourcePath = sourceFile.FullName; var targetPath = Path.Combine (target, Path.GetFileName (source), sourceFile.Name); - CopyIfNeeded (sourcePath, targetPath); + CopyIfNeeded (log, sourcePath, targetPath); } foreach (var subdir in dir.GetDirectories ()) { - rv &= TryUpdateDirectoryWindows (Path.Combine (source, subdir.Name), Path.Combine (target, Path.GetFileName (source)), out errno); + rv &= TryUpdateDirectoryWindows (log, Path.Combine (source, subdir.Name), Path.Combine (target, Path.GetFileName (source)), out errno); } } else { var targetPath = Path.Combine (target, Path.GetFileName (source)); - CopyIfNeeded (source, targetPath); + CopyIfNeeded (log, source, targetPath); } return rv; } - static void CopyIfNeeded (string source, string target) + static void CopyIfNeeded (IToolLog log, string source, string target) { - if (IsUptodate (source, target)) { - Log (3, "Target '{0}' is up-to-date", target); + if (IsUptodate (log, source, target)) { + log.Log (3, "Target '{0}' is up-to-date", target); } else { Directory.CreateDirectory (Path.GetDirectoryName (target)!); File.Copy (source, target, true); - Log (1, "Copied {0} to {1}", source, target); + log.Log (1, "Copied {0} to {1}", source, target); } } - static bool TryUpdateDirectoryMacOS (string source, string target, out int errno) + static bool TryUpdateDirectoryMacOS (IToolLog log, string source, string target, out int errno) { Directory.CreateDirectory (target); // Mono's File.Copy can't handle symlinks (the symlinks are followed instead of copied), // so we need to use native functions directly. Luckily OSX provides exactly what we need. IntPtr state = copyfile_state_alloc (); + var logHandle = GCHandle.Alloc (log); try { +#if NET + unsafe { + copyfile_state_set (state, CopyFileState.StatusCB, &CopyFileCallback); + } +#else CopyFileCallbackDelegate del = CopyFileCallback; copyfile_state_set (state, CopyFileState.StatusCB, Marshal.GetFunctionPointerForDelegate (del)); +#endif + copyfile_state_set (state, CopyFileState.StatusCtx, (IntPtr) logHandle); int rv = copyfile (source, target, state, CopyFileFlags.Data | CopyFileFlags.Recursive | CopyFileFlags.Nofollow | CopyFileFlags.Clone); if (rv == 0) { errno = 0; // satisfy compiler and make sure not to pick up some older error code @@ -212,25 +180,36 @@ static bool TryUpdateDirectoryMacOS (string source, string target, out int errno return false; } } finally { + logHandle.Free (); copyfile_state_free (state); } } // do not call `Marshal.GetLastWin32Error` inside this method since it's called while the p/invoke is executing and will return `260` +#if NET + [UnmanagedCallersOnly] + static CopyFileResult CopyFileCallback (CopyFileWhat what, CopyFileStep stage, IntPtr state, IntPtr sourcePtr, IntPtr targetPtr, IntPtr ctx) + { + var source = Marshal.PtrToStringUTF8 (sourcePtr)!; + var target = Marshal.PtrToStringUTF8 (targetPtr)!; +#else static CopyFileResult CopyFileCallback (CopyFileWhat what, CopyFileStep stage, IntPtr state, string source, string target, IntPtr ctx) { - // Console.WriteLine ("CopyFileCallback ({0}, {1}, 0x{2}, {3}, {4}, 0x{5})", what, stage, state.ToString ("x"), source, target, ctx.ToString ("x")); +#endif + var log = (IToolLog) GCHandle.FromIntPtr (ctx).Target!; + + // log.Log ("CopyFileCallback ({0}, {1}, 0x{2}, {3}, {4}, 0x{5})", what, stage, state.ToString ("x"), source, target, ctx.ToString ("x")); switch (what) { case CopyFileWhat.File: - if (!IsUptodate (source, target)) { + if (!IsUptodate (log, source, target)) { if (stage == CopyFileStep.Finish) - Log (1, "Copied {0} to {1}", source, target); + log.Log (1, "Copied {0} to {1}", source, target); else if (stage == CopyFileStep.Err) { - Log (1, "Could not copy the file '{0}' to '{1}'", source, target); + log.Log (1, "Could not copy the file '{0}' to '{1}'", source, target); return CopyFileResult.Quit; } else if (stage == CopyFileStep.Start) { if (File.Exists (target) || Directory.Exists (target)) { - Log (1, "Deleted target {0}, it's not up-to-date", target); + log.Log (1, "Deleted target {0}, it's not up-to-date", target); // This callback won't be called for directories, but we can get here for symlinks to directories. // This means that File.Delete should always work (no need to check for a directory to call Directory.Delete) File.Delete (target); @@ -238,7 +217,7 @@ static CopyFileResult CopyFileCallback (CopyFileWhat what, CopyFileStep stage, I } return CopyFileResult.Continue; } else { - Log (3, "Target '{0}' is up-to-date", target); + log.Log (3, "Target '{0}' is up-to-date", target); return CopyFileResult.Skip; } case CopyFileWhat.Dir: @@ -247,36 +226,20 @@ static CopyFileResult CopyFileCallback (CopyFileWhat what, CopyFileStep stage, I case CopyFileWhat.CopyXattr: return CopyFileResult.Continue; case CopyFileWhat.Error: - Log (1, "Could not copy the file '{0}' to '{1}'", source, target); + log.Log (1, "Could not copy the file '{0}' to '{1}'", source, target); return CopyFileResult.Quit; default: return CopyFileResult.Continue; } } - public static bool IsUptodate (string source, string target, ReportErrorCallback reportErrorCallback, LogCallback logCallback, bool check_contents = false, bool check_stamp = true) - { - try { - FileCopier.reportErrorCallback = reportErrorCallback; - FileCopier.logCallback = logCallback; - return IsUptodate (source, target, check_contents, check_stamp); - } finally { - FileCopier.reportErrorCallback = null; - FileCopier.logCallback = null; - } - } - // Checks if the source file has a time stamp later than the target file. // // Optionally check if the contents of the files are different after checking the timestamp. // // If check_stamp is true, the function will use the timestamp of a "target".stamp file // if it's later than the timestamp of the "target" file itself. -#if LEGACY_TOOLS || BUNDLER - public static bool IsUptodate (string source, string target, bool check_contents = false, bool check_stamp = true) -#else - static bool IsUptodate (string source, string target, bool check_contents = false, bool check_stamp = true) -#endif + public static bool IsUptodate (IToolLog log, string source, string target, bool check_contents = false, bool check_stamp = true) { #if LEGACY_TOOLS || BUNDLER // msbuild does not have force if (Driver.Force) @@ -286,14 +249,14 @@ static bool IsUptodate (string source, string target, bool check_contents = fals var tfi = new FileInfo (target); if (!tfi.Exists) { - Log (3, "Target '{0}' does not exist.", target); + log.Log (3, "Target '{0}' does not exist.", target); return false; } if (check_stamp) { var tfi_stamp = new FileInfo (target + ".stamp"); if (tfi_stamp.Exists && tfi_stamp.LastWriteTimeUtc > tfi.LastWriteTimeUtc) { - Log (3, "Target '{0}' has a stamp file with newer timestamp ({1} > {2}), using the stamp file's timestamp", target, tfi_stamp.LastWriteTimeUtc, tfi.LastWriteTimeUtc); + log.Log (3, "Target '{0}' has a stamp file with newer timestamp ({1} > {2}), using the stamp file's timestamp", target, tfi_stamp.LastWriteTimeUtc, tfi.LastWriteTimeUtc); tfi = tfi_stamp; } } @@ -301,13 +264,13 @@ static bool IsUptodate (string source, string target, bool check_contents = fals var sfi = new FileInfo (source); if (sfi.LastWriteTimeUtc <= tfi.LastWriteTimeUtc) { - Log (3, "Prerequisite '{0}' is older than the target '{1}'.", source, target); + log.Log (3, "Prerequisite '{0}' is older than the target '{1}'.", source, target); return true; } #if LEGACY_TOOLS || BUNDLER // msbuild usages do not require CompareFiles optimization - if (check_contents && Cache.CompareFiles (source, target)) { - Log (3, "Prerequisite '{0}' is newer than the target '{1}', but the contents are identical.", source, target); + if (check_contents && Cache.CompareFiles (log, source, target)) { + log.Log (3, "Prerequisite '{0}' is newer than the target '{1}', but the contents are identical.", source, target); return true; } #else @@ -315,31 +278,15 @@ static bool IsUptodate (string source, string target, bool check_contents = fals throw new NotImplementedException ("Checking file contents is not supported"); #endif - Log (3, "Prerequisite '{0}' is newer than the target '{1}'.", source, target); + log.Log (3, "Prerequisite '{0}' is newer than the target '{1}'.", source, target); return false; } - public static bool IsUptodate (IEnumerable sources, IEnumerable targets, ReportErrorCallback reportErrorCallback, LogCallback logCallback, bool check_stamp = true) - { - try { - FileCopier.reportErrorCallback = reportErrorCallback; - FileCopier.logCallback = logCallback; - return IsUptodate (sources, targets, check_stamp); - } finally { - FileCopier.reportErrorCallback = null; - FileCopier.logCallback = null; - } - } - // Checks if any of the source files have a time stamp later than any of the target files. // // If check_stamp is true, the function will use the timestamp of a "target".stamp file // if it's later than the timestamp of the "target" file itself. -#if LEGACY_TOOLS || BUNDLER - public static bool IsUptodate (IEnumerable sources, IEnumerable targets, bool check_stamp = true) -#else - static bool IsUptodate (IEnumerable sources, IEnumerable targets, bool check_stamp = true) -#endif + public static bool IsUptodate (IToolLog log, IEnumerable sources, IEnumerable targets, bool check_stamp = true) { #if LEGACY_TOOLS || BUNDLER // msbuild does not have force if (Driver.Force) @@ -355,7 +302,7 @@ static bool IsUptodate (IEnumerable sources, IEnumerable targets foreach (var s in sources) { var sfi = new FileInfo (s); if (!sfi.Exists) { - Log (3, "Prerequisite '{0}' does not exist.", s); + log.Log (3, "Prerequisite '{0}' does not exist.", s); return false; } @@ -370,31 +317,31 @@ static bool IsUptodate (IEnumerable sources, IEnumerable targets foreach (var t in targets) { var tfi = new FileInfo (t); if (!tfi.Exists) { - Log (3, "Target '{0}' does not exist.", t); + log.Log (3, "Target '{0}' does not exist.", t); return false; } if (check_stamp) { var tfi_stamp = new FileInfo (t + ".stamp"); if (tfi_stamp.Exists && tfi_stamp.LastWriteTimeUtc > tfi.LastWriteTimeUtc) { - Log (3, "Target '{0}' has a stamp file with newer timestamp ({1} > {2}), using the stamp file's timestamp", t, tfi_stamp.LastWriteTimeUtc, tfi.LastWriteTimeUtc); + log.Log (3, "Target '{0}' has a stamp file with newer timestamp ({1} > {2}), using the stamp file's timestamp", t, tfi_stamp.LastWriteTimeUtc, tfi.LastWriteTimeUtc); tfi = tfi_stamp; } } var lwt = tfi.LastWriteTimeUtc; if (max_source > lwt) { - Log (3, "Prerequisite '{0}' is newer than target '{1}' ({2} vs {3}).", max_s, t, max_source, lwt); + log.Log (3, "Prerequisite '{0}' is newer than target '{1}' ({2} vs {3}).", max_s, t, max_source, lwt); return false; } } - Log (3, "Prerequisite(s) '{0}' are all older than the target(s) '{1}'.", string.Join ("', '", sources.ToArray ()), string.Join ("', '", targets.ToArray ())); + log.Log (3, "Prerequisite(s) '{0}' are all older than the target(s) '{1}'.", string.Join ("', '", sources.ToArray ()), string.Join ("', '", targets.ToArray ())); return true; } - [DllImport ("/usr/lib/libSystem.dylib", SetLastError = true, EntryPoint = "strerror")] + [DllImport ("libc", SetLastError = true, EntryPoint = "strerror")] static extern IntPtr _strerror (int errno); internal static string strerror (int errno) diff --git a/tools/common/FileUtils.cs b/tools/common/FileUtils.cs index f8b3c617674f..7b406fd24ed6 100644 --- a/tools/common/FileUtils.cs +++ b/tools/common/FileUtils.cs @@ -75,5 +75,19 @@ public static bool UpdateFile (string targetFile, Action createOutput) } } + + public static void WriteIfDifferent (string path, string contents, Action log) + { + if (!File.Exists (path)) { + log ($"File '{path}' contents are not up-to-date, because the file doesn't exist."); + File.WriteAllText (path, contents); + } else if (string.Equals (contents, File.ReadAllText (path), StringComparison.Ordinal)) { + log ($"File '{path}' contents are up-to-date."); + return; + } else { + log ($"File '{path}' contents are not up-to-date."); + File.WriteAllText (path, contents); + } + } } } diff --git a/tools/common/Frameworks.cs b/tools/common/Frameworks.cs index 3ae4d13d039f..3970120f17fa 100644 --- a/tools/common/Frameworks.cs +++ b/tools/common/Frameworks.cs @@ -7,6 +7,7 @@ using Mono.Tuner; using Xamarin.Bundler; +using Xamarin.Linker; using Registrar; #endif @@ -21,7 +22,8 @@ public class Framework { public required Version Version { get; set; } public Version? VersionAvailableInSimulator { get; set; } public bool AlwaysWeakLinked { get; set; } - public bool Unavailable { get; set; } + public bool Unavailable { private get; set; } // Call IsFrameworkUnavailable () to determine if a framework is available or not + public Version? VersionUnavailable { get; set; } // if null, always unavailable (if Unavailable=true) public string LibraryPath { get { @@ -34,7 +36,7 @@ public string LibraryPath { } #if LEGACY_TOOLS || BUNDLER - public bool IsFrameworkAvailableInSimulator (Application app) + bool IsFrameworkAvailableInSimulator (Application app) { if (VersionAvailableInSimulator is null) return false; @@ -45,6 +47,27 @@ public bool IsFrameworkAvailableInSimulator (Application app) return true; } #endif + +#if LEGACY_TOOLS || BUNDLER + public bool IsFrameworkUnavailable (Application app) + { + if (app.IsSimulatorBuild && !IsFrameworkAvailableInSimulator (app)) + return true; + + if (!Unavailable) + return false; + + if (VersionUnavailable is null) + return true; + + return app.SdkVersion >= VersionUnavailable; + } +#else + public bool IsFrameworkUnavailable () + { + return Unavailable; + } +#endif } public class Frameworks : Dictionary { @@ -88,7 +111,7 @@ public void Add (string @namespace, string framework, int major_version, int min Add (@namespace, framework, new Version (major_version, minor_version, build_version)); } - public void Add (string @namespace, string framework, Version version, Version? version_available_in_simulator = null, bool alwaysWeakLink = false, string? subFramework = null) + public void Add (string @namespace, string framework, Version version, Version? version_available_in_simulator = null, bool alwaysWeakLink = false, string? subFramework = null, Version? version_unavailable = null) { var fr = new Framework () { Namespace = @namespace, @@ -97,6 +120,8 @@ public void Add (string @namespace, string framework, Version version, Version? VersionAvailableInSimulator = version_available_in_simulator ?? version, AlwaysWeakLinked = alwaysWeakLink, SubFramework = subFramework, + Unavailable = version_unavailable is not null, + VersionUnavailable = version_unavailable, }; base.Add (fr.Namespace, fr); } @@ -337,6 +362,7 @@ public static Frameworks CreateiOSFrameworks (bool is_simulator_build) { "UIKit", "UIKit", 3 }, { "Accelerate", "Accelerate", 4 }, + { "AssetsLibrary", "AssetsLibrary", new Version (4, 0), null, false, null, /* version_unavailable = */ new Version (17, 4) }, { "EventKit", "EventKit", 4 }, { "EventKitUI", "EventKitUI", 4 }, { "CoreMotion", "CoreMotion", 4 }, @@ -350,6 +376,7 @@ public static Frameworks CreateiOSFrameworks (bool is_simulator_build) { "Accounts", "Accounts", 5 }, { "GLKit", "GLKit", 5 }, + { "NewsstandKit", "NewsstandKit", new Version (5, 0), null, false, null, /* version_unavailable = */ new Version (17, 0) }, { "CoreImage", "CoreImage", 5 }, { "CoreBluetooth", "CoreBluetooth", 5 }, { "Twitter", "Twitter", 5 }, @@ -453,7 +480,7 @@ public static Frameworks CreateiOSFrameworks (bool is_simulator_build) { "CoreLocationUI", "CoreLocationUI", 15,0 }, { "DataDetection", "DataDetection", 15, 0 }, - { "Phase", "PHASE", new Version (15,0), NotAvailableInSimulator /* no headers in beta 2 */ }, + { "Phase", "PHASE", new Version (15, 0), new Version (26, 0) /* not certain about the exact version when this framework was added to the simulator, but this should be a safe default */ }, { "OSLog", "OSLog", 15,0 }, { "ShazamKit", "ShazamKit", new Version (15,0), new Version (16, 0)}, { "ThreadNetwork", "ThreadNetwork", new Version (15,0), NotAvailableInSimulator}, @@ -651,7 +678,6 @@ public static Frameworks GetMacCatalystFrameworks () // These frameworks are not available on Mac Catalyst case "DeviceDiscoveryUI": // xtro and introspection says it's not in Mac Catalyst, Apple's website says it is. For now, listen to xtro and introspection, until proven otherwise. case "OpenGLES": - case "NewsstandKit": case "NotificationCenter": case "GLKit": case "VideoSubscriberAccount": @@ -663,7 +689,6 @@ public static Frameworks GetMacCatalystFrameworks () // headers-based xtro reporting those are *all* unknown API for Catalyst case "AddressBookUI": case "ARKit": - case "AssetsLibrary": case "BrowserEngineCore": case "CarPlay": case "WatchConnectivity": @@ -705,11 +730,15 @@ public static Frameworks GetMacCatalystFrameworks () } } -#if LEGACY_TOOLS || BUNDLER - public static IEnumerable GetFrameworks (TypeDefinition td) +#if BUNDLER || LEGACY_TOOLS + public static bool TryGetFramework (Application app, TypeDefinition? td, [NotNullWhen (true)] out string? framework) { + framework = null; + + if (td is null) + return false; + if (td.HasCustomAttributes) { - var any = false; foreach (var attrib in td.CustomAttributes) { if (!attrib.AttributeType.Is ("ObjCRuntime", "ObjectiveCFrameworkAttribute")) continue; @@ -718,25 +747,65 @@ public static IEnumerable GetFrameworks (TypeDefinition td) var arg = attrib.ConstructorArguments [0]; if (arg.Value is not string stringArgument) continue; - yield return stringArgument; - any = true; + framework = stringArgument; + return framework is not null; } - if (any) - yield break; } - yield return td.Namespace; +#if !LEGACY_TOOLS + if (!app.Profile.IsProductAssembly (td.Module.Assembly)) + return false; +#endif + + framework = td.Namespace; + return framework is not null; } - static void Gather (Application app, AssemblyDefinition product_assembly, HashSet frameworks, HashSet weak_frameworks, Func include_framework) + public static bool TryGetFramework (Application app, TypeDefinition? td, [NotNullWhen (true)] out Framework? framework) + { + framework = null; + + if (td is null) + return false; + + if (!TryGetFramework (app, td, out string? frameworkName)) + return false; + + var all_frameworks = GetFrameworks (app.Platform, app.IsSimulatorBuild); + if (all_frameworks is null) + return false; + return all_frameworks.TryGetValue (frameworkName, out framework); + } + + static void Gather (Application app, IEnumerable assemblies, HashSet frameworks, HashSet weak_frameworks, Func include_framework) { var namespaces = new HashSet (); - // Collect all the namespaces. - foreach (var md in product_assembly.Modules) { - foreach (var td in md.Types) { - foreach (var fw in GetFrameworks (td)) - namespaces.Add (fw); + // Process our product assembly + any assembly with the [ObjectiveCFramework] attribute, and collect all the namespaces that are used in those assemblies. + // For non-product assemblies, we only look at types with the [ObjectiveCFramework] attribute. + foreach (var assembly in assemblies) { +#if LEGACY_TOOLS + var hasObjectiveCFrameworkAttribute = true; +#else + var hasObjectiveCFrameworkAttribute = false; + if (!app.Profile.IsProductAssembly (assembly)) { + hasObjectiveCFrameworkAttribute = assembly.MainModule.HasTypeReference ("ObjCRuntime.ObjectiveCFrameworkAttribute"); + if (!hasObjectiveCFrameworkAttribute) + continue; + } +#endif + + // Collect all the namespaces. + foreach (var md in assembly.Modules) { + foreach (var td in md.Types) { + if (hasObjectiveCFrameworkAttribute && !td.HasCustomAttribute ("ObjCRuntime", "ObjectiveCFrameworkAttribute")) + continue; + + if (TryGetFramework (app, td, out string? framework)) { + namespaces.Add (framework); + continue; + } + } } } @@ -756,7 +825,7 @@ static void Gather (Application app, AssemblyDefinition product_assembly, HashSe continue; } - if (app.IsSimulatorBuild && !framework.IsFrameworkAvailableInSimulator (app)) + if (framework.IsFrameworkUnavailable (app)) continue; var weak_link = framework.AlwaysWeakLinked || app.DeploymentTarget < framework.Version; @@ -771,39 +840,25 @@ static void Gather (Application app, AssemblyDefinition product_assembly, HashSe static bool FilterFrameworks (Application app, Framework framework) { - var xcodeVersion = Driver.XcodeVersion; - if (xcodeVersion is not null && framework.Name == "NewsstandKit" && xcodeVersion.Major >= 15) { - Driver.Log (3, "Not linking with the framework {0} because it's not available when using Xcode 15+.", framework.Name); + if (framework.IsFrameworkUnavailable (app)) { + app.Log (3, "Not linking with the framework {0} because it's not available in the current SDK.", framework.Name); return false; } switch (app.Platform) { case ApplePlatform.iOS: - switch (framework.Name) { - case "GameKit": - break; - case "NewsstandKit": - if (xcodeVersion is not null && xcodeVersion.Major >= 15) { - Driver.Log (3, "Not linking with the framework {0} because it's been removed from Xcode 15+.", framework.Name); - return false; - } - break; - } - break; case ApplePlatform.TVOS: case ApplePlatform.MacCatalyst: - break; // Include all frameworks by default case ApplePlatform.MacOSX: - return true; + return true; // Include all frameworks by default default: throw ErrorHelper.CreateError (71, Errors.MX0071 /* "Unknown platform: {0}. This usually indicates a bug in {1}; please file a bug report at https://github.com/dotnet/macios/issues/new with a test case." */, app.Platform, app.ProductName); } - return true; } - public static void Gather (Application app, AssemblyDefinition product_assembly, HashSet frameworks, HashSet weak_frameworks) + public static void Gather (Application app, IEnumerable assemblies, HashSet frameworks, HashSet weak_frameworks) { - Gather (app, product_assembly, frameworks, weak_frameworks, (framework) => FilterFrameworks (app, framework)); + Gather (app, assemblies, frameworks, weak_frameworks, (framework) => FilterFrameworks (app, framework)); } -#endif // LEGACY_TOOLS || BUNDLER +#endif // BUNDLER } diff --git a/tools/common/IToolLog.cs b/tools/common/IToolLog.cs new file mode 100644 index 000000000000..1bc5a9c41d31 --- /dev/null +++ b/tools/common/IToolLog.cs @@ -0,0 +1,68 @@ +namespace Xamarin.Bundler; + +public interface IToolLog { + int Verbosity { get; } + void Log (string message); + void LogError (string message); + // Log an error we raise ourselves (through an exception) + void LogError (Exception exception); + // Log an unexpected exception + void LogException (Exception exception); +} + +public static class IToolLogExtensions { + public static void Log (this IToolLog log, string format, params object? [] args) + { + log.Log (string.Format (format, args)); + } + + public static void Log (this IToolLog log, int min_verbosity, string message) + { + if (min_verbosity > log.Verbosity) + return; + + log.Log (message); + } + + public static void Log (this IToolLog log, int min_verbosity, string format, params object? [] args) + { + if (min_verbosity > log.Verbosity) + return; + + Log (log, format, args); + } +} + +#if !MSBUILD_TASKS +public class ConsoleLog : IToolLog { + public readonly static IToolLog Instance = new ConsoleLog (); + +#if TESTS + int verbosity = 0; +#else + int verbosity = Driver.GetDefaultVerbosity (); +#endif + + public int Verbosity { get => verbosity; } + + public void Log (string message) + { + Console.WriteLine (message); + } + + public void LogError (string message) + { + Console.Error.WriteLine (message); + } + + public void LogError (Exception exception) + { + Console.Error.WriteLine (exception); + } + + public void LogException (Exception exception) + { + Console.Error.WriteLine (exception); + } +} +#endif // !MSBUILD_TASKS diff --git a/tools/common/MachO.cs b/tools/common/MachO.cs index 197c99736be1..ff06994660b7 100644 --- a/tools/common/MachO.cs +++ b/tools/common/MachO.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Net; using System.Text; using Xamarin.Bundler; @@ -90,6 +91,7 @@ public enum LoadCommands : uint { // /* Constants for the cmd field of all load commands, the type */ //#define LC_SEGMENT 0x1 /* segment of this file to be mapped */ //#define LC_SYMTAB 0x2 /* link-edit stab symbol table info */ + Symtab = 0x2, //#define LC_SYMSEG 0x3 /* link-edit gdb symbol table info (obsolete) */ //#define LC_THREAD 0x4 /* thread */ //#define LC_UNIXTHREAD 0x5 /* unix thread (includes a stack) */ @@ -267,122 +269,7 @@ public static IEnumerable Read (string filename) } } -#if MTOUCH - // Removes all architectures from the target file, except for those in 'architectures'. - // This method doesn't do anything if the target file is a thin mach-o file. - // Also it doesn't do anything if the result is an empty file (i.e. none of the - // selected architectures match any of the architectures in the file) - this is - // only because I haven't investigated what would be needed elsewhere in the link - // process when the entire file is removed. FIXME <--. - public static void SelectArchitectures (string filename, ICollection abis) - { - var architectures = GetArchitectures (abis); - var tmpfile = filename + ".tmp"; - - if (abis.Count == 0) - return; - - using (var fsr = new FileStream (filename, FileMode.Open, FileAccess.Read)) { - using (var reader = new BinaryReader (fsr)) { - var file = ReadFile (filename); - if (file is MachOFile) { - Driver.Log (2, "Skipping architecture selecting of '{0}', since it only contains 1 architecture.", filename); - return; - } - - var fatfile = (FatFile) file; - bool any_removed = false; - - // remove architectures we don't want - for (int i = fatfile.entries!.Count - 1; i >= 0; i--) { - var ff = fatfile.entries [i]; - if (!architectures.Contains (ff.entry!.Architecture)) { - any_removed = true; - fatfile.entries.RemoveAt (i); - fatfile.nfat_arch--; - Driver.Log (2, "Removing architecture {0} from {1}", ff.entry.Architecture, filename); - } - } - - if (!any_removed) { - Driver.Log (2, "Architecture selection of '{0}' didn't find any architectures to remove.", filename); - return; - } - - if (fatfile.nfat_arch == 0) { - Driver.Log (2, "Skipping architecture selection of '{0}', none of the selected architectures match any of the architectures in the archive.", filename, architectures [0]); - return; - } - - if (fatfile.nfat_arch == 1) { - // Thin file - var entry = fatfile.entries [0]; - using (var fsw = new FileStream (tmpfile, FileMode.Create, FileAccess.Write)) { - using (var writer = new BinaryWriter (fsw)) { - entry.WriteFile (writer, reader, entry.offset); - } - } - } else { - // Fat file - // Re-calculate header data - var read_offset = new List (fatfile.entries.Count); - read_offset.Add (fatfile.entries [0].offset); - fatfile.entries [0].offset = (uint) (1 << (int) fatfile.entries [0].align); - for (int i = 1; i < fatfile.entries.Count; i++) { - read_offset.Add (fatfile.entries [i].offset); - fatfile.entries [i].offset = fatfile.entries [i - 1].offset + fatfile.entries [i - 1].size; - var alignSize = (1 << (int) fatfile.entries [i].align); - var align = (int) fatfile.entries [i].offset % alignSize; - if (align != 0) - fatfile.entries [i].offset += (uint) (alignSize - align); - } - // Write out the fat file - using (var fsw = new FileStream (tmpfile, FileMode.Create, FileAccess.Write)) { - using (var writer = new BinaryWriter (fsw)) { - // write headers - fatfile.WriteHeaders (writer); - // write data - for (int i = 0; i < fatfile.entries.Count; i++) { - fatfile.entries [i].Write (writer, reader, read_offset [i]); - } - } - } - } - } - } - - File.Delete (filename); - File.Move (tmpfile, filename); - } -#endif - - static Dictionary> native_dependencies = new Dictionary> (); - - public static IEnumerable GetNativeDependencies (string libraryName) - { - IEnumerable? result; - lock (native_dependencies) { - if (native_dependencies.TryGetValue (libraryName, out result)) - return result; - } - - var macho_files = Read (libraryName); - var dependencies = new HashSet (); - foreach (var macho_file in macho_files) { - foreach (var lc in macho_file.load_commands) { - var dyld_lc = lc as Xamarin.DylibLoadCommand; - if (dyld_lc?.name is not null) { - dependencies.Add (dyld_lc.name); - } - } - } - result = dependencies; - lock (native_dependencies) - native_dependencies.Add (libraryName, result); - return result; - } - - public static List GetArchitectures (string file) + public static List GetArchitectures (IToolLog log, string file) { var result = new List (); @@ -422,7 +309,7 @@ public static List GetArchitectures (string file) result.Add (GetArch (System.Net.IPAddress.NetworkToHostOrder (reader.ReadInt32 ()), System.Net.IPAddress.NetworkToHostOrder (reader.ReadInt32 ()))); break; default: - Console.WriteLine ("File '{0}' is neither a Universal binary nor a Mach-O binary (magic: 0x{1})", file, magic.ToString ("x")); + log.Log ("File '{0}' is neither a Universal binary nor a Mach-O binary (magic: 0x{1})", file, magic.ToString ("x")); break; } } @@ -606,8 +493,8 @@ internal void Read (string filename, BinaryReader reader, long size) file.Read (reader); object_files.Add (file); } - // byte position is always even after each file. - if (nextPosition % 1 == 1) + // The ar format requires each entry to start at an even byte offset. + if (nextPosition % 2 == 1) nextPosition++; reader.BaseStream.Position = nextPosition; } @@ -641,6 +528,33 @@ public static bool IsStaticLibrary (string filename, bool throw_if_error = false } } } + + /// + /// Reads a static library or a Mach-O object file and returns the set of unresolved (undefined external) symbols. + /// + public static HashSet GetUnresolvedSymbols (string filename) + { + var symbols = new HashSet (); + using (var fs = File.OpenRead (filename)) + using (var reader = new BinaryReader (fs)) { + if (IsStaticLibrary (reader)) { + var lib = new StaticLibrary (); + lib.Read (filename, reader, fs.Length); + foreach (var obj in lib.ObjectFiles) { + foreach (var sym in obj.GetUnresolvedSymbols (reader)) + symbols.Add (sym); + } + } else if (MachOFile.IsMachOLibrary (null, reader)) { + var obj = new MachOFile (filename); + obj.Read (reader); + foreach (var sym in obj.GetUnresolvedSymbols (reader)) + symbols.Add (sym); + } else { + throw ErrorHelper.CreateError (1601, Errors.MT1601, System.Text.Encoding.ASCII.GetString (reader.ReadBytes (7), 0, 7)); + } + } + return symbols; + } } public class MachOFile { @@ -657,6 +571,7 @@ public class MachOFile { uint _reserved; bool is64bitheader; + long streamBasePosition; // position in the stream where this Mach-O header starts public int cputype { get { return is_big_endian ? MachO.ToBigEndian (_cputype) : _cputype; } } public int cpusubtype { get { return is_big_endian ? MachO.ToBigEndian (_cpusubtype) : _cpusubtype; } } @@ -728,6 +643,8 @@ internal static bool IsMachOLibrary (FatEntry? fat_entry, BinaryReader reader, b internal void Read (BinaryReader reader) { + streamBasePosition = reader.BaseStream.Position; + /* definitions from: /usr/include/mach-o/loader.h */ /* * The 32-bit mach header appears at the very beginning of the object file for @@ -868,6 +785,16 @@ internal void Read (BinaryReader reader) } lc = buildVer; break; + case MachO.LoadCommands.Symtab: + var symtabCmd = new SymtabLoadCommand (); + symtabCmd.cmd = reader.ReadUInt32 (); + symtabCmd.cmdsize = reader.ReadUInt32 (); + symtabCmd.symoff = reader.ReadUInt32 (); + symtabCmd.nsyms = reader.ReadUInt32 (); + symtabCmd.stroff = reader.ReadUInt32 (); + symtabCmd.strsize = reader.ReadUInt32 (); + lc = symtabCmd; + break; default: lc = new LoadCommand (); lc.cmd = reader.ReadUInt32 (); @@ -893,6 +820,58 @@ public bool IsDynamicLibrary { public bool IsObjectFile { get => filetype == MachO.MH_OBJECT; } + + const byte N_EXT = 0x01; // external symbol + const byte N_TYPE = 0x0e; // mask for type bits + const byte N_UNDF = 0x0; // undefined symbol + + /// + /// Reads unresolved (undefined external) symbols from this Mach-O file. + /// The reader must be the same stream used to read this file. + /// + public HashSet GetUnresolvedSymbols (BinaryReader reader) + { + var symbols = new HashSet (); + var symtab = load_commands.OfType ().FirstOrDefault (); + if (symtab is null || symtab.nsyms == 0) + return symbols; + + // Read the string table + reader.BaseStream.Position = streamBasePosition + symtab.stroff; + var stringTable = reader.ReadBytes ((int) symtab.strsize); + + // Read symbol table entries + reader.BaseStream.Position = streamBasePosition + symtab.symoff; + var nlistSize = is64bitheader ? 16 : 12; + for (uint i = 0; i < symtab.nsyms; i++) { + var n_strx = reader.ReadUInt32 (); + var n_type = reader.ReadByte (); + var n_sect = reader.ReadByte (); + var n_desc = reader.ReadInt16 (); + if (is64bitheader) + reader.ReadUInt64 (); // n_value (8 bytes) + else + reader.ReadUInt32 (); // n_value (4 bytes) + + // Filter for undefined external symbols (equivalent of nm -u) + if ((n_type & N_EXT) == 0) + continue; + if ((n_type & N_TYPE) != N_UNDF) + continue; + + // Read symbol name from string table + if (n_strx >= symtab.strsize) + continue; + var end = (int) n_strx; + while (end < stringTable.Length && stringTable [end] != 0) + end++; + var name = Encoding.UTF8.GetString (stringTable, (int) n_strx, end - (int) n_strx); + if (name.Length > 0) + symbols.Add (name); + } + + return symbols; + } } public class FatFile { @@ -1044,10 +1023,10 @@ public MachO.LoadCommands Command { } #if DEBUG - public virtual void Dump () + public virtual void Dump (IToolLog log) { - Console.WriteLine (" cmd: {0}", cmd); - Console.WriteLine (" cmdsize: {0}", cmdsize); + log.Log (" cmd: {0}", cmd); + log.Log (" cmdsize: {0}", cmdsize); } #endif } @@ -1059,13 +1038,13 @@ public class DylibLoadCommand : LoadCommand { public uint compatibility_version; #if DEBUG - public override void Dump () + public override void Dump (IToolLog log) { - base.Dump (); - Console.WriteLine (" name: {0}", name); - Console.WriteLine (" timestamp: {0}", timestamp); - Console.WriteLine (" current_version: {0}", current_version); - Console.WriteLine (" compatibility_version: {0}", compatibility_version); + base.Dump (log); + log.Log (" name: {0}", name); + log.Log (" timestamp: {0}", timestamp); + log.Log (" current_version: {0}", current_version); + log.Log (" compatibility_version: {0}", compatibility_version); } #endif } @@ -1077,13 +1056,13 @@ public class DylibIdCommand : LoadCommand { public uint compatibility_version; #if DEBUG - public override void Dump () + public override void Dump (IToolLog log) { - base.Dump (); - Console.WriteLine (" name: {0}", name); - Console.WriteLine (" timestamp: {0}", timestamp); - Console.WriteLine (" current_version: {0}", current_version); - Console.WriteLine (" compatibility_version: {0}", compatibility_version); + base.Dump (log); + log.Log (" name: {0}", name); + log.Log (" timestamp: {0}", timestamp); + log.Log (" current_version: {0}", current_version); + log.Log (" compatibility_version: {0}", compatibility_version); } #endif } @@ -1092,11 +1071,11 @@ public class UuidCommand : LoadCommand { public byte []? uuid; #if DEBUG - public override void Dump () + public override void Dump (IToolLog log) { - base.Dump (); - Console.WriteLine (" cmd: {0}", cmd); - Console.WriteLine (" uuid: {0}", uuid); + base.Dump (log); + log.Log (" cmd: {0}", cmd); + log.Log (" uuid: {0}", uuid); } #endif } @@ -1148,4 +1127,11 @@ public MachO.Platform Platform { get { return (MachO.Platform) platform; } } } + + public class SymtabLoadCommand : LoadCommand { + public uint symoff; // offset to symbol table entries + public uint nsyms; // number of symbol table entries + public uint stroff; // offset to string table + public uint strsize; // size of string table in bytes + } } diff --git a/tools/common/PInvokeWrapperGenerator.cs b/tools/common/PInvokeWrapperGenerator.cs index a0c4592a5ccb..d8ba33801ac6 100644 --- a/tools/common/PInvokeWrapperGenerator.cs +++ b/tools/common/PInvokeWrapperGenerator.cs @@ -70,8 +70,8 @@ public void End () Registrar.GeneratePInvokeWrappersEnd (); - Driver.WriteIfDifferent (HeaderPath, hdr.ToString () + "\n" + decls.ToString () + "\n" + ifaces.ToString () + "\n", true); - Driver.WriteIfDifferent (SourcePath, mthds.ToString () + "\n" + sb.ToString () + "\n", true); + Driver.WriteIfDifferent (App, HeaderPath, hdr.ToString () + "\n" + decls.ToString () + "\n" + ifaces.ToString () + "\n", true); + Driver.WriteIfDifferent (App, SourcePath, mthds.ToString () + "\n" + sb.ToString () + "\n", true); } public void ProcessMethod (MethodDefinition method) diff --git a/tools/common/PListExtensions.cs b/tools/common/PListExtensions.cs index 26ac6c7e745e..892e142eb61d 100644 --- a/tools/common/PListExtensions.cs +++ b/tools/common/PListExtensions.cs @@ -11,7 +11,7 @@ public static void LoadWithoutNetworkAccess (this XmlDocument doc, string filena using (var fs = new FileStream (filename, FileMode.Open, FileAccess.Read)) { var settings = new XmlReaderSettings () { XmlResolver = null, - DtdProcessing = DtdProcessing.Parse, + DtdProcessing = DtdProcessing.Ignore, }; using (var reader = XmlReader.Create (fs, settings)) { doc.Load (reader); @@ -24,7 +24,7 @@ public static void LoadXmlWithoutNetworkAccess (this XmlDocument doc, string xml using (var fs = new StringReader (xml)) { var settings = new XmlReaderSettings () { XmlResolver = null, - DtdProcessing = DtdProcessing.Parse, + DtdProcessing = DtdProcessing.Ignore, }; using (var reader = XmlReader.Create (fs, settings)) { doc.Load (reader); diff --git a/tools/common/PathUtils.cs b/tools/common/PathUtils.cs index 19dcc31df8fe..355253f5c2a7 100644 --- a/tools/common/PathUtils.cs +++ b/tools/common/PathUtils.cs @@ -38,7 +38,7 @@ static char ToOrdinalIgnoreCase (char c) return path; } - [DllImport ("/usr/lib/libc.dylib")] + [DllImport ("libc")] static extern IntPtr realpath (string path, IntPtr buffer); #if NET @@ -422,5 +422,25 @@ static bool IsLongPathsEnabledRegistry { } } } + + public static void CreateDirectoryForFile (string? file) + { +#if NET + if (string.IsNullOrEmpty (file)) +#else + if (string.IsNullOrEmpty (file) || file is null) +#endif + return; + + var dir = Path.GetDirectoryName (file); +#if NET + if (string.IsNullOrEmpty (dir)) +#else + if (string.IsNullOrEmpty (dir) || dir is null) +#endif + return; + + Directory.CreateDirectory (dir); + } } } diff --git a/tools/common/StaticRegistrar.cs b/tools/common/StaticRegistrar.cs index ad3102cb77fa..be257833d956 100644 --- a/tools/common/StaticRegistrar.cs +++ b/tools/common/StaticRegistrar.cs @@ -726,14 +726,14 @@ protected override bool LaxMode { } } - protected override void ReportError (int code, string message, params object [] args) + protected override void ReportError (int code, string message, params object? [] args) { throw ErrorHelper.CreateError (code, message, args); } - protected override void ReportWarning (int code, string message, params object [] args) + protected override void ReportWarning (int code, string message, params object? [] args) { - ErrorHelper.Show (ErrorHelper.CreateWarning (code, message, args)); + ErrorHelper.Show (App, ErrorHelper.CreateWarning (code, message, args)); } public static int GetValueTypeSize (TypeDefinition type) @@ -1591,7 +1591,7 @@ protected override IEnumerable GetProtocolMemberAttribu } #if !LEGACY_TOOLS - bool GetDotNetAvailabilityAttribute (ICustomAttribute ca, ApplePlatform currentPlatform, out Version? sdkVersion, out string? message) + public bool GetDotNetAvailabilityAttribute (ICustomAttribute ca, ApplePlatform currentPlatform, out Version? sdkVersion, out string? message) { var caType = ca.AttributeType; @@ -1601,6 +1601,7 @@ bool GetDotNetAvailabilityAttribute (ICustomAttribute ca, ApplePlatform currentP string supportedPlatformAndVersion; switch (ca.ConstructorArguments.Count) { case 1: + case 2: // second argument can be a message supportedPlatformAndVersion = (string) ca.ConstructorArguments [0].Value; break; default: @@ -1679,7 +1680,7 @@ bool CollectAvailabilityAttributes (IEnumerable attributes, ou return false; } - protected override Version? GetSdkIntroducedVersion (TypeReference obj, out string? message) + public override Version? GetSdkIntroducedVersion (TypeReference obj, out string? message) { TypeDefinition td = obj.Resolve (); @@ -2025,7 +2026,7 @@ public bool IsCustomType (ObjCType type) return false; } - bool IsPlatformType (TypeReference type) + public bool IsPlatformType (TypeReference type) { if (type.IsNested) return false; @@ -2101,11 +2102,8 @@ void CheckNamespace (string ns, List exceptions) namespaces.Add (ns); - if (App.IsSimulatorBuild && !App.IsFrameworkAvailableInSimulator (ns)) { - Driver.Log (5, "Not importing the framework {0} in the generated registrar code because it's not available in the simulator.", ns); - return; - } else if (Frameworks.GetFrameworks (App.Platform, false)?.TryGetValue (ns, out var fw) == true && fw.Unavailable) { - Driver.Log (5, "Not importing the framework {0} in the generated registrar code because it's not available in the current platform.", ns); + if (Driver.GetFrameworks (App).TryGetValue (ns, out var fw) && fw.IsFrameworkUnavailable (App)) { + App.Log (5, "Not importing the framework {0} in the generated registrar code because it's not available in the current platform.", ns); return; } @@ -2631,12 +2629,6 @@ static bool IsTypeCore (ObjCType type, string nsToMatch) static bool IsIntentsType (ObjCType type) => IsTypeCore (type, "Intents"); static bool IsExternalAccessoryType (ObjCType type) => IsTypeCore (type, "ExternalAccessory"); - bool IsTypeAllowedInSimulator (ObjCType type) - { - var ns = type.Type.Namespace; - return App.IsFrameworkAvailableInSimulator (ns); - } - class ProtocolInfo { public uint TokenReference; public ObjCType Protocol; @@ -2674,7 +2666,7 @@ public List SkippedTypes { public string GetInitializationMethodName (string? single_assembly) { - if (!string.IsNullOrEmpty (single_assembly)) { + if (!StringUtils.IsNullOrEmpty (single_assembly)) { return "xamarin_create_classes_" + single_assembly.Replace ('.', '_').Replace ('-', '_'); } else { return "xamarin_create_classes"; @@ -2688,24 +2680,13 @@ List GetAllTypes (List exceptions) return all_types; var allTypes = new List (); foreach (var @class in Types.Values) { - if (!string.IsNullOrEmpty (single_assembly) && single_assembly != @class.Type.Module.Assembly.Name.Name) + if (@class.Type is null) continue; - if (App.Platform != ApplePlatform.MacOSX) { - var isPlatformType = IsPlatformType (@class.Type); - if (isPlatformType && IsSimulatorOrDesktop && !IsTypeAllowedInSimulator (@class)) { - Driver.Log (5, "The static registrar won't generate code for {0} because its framework is not supported in the simulator.", @class.ExportedName); - continue; // Some types are not supported in the simulator. - } - } + if (!string.IsNullOrEmpty (single_assembly) && single_assembly != @class.Type.Module.Assembly.Name.Name) + continue; - // Xcode 15 removed NewsstandKit if (Driver.XcodeVersion.Major >= 15) { - if (IsTypeCore (@class, "NewsstandKit")) { - exceptions.Add (ErrorHelper.CreateWarning (4178, $"The class '{@class.Type.FullName}' will not be registered because the NewsstandKit framework has been removed from the {App.Platform} SDK.")); - continue; - } - if (@class.Type.Is ("PassKit", "PKDisbursementAuthorizationControllerDelegate") || @class.Type.Is ("PassKit", "IPKDisbursementAuthorizationControllerDelegate")) { exceptions.Add (ErrorHelper.CreateWarning (4189, $"The class '{@class.Type.FullName}' will not be registered it has been removed from the {App.Platform} SDK.")); continue; @@ -2715,21 +2696,11 @@ List GetAllTypes (List exceptions) exceptions.Add (ErrorHelper.CreateWarning (4189, $"The class '{@class.Type.FullName}' will not be registered it has been removed from the {App.Platform} SDK.")); continue; } - - if (Driver.XcodeVersion.Minor >= 3 || Driver.XcodeVersion.Major >= 16) { - // Xcode 15.3+ will remove AssetsLibrary - if (IsTypeCore (@class, "AssetsLibrary")) { - exceptions.Add (ErrorHelper.CreateWarning (4178, $"The class '{@class.Type.FullName}' will not be registered because the AssetsLibrary framework has been removed from the {App.Platform} SDK.")); - continue; - } - } } - if (Driver.XcodeVersion.Major >= 16) { - if (@class.Type.Namespace == "AssetsLibrary") { - exceptions.Add (ErrorHelper.CreateWarning (4190, $"The class '{@class.Type.FullName}' will not be registered because the {@class.Type.Namespace} framework has been deprecated from the {App.Platform} SDK.")); - continue; - } + if (Frameworks.TryGetFramework (App, @class.Type.Resolve (), out Framework? framework) && framework.IsFrameworkUnavailable (App)) { + exceptions.Add (ErrorHelper.CreateWarning (4178, $"The class '{@class.Type.FullName}' will not be registered because the {framework.Name} framework has been removed from the {App.Platform} SDK.")); + continue; } if (@class.IsFakeProtocol) @@ -2771,9 +2742,9 @@ public void Rewrite () var rewriter = new Rewriter (map_dict, GetAssemblies (), LinkContext); var result = rewriter.Process (); if (!string.IsNullOrEmpty (result)) { - Driver.Log (5, $"Not redirecting class handles because {result}"); + App.Log (5, $"Not redirecting class handles because {result}"); } - ErrorHelper.ThrowIfErrors (exceptions); + ErrorHelper.ThrowIfErrors (App, exceptions); } #endif } @@ -2816,7 +2787,7 @@ void Specialize (AutoIndentStringBuilder sb, out string initialization_method) // Select the types that needs to be registered. var allTypes = GetAllTypes (exceptions); - if (string.IsNullOrEmpty (single_assembly)) { + if (StringUtils.IsNullOrEmpty (single_assembly)) { foreach (var assembly in GetAssemblies ()) registered_assemblies.Add (new (assembly, GetAssemblyName (assembly))); } else { @@ -3230,7 +3201,7 @@ void Specialize (AutoIndentStringBuilder sb, out string initialization_method) sb.WriteLine (map.ToString ()); sb.WriteLine (map_init.ToString ()); - ErrorHelper.ThrowIfErrors (exceptions); + ErrorHelper.ThrowIfErrors (App, exceptions); } bool TryGetIntPtrBoolCtor (TypeDefinition type, List exceptions, [NotNullWhen (true)] out MethodDefinition? ctor) @@ -4429,11 +4400,11 @@ void SpecializePrepareReturnValue (AutoIndentStringBuilder sb, ObjCMethod method var token = "INVALID_TOKEN_REF"; if (App.Optimizations.OptimizeBlockLiteralSetupBlock == true) { if (type.Is ("System", "Delegate") || type.Is ("System", "MulticastDelegate")) { - ErrorHelper.Show (ErrorHelper.CreateWarning (App, 4173, method.Method, Errors.MT4173, type.FullName, descriptiveMethodName)); + ErrorHelper.Show (App, ErrorHelper.CreateWarning (App, 4173, method.Method, Errors.MT4173, type.FullName, descriptiveMethodName)); } else { var delegateMethod = type.Resolve ().GetMethods ().FirstOrDefault ((v) => v.Name == "Invoke"); if (delegateMethod is null) { - ErrorHelper.Show (ErrorHelper.CreateWarning (App, 4173, method.Method, Errors.MT4173_A, type.FullName, descriptiveMethodName)); + ErrorHelper.Show (App, ErrorHelper.CreateWarning (App, 4173, method.Method, Errors.MT4173_A, type.FullName, descriptiveMethodName)); } else { signature = "\"" + ComputeSignature (method.DeclaringType.Type, null, method, isBlockSignature: true) + "\""; } @@ -4718,7 +4689,7 @@ public bool TryFindMethod (MethodDefinition method, [NotNullWhen (true)] out Obj // One common variation is that the IDE will add the BlockProxy attribute found in base methods when the user overrides those methods, // which unfortunately doesn't compile (because the type passed to the BlockProxy attribute is internal), and then // the user just modifies the attribute to something that compiles. - ErrorHelper.Show (ErrorHelper.CreateWarning (App, 4175, method, $"{(string.IsNullOrEmpty (param.Name) ? $"Parameter #{param.Index + 1}" : $"The parameter '{param.Name}'")} in the method '{GetTypeFullName (method.DeclaringType)}.{GetDescriptiveMethodName (method)}' has an invalid BlockProxy attribute (the type passed to the attribute does not have a 'Create' method).")); + ErrorHelper.Show (App, ErrorHelper.CreateWarning (App, 4175, method, $"{(string.IsNullOrEmpty (param.Name) ? $"Parameter #{param.Index + 1}" : $"The parameter '{param.Name}'")} in the method '{GetTypeFullName (method.DeclaringType)}.{GetDescriptiveMethodName (method)}' has an invalid BlockProxy attribute (the type passed to the attribute does not have a 'Create' method).")); // Returning null will make the caller look for the attribute in the base implementation. } return createMethod; @@ -4995,7 +4966,7 @@ void GenerateConversionToManaged (TypeReference inputType, TypeReference outputT func = GetNSStringToSmartEnumFunc (underlyingManagedType, inputType, outputType, descriptiveMethodName, managedClassExpression, out nativeTypeName); if (!IsSmartEnum (underlyingManagedType, out var _, out var getValueMethod)) { // method linked away!? this should already be verified - ErrorHelper.Show (ErrorHelper.CreateWarning (99, Errors.MX0099, $"the smart enum {underlyingManagedType.FullName} doesn't seem to be a smart enum after all")); + ErrorHelper.Show (App, ErrorHelper.CreateWarning (99, Errors.MX0099, $"the smart enum {underlyingManagedType.FullName} doesn't seem to be a smart enum after all")); token = "INVALID_TOKEN_REF"; } else if (TryCreateTokenReference (getValueMethod, TokenType.Method, out var get_value_method_token_ref, out _)) { token = $"0x{get_value_method_token_ref:X} /* {getValueMethod.FullName} */"; @@ -5091,7 +5062,7 @@ void GenerateConversionToNative (TypeReference inputType, TypeReference outputTy func = GetSmartEnumToNSStringFunc (underlyingManagedType, inputType, outputType, descriptiveMethodName, classVariableName); if (!IsSmartEnum (underlyingManagedType, out var getConstantMethod, out var _)) { // method linked away!? this should already be verified - ErrorHelper.Show (ErrorHelper.CreateWarning (99, Errors.MX0099, $"the smart enum {underlyingManagedType.FullName} doesn't seem to be a smart enum after all")); + ErrorHelper.Show (App, ErrorHelper.CreateWarning (99, Errors.MX0099, $"the smart enum {underlyingManagedType.FullName} doesn't seem to be a smart enum after all")); token = "INVALID_TOKEN_REF"; } else if (TryCreateTokenReference (getConstantMethod, TokenType.Method, out var get_constant_method_token_ref, out _)) { token = $"0x{get_constant_method_token_ref:X} /* {getConstantMethod.FullName} */"; @@ -5369,7 +5340,7 @@ string TryGeneratePInvokeWrapper (PInvokeWrapperGenerator state, MethodDefinitio sb.WriteLine ("}"); sb.WriteLine (); } else { - // Console.WriteLine ("Signature already processed: {0} for {1}.{2}", signature.ToString (), method.DeclaringType.FullName, method.Name); + // App.Log ("Signature already processed: {0} for {1}.{2}", signature.ToString (), method.DeclaringType.FullName, method.Name); } return wrapperName; @@ -5412,7 +5383,7 @@ public void Register (PlatformResolver? resolver, IEnumerable= 0) { // we want to get the space before `[` too. @@ -380,6 +372,14 @@ static string RemovePathAtEnd (string line) return line; } + + // This function only exists because netstandard2.0's version doesn't have the [NotNullWhen] attribute, + // which makes nullability analysis somewhat annoying. This function can be removed and callsites updated + // to call string.IsNullOrEmpty directly once we stop targeting netstandard2.0. + public static bool IsNullOrEmpty ([NotNullWhen (false)] string? s) + { + return string.IsNullOrEmpty (s); + } } static class StringExtensions { @@ -397,5 +397,14 @@ internal static T [] CopyAndAdd (this T [] array, T value) tmpArray [tmpArray.Length - 1] = value; return tmpArray; } + +#if !NET + public static bool EndsWith (this string s, char value) + { + if (s.Length == 0) + return false; + return s [s.Length - 1] == value; + } +#endif } } diff --git a/tools/common/Symbols.cs b/tools/common/Symbols.cs index 7306afd5fa2f..6b1b13077fe5 100644 --- a/tools/common/Symbols.cs +++ b/tools/common/Symbols.cs @@ -27,7 +27,7 @@ public class Symbol { public bool Ignore; public Abi? ValidAbis; - static string ObjectiveCPrefix { + public static string ObjectiveCPrefix { get { return "OBJC_CLASS_$_"; } @@ -52,11 +52,7 @@ public string Name { } public string? ObjectiveCName; - public string Prefix { - get { - return "_"; - } - } + public const string Prefix = "_"; List members = new List (); public IEnumerable Members { get { return members; } } @@ -158,6 +154,7 @@ public Symbol this [string name] { } } +#if !MSBUILD_TASKS public void Load (string filename, Application app) { using (var reader = new StreamReader (filename)) { @@ -183,6 +180,7 @@ public void Load (string filename, Application app) } } } +#endif // !MSBUILD_TASKS public void Save (string filename) { diff --git a/tools/common/Target.cs b/tools/common/Target.cs index 0121e834ad14..b4899f762554 100644 --- a/tools/common/Target.cs +++ b/tools/common/Target.cs @@ -33,22 +33,25 @@ public partial class Application { #else public PlatformLinkContext LinkContext; #endif - public PlatformResolver Resolver = new PlatformResolver (); + public PlatformResolver Resolver; internal StaticRegistrar StaticRegistrar { get; set; } +#if !LEGACY_TOOLS public Assembly AddAssembly (AssemblyDefinition assembly) { var asm = new Assembly (this, assembly); Assemblies.Add (asm); return asm; } +#endif // !LEGACY_TOOLS public PlatformLinkContext? GetLinkContext () { return LinkContext; } +#if !LEGACY_TOOLS public void ExtractNativeLinkInfo (List exceptions) { foreach (var a in Assemblies) { @@ -59,11 +62,12 @@ public void ExtractNativeLinkInfo (List exceptions) } } } +#endif // !LEGACY_TOOLS - [DllImport (Constants.libSystemLibrary, SetLastError = true)] + [DllImport ("libc", SetLastError = true)] static extern string realpath (string path, IntPtr zero); - public static string GetRealPath (string path, bool warnIfNoSuchPathExists = true) + public static string GetRealPath (IToolLog log, string path, bool warnIfNoSuchPathExists = true) { // For some reason realpath doesn't always like filenames only, and will randomly fail. // Prepend the current directory if there's no directory specified. @@ -76,118 +80,17 @@ public static string GetRealPath (string path, bool warnIfNoSuchPathExists = tru var errno = Marshal.GetLastWin32Error (); if (warnIfNoSuchPathExists || (errno != 2)) - ErrorHelper.Warning (54, Errors.MT0054, path, FileCopier.strerror (errno), errno); + ErrorHelper.Warning (log, 54, Errors.MT0054, path, FileCopier.strerror (errno), errno); return path; } - public void ValidateAssembliesBeforeLink () - { - if (App.AreAnyAssembliesTrimmed) { - foreach (Assembly assembly in Assemblies) { - if ((assembly.AssemblyDefinition.MainModule.Attributes & ModuleAttributes.ILOnly) == 0) - throw ErrorHelper.CreateError (2014, Errors.MT2014, assembly.AssemblyDefinition.MainModule.FileName); - } - } - } - +#if !LEGACY_TOOLS public void ComputeLinkerFlags () { foreach (var a in Assemblies) a.ComputeLinkerFlags (); } - - public void GatherFrameworks () - { - Assembly? asm = null; - - foreach (var assembly in Assemblies) { - if (assembly.AssemblyDefinition.Name.Name == Driver.GetProductAssembly (App)) { - asm = assembly; - break; - } - } - - if (asm is null) - throw ErrorHelper.CreateError (99, Errors.MX0099, $"could not find the product assembly {Driver.GetProductAssembly (App)} in the list of assemblies referenced by the executable"); - - AssemblyDefinition productAssembly = asm.AssemblyDefinition; - - // *** make sure any change in the above lists (or new list) are also reflected in - // *** Makefile so simlauncher-sgen does not miss any framework - - var processed = new HashSet (); - var v80 = new Version (8, 0); - - foreach (ModuleDefinition md in productAssembly.Modules) { - foreach (TypeDefinition td in md.Types) { - // process only once each namespace (as we keep adding logic below) - string nspace = td.Namespace; -#if !XAMCORE_5_0 - // AVCustomRoutingControllerDelegate was incorrectly placed in AVKit - if (td.Is ("AVKit", "AVCustomRoutingControllerDelegate")) - nspace = "AVRouting"; -#endif - - if (processed.Contains (nspace)) - continue; - processed.Add (nspace); - - if (Driver.GetFrameworks (App).TryGetValue (nspace, out var framework) && framework is not null) { - // framework specific processing - switch (framework.Name) { - case "Metal": - case "MetalKit": - case "MetalPerformanceShaders": - case "PHASE": - case "ThreadNetwork": - // some frameworks do not exists on simulators and will result in linker errors if we include them - if (App.IsSimulatorBuild) - continue; - break; - case "NewsstandKit": - if (Driver.XcodeVersion.Major >= 15) { - Driver.Log (3, "Not linking with the framework {0} because it's not available when using Xcode 15+.", framework.Name); - continue; - } - break; - case "AssetsLibrary": - if (Driver.XcodeVersion.Major >= 16 || (Driver.XcodeVersion.Major == 15 && Driver.XcodeVersion.Minor >= 3)) { - Driver.Log (3, "Not linking with the framework {0} because it's not available when using Xcode 15.3+.", framework.Name); - continue; - } - break; - default: - if (App.IsSimulatorBuild && !App.IsFrameworkAvailableInSimulator (framework.Name)) { - if (App.AreAnyAssembliesTrimmed) { - ErrorHelper.Warning (5223, Errors.MX5223, framework.Name, App.PlatformName); - } else { - Driver.Log (3, Errors.MX5223, framework.Name, App.PlatformName); - } - continue; - } - break; - } - - if (framework.Unavailable) { - ErrorHelper.Warning (181, Errors.MX0181 /* Not linking with the framework {0} (used by the type {1}) because it's not available on the current platform ({2}). */, framework.Name, td.FullName, App.PlatformName); - continue; - } - - if (App.SdkVersion >= framework.Version) { - var add_to = framework.AlwaysWeakLinked || App.DeploymentTarget < framework.Version ? asm.WeakFrameworks : asm.Frameworks; - add_to.Add (framework.Name); - continue; - } else { - Driver.Log (3, "Not linking with the framework {0} (used by the type {1}) because it was introduced in {2} {3}, and we're using the {2} {4} SDK.", framework.Name, td.FullName, App.PlatformName, framework.Version, App.SdkVersion); - } - } - } - } - - // Make sure there are no duplicates between frameworks and weak frameworks. - // Keep the weak ones. - asm.Frameworks.ExceptWith (asm.WeakFrameworks); - } +#endif // !LEGACY_TOOLS #if !LEGACY_TOOLS internal string? GenerateReferencingSource (string reference_m, IEnumerable symbols) @@ -232,7 +135,7 @@ public void GatherFrameworks () sb.AppendLine ("}"); sb.AppendLine (); - Driver.WriteIfDifferent (reference_m, sb.ToString (), true); + Driver.WriteIfDifferent (App, reference_m, sb.ToString (), true); return reference_m; } @@ -290,7 +193,7 @@ public void GenerateMain (StringBuilder sb, ApplePlatform platform, Abi abi, str throw ErrorHelper.CreateError (71, Errors.MX0071, platform, App.ProductName); } } - Driver.WriteIfDifferent (main_source, sb.ToString (), true); + Driver.WriteIfDifferent (App, main_source, sb.ToString (), true); } catch (ProductException) { throw; } catch (Exception e) { @@ -412,7 +315,7 @@ void GenerateMainImpl (StringWriter sw, Abi abi) sw.WriteLine ("\txamarin_executable_name = \"{0}\";", assembly_name); if (app.XamarinRuntime == XamarinRuntime.MonoVM) sw.WriteLine ("\tmono_use_llvm = {0};", enable_llvm ? "TRUE" : "FALSE"); - sw.WriteLine ("\txamarin_log_level = {0};", Driver.Verbosity.ToString (CultureInfo.InvariantCulture)); + sw.WriteLine ("\txamarin_log_level = {0};", Verbosity.ToString (CultureInfo.InvariantCulture)); sw.WriteLine ("\txamarin_arch_name = \"{0}\";", abi.AsArchString ()); if (!app.IsDefaultMarshalManagedExceptionMode) sw.WriteLine ("\txamarin_marshal_managed_exception_mode = MarshalManagedExceptionMode{0};", app.MarshalManagedExceptions); diff --git a/tools/common/cache.cs b/tools/common/cache.cs index 1b6b7130ec2c..1dcba0073ef9 100644 --- a/tools/common/cache.cs +++ b/tools/common/cache.cs @@ -33,116 +33,79 @@ public bool IsCacheTemporary { } // see --cache=DIR - public string Location { - get { - if (cache_dir is null) { - do { - cache_dir = Path.Combine (Path.GetTempPath (), NAME + ".cache", Path.GetRandomFileName ()); - if (File.Exists (cache_dir) || Directory.Exists (cache_dir)) - continue; - Directory.CreateDirectory (cache_dir); - break; - } while (true); + public string GetLocation (IToolLog log) + { + if (cache_dir is null) { + do { + cache_dir = Path.Combine (Path.GetTempPath (), NAME + ".cache", Path.GetRandomFileName ()); + if (File.Exists (cache_dir) || Directory.Exists (cache_dir)) + continue; + Directory.CreateDirectory (cache_dir); + break; + } while (true); - cache_dir = Application.GetRealPath (cache_dir); + cache_dir = Application.GetRealPath (log, cache_dir); - temporary_cache = true; - if (!Directory.Exists (cache_dir)) - Directory.CreateDirectory (cache_dir); -#if DEBUG - Console.WriteLine ("Cache defaults to {0}", cache_dir); -#endif - } - return cache_dir; - } - set { - cache_dir = value; + temporary_cache = true; if (!Directory.Exists (cache_dir)) Directory.CreateDirectory (cache_dir); - cache_dir = Application.GetRealPath (Path.GetFullPath (cache_dir)); +#if DEBUG + log.Log ("Cache defaults to {0}", cache_dir); +#endif } + return cache_dir; } - public void Clean () + public void SetLocation (IToolLog log, string value) { -#if DEBUG - Console.WriteLine ("Cache.Clean: {0}", Location); -#endif - Directory.Delete (Location, true); - Directory.CreateDirectory (Location); + cache_dir = value; + if (!Directory.Exists (cache_dir)) + Directory.CreateDirectory (cache_dir); + cache_dir = Application.GetRealPath (log, Path.GetFullPath (cache_dir)); } - public static bool CompareDirectories (string a, string b, bool ignore_cache = false) + public void Clean (IToolLog log) { - if (Driver.Force && !ignore_cache) { - Driver.Log (6, "Directories {0} and {1} are considered different because -f was passed to " + NAME + ".", a, b); - return false; - } - - var diff = new StringBuilder (); - if (Driver.RunCommand ("diff", new [] { "-ur", a, b, }, output: diff, suppressPrintOnErrors: true) != 0) { - Driver.Log (1, "Directories {0} and {1} are considered different because diff said so:\n{2}", a, b, diff); - return false; - } - - return true; + var location = GetLocation (log); +#if DEBUG + log.Log ("Cache.Clean: {0}", location); +#endif + Directory.Delete (location, true); + Directory.CreateDirectory (location); } - public static bool CompareFiles (string a, string b, bool ignore_cache = false) + public static bool CompareFiles (IToolLog log, string a, string b, bool ignore_cache = false) { if (Driver.Force && !ignore_cache) { - Driver.Log (6, "Files {0} and {1} are considered different because -f was passed to " + NAME + ".", a, b); + log.Log (6, "Files {0} and {1} are considered different because -f was passed to " + NAME + ".", a, b); return false; } if (!File.Exists (b)) { - Driver.Log (6, "Files {0} and {1} are considered different because the latter doesn't exist.", a, b); + log.Log (6, "Files {0} and {1} are considered different because the latter doesn't exist.", a, b); return false; } using (var astream = new FileStream (a, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var bstream = new FileStream (b, FileMode.Open, FileAccess.Read, FileShare.Read)) { bool rv; - Driver.Log (6, "Comparing files {0} and {1}...", a, b); - rv = CompareStreams (astream, bstream, ignore_cache); - Driver.Log (6, " > {0}", rv ? "Identical" : "Different"); + log.Log (6, "Comparing files {0} and {1}...", a, b); + rv = CompareStreams (log, astream, bstream, ignore_cache); + log.Log (6, " > {0}", rv ? "Identical" : "Different"); return rv; } } } - public static bool CompareAssemblies (string a, string b, bool ignore_cache = false, bool compare_guids = false) + public unsafe static bool CompareStreams (IToolLog log, Stream astream, Stream bstream, bool ignore_cache = false) { if (Driver.Force && !ignore_cache) { - Driver.Log (6, "Assemblies {0} and {1} are considered different because -f was passed to " + NAME + ".", a, b); - return false; - } - - if (!File.Exists (b)) { - Driver.Log (6, "Assemblies {0} and {1} are considered different because the latter doesn't exist.", a, b); - return false; - } - - using (var astream = new AssemblyReader (a) { CompareGUIDs = compare_guids }) { - using (var bstream = new AssemblyReader (b) { CompareGUIDs = compare_guids }) { - bool rv; - Driver.Log (6, "Comparing assemblies {0} and {1}...", a, b); - rv = CompareStreams (astream, bstream, ignore_cache); - Driver.Log (6, " > {0}", rv ? "Identical" : "Different"); - return rv; - } - } - } - - public unsafe static bool CompareStreams (Stream astream, Stream bstream, bool ignore_cache = false) - { - if (Driver.Force && !ignore_cache) { - Driver.Log (6, " > streams are considered different because -f was passed to " + NAME + "."); + log.Log (6, " > streams are considered different because -f was passed to " + NAME + "."); return false; } if (astream.Length != bstream.Length) { - Driver.Log (6, " > streams are considered different because their lengths do not match."); + log.Log (6, " > streams are considered different because their lengths do not match."); return false; } @@ -190,20 +153,20 @@ void CollectArgumentsForCache (IList args, int firstArgument, StringBuil public bool IsCacheValid (Application app) { var name = "arguments"; - var pcache = Path.Combine (Location, name); + var pcache = Path.Combine (GetLocation (app), name); if (!File.Exists (pcache)) { - Driver.Log (3, "A full rebuild will be performed because the cache is either incomplete or entirely missing."); + app.Log (3, "A full rebuild will be performed because the cache is either incomplete or entirely missing."); return false; } else if (GetArgumentsForCacheData (app) != File.ReadAllText (pcache)) { - Driver.Log (3, "A full rebuild will be performed because the arguments to " + NAME + " has changed with regards to the cached data."); + app.Log (3, "A full rebuild will be performed because the arguments to " + NAME + " has changed with regards to the cached data."); return false; } // Check if mtouch/mmp has been modified. var executable = System.Reflection.Assembly.GetExecutingAssembly ().Location; - if (!Application.IsUptodate (executable, pcache)) { - Driver.Log (3, "A full rebuild will be performed because " + NAME + " has been modified."); + if (!Application.IsUptodate (app, executable, pcache)) { + app.Log (3, "A full rebuild will be performed because " + NAME + " has been modified."); return false; } @@ -213,7 +176,7 @@ public bool IsCacheValid (Application app) public bool VerifyCache (Application app) { if (!IsCacheValid (app)) { - Clean (); + Clean (app); return false; } @@ -223,270 +186,7 @@ public bool VerifyCache (Application app) public void ValidateCache (Application app) { var name = "arguments"; - var pcache = Path.Combine (Location, name); + var pcache = Path.Combine (GetLocation (app), name); File.WriteAllText (pcache, GetArgumentsForCacheData (app)); } - - // A stream that reads an assembly and skips the header and the GUID table. - class AssemblyReader : Stream { - string filename; - FileStream stream; - long guid_table_start; - long guid_table_length; - - public bool CompareGUIDs; - - public AssemblyReader (string filename) - { - this.filename = filename; - - // Need to figure out where the #GUID table is so we can ignore it. - FindGUIDTable (); - - stream = File.OpenRead (filename); - } - - public override int Read (byte [] buffer, int offset, int count) - { - // read the header, always the same 136 bytes, followed by a 4 bytes timestamp (which we must ignore) - // the rest (except the #GUID table) is safe to compare. - if (stream.Position < 136) { - // read the first 136 bytes - int read = stream.Read (buffer, offset, 136 - (int) stream.Position); - if (stream.Position == 136) { - // skip the timestamp - stream.Position += 4; - // this prints the timestamp: - // byte[] buf = new byte[4]; - // stream.Read (buf, 0, 4); - // int t2 = (buf [3] << 24) + (buf [2] << 16) + (buf [1] << 8) + buf [0]; - // var d = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - // var d2 = d.AddSeconds (t2); - // Console.WriteLine ("TS of {1}: {0}", d2, filename); - } - return read; // don't bother reading more, this makes the implementation easier. - } - - if (CompareGUIDs) - return stream.Read (buffer, offset, count); - - if (stream.Position + count < guid_table_start) { - // entire read before guid table - return stream.Read (buffer, offset, count); - } else if (stream.Position >= guid_table_start + guid_table_length) { - // entire read after guid table - return stream.Read (buffer, offset, count); - } else { - int read = 0; - // read up intil guid table - read = stream.Read (buffer, offset, (int) (guid_table_start - stream.Position)); - // skip guid table - stream.Position += guid_table_length; - // read after guid table - if (count - read > 0) - read += stream.Read (buffer, offset + read, count - read); - return read; - } - } - - void FindGUIDTable () - { - using (var fs = File.OpenRead (filename)) { - using (var str = new BinaryReader (fs)) { - str.BaseStream.Position = 0; - if (str.ReadByte () != 0x4d || str.ReadByte () != 0x5a) - return; // MZ header - - str.BaseStream.Position = 0x80; - if (str.ReadByte () != 'P' || str.ReadByte () != 'E' || str.ReadByte () != 0 || str.ReadByte () != 0) - return; // PE signature ("PE\0\0") - - // Read the PE file header - - if (str.ReadByte () != 0x4c || str.ReadByte () != 0x01) - return; // PE file header -> Machine (always 0x014c) - - ushort sectionCount = str.ReadUInt16 (); - str.BaseStream.Position += 12; - ushort optionalHeaderSize = str.ReadUInt16 (); - if (optionalHeaderSize < 224) - return; // optional header is not big enough - - str.BaseStream.Position += 2; - - // Read the optional PE header - str.BaseStream.Position += 208; - int cliHeaderRVA = str.ReadInt32 (); - /*int cliHeaderSize = */ - str.ReadInt32 (); - - str.BaseStream.Position += 8; - - // Read the sections, looking for the ".text" section. - int sectionHeaderPosition = (int) str.BaseStream.Position; - int textSectionPosition = -1; - uint virtualAddress = uint.MaxValue; - uint pointerToRawData = 0; - for (int i = 0; i < sectionCount; i++) { - str.BaseStream.Position = sectionHeaderPosition + 40 * i; - if (str.ReadByte () != '.' || str.ReadByte () != 't' || str.ReadByte () != 'e' || str.ReadByte () != 'x' || str.ReadByte () != 't' || str.ReadByte () != 0) - continue; - - textSectionPosition = sectionHeaderPosition + 40 * i; - str.BaseStream.Position = textSectionPosition + 12; - virtualAddress = str.ReadUInt32 (); - str.BaseStream.Position += 4; - pointerToRawData = str.ReadUInt32 (); - break; - } - - if (virtualAddress == uint.MaxValue) - return; - - // Now we can calculate the file position of the CLI header - str.BaseStream.Position = cliHeaderRVA - (virtualAddress - pointerToRawData); - str.BaseStream.Position += 8; - uint metadataRVA = str.ReadUInt32 (); - /*uint metadataSize = */ - str.ReadUInt32 (); - - // Find and read the metadata header - uint metadataRootPosition = metadataRVA - (virtualAddress - pointerToRawData); - str.BaseStream.Position = metadataRootPosition; - if (str.ReadByte () != 0x42 || str.ReadByte () != 0x53 || str.ReadByte () != 0x4a || str.ReadByte () != 0x42) - return; // Invalid magic signature. - - str.BaseStream.Position += 8; - int dynamicLength = str.ReadInt32 (); - str.BaseStream.Position += dynamicLength; - str.BaseStream.Position += 2; // flags - ushort metadataStreams = str.ReadUInt16 (); - for (ushort i = 0; i < metadataStreams; i++) { - uint offset = str.ReadUInt32 (); - uint size = str.ReadUInt32 (); - byte [] name = new byte [32]; - - for (int k = 0; k < 8; k++) { - str.Read (name, k * 4, 4); - if (name [k * 4 + 3] == 0) - break; - } - - if (name [0] == '#' && name [1] == 'G' && name [2] == 'U' && name [3] == 'I' && name [4] == 'D' && name [5] == 0) { - // found the GUID table. - guid_table_start = metadataRootPosition + offset; - guid_table_length = size; - return; - } - } - } - } - } - - protected override void Dispose (bool disposing) - { - base.Dispose (disposing); - stream.Dispose (); - } - - public override void Flush () - { - throw new NotImplementedException (); - } - - public override long Seek (long offset, SeekOrigin origin) - { - throw new NotImplementedException (); - } - - public override void SetLength (long value) - { - throw new NotImplementedException (); - } - - public override void Write (byte [] buffer, int offset, int count) - { - throw new NotImplementedException (); - } - - public override bool CanRead { - get { - throw new NotImplementedException (); - } - } - - public override bool CanSeek { - get { - throw new NotImplementedException (); - } - } - - public override bool CanWrite { - get { - throw new NotImplementedException (); - } - } - - public override long Length { - get { - return stream.Length - 140 - guid_table_length; - } - } - - public override long Position { - get { - throw new NotImplementedException (); - } - set { - throw new NotImplementedException (); - } - } - } - -#if false - static public void ComputeDependencies (IEnumerable assemblies, MonoTouchResolver resolver) - { - // note: Parallel.ForEach (with lock to add on 'digests') turns out (much) slower - // (linksdk.app with 20 assemblies) - // likely because it's faster (using commoncrypto) than it seems - foreach (string a in assemblies) { - string key = Path.GetFileNameWithoutExtension (a); - using (Stream fs = File.OpenRead (a)) { - string digest = ComputeDigest (fs, 140); - digests.Add (key, digest); - } - } - - Dictionary> dependencies = new Dictionary> (); - foreach (string a in assemblies) { - HashSet references; - AssemblyDefinition ad = resolver.Load (a); - foreach (AssemblyNameReference ar in ad.MainModule.AssemblyReferences) { - if (!dependencies.TryGetValue (ar.Name, out references)) { - references = new HashSet (); - dependencies.Add (ar.Name, references); - } - references.Add (ad.Name.Name); - } - } -#if DEBUG - foreach (var kvp in dependencies) { - Console.WriteLine ("The following assemblies depends on {0}", kvp.Key); - foreach (var s in kvp.Value) - Console.WriteLine ("\t{0}", s); - } -#endif - // if a dependency has changed everything that depends on it must be cleaned - foreach (var kvp in dependencies) { - string cname = kvp.Key + ".*.cache." + GetDigestForAssembly (kvp.Key) + ".o"; - var files = Directory.GetFiles (Location, cname); - if (files.Length != 0) - continue; - - Clean (kvp.Key + "*"); - foreach (var deps in kvp.Value) - Clean (deps + "*"); - } - } -#endif } diff --git a/tools/common/create-makefile-fragment.sh b/tools/common/create-makefile-fragment.sh index 076245d65ca2..d436c538b039 100755 --- a/tools/common/create-makefile-fragment.sh +++ b/tools/common/create-makefile-fragment.sh @@ -33,13 +33,15 @@ fi PROJECT_FILE="$1" PROJECT=$(basename -s .csproj "$PROJECT_FILE") PROJECT_DIR=$(dirname "$PROJECT_FILE") -FRAGMENT_PATH="$2" +FINAL_FRAGMENT_PATH="$2" REFERENCES_PATH=$(pwd)/$PROJECT-references.txt -if test -z "$FRAGMENT_PATH"; then - FRAGMENT_PATH=$PROJECT_FILE.inc +if test -z "$FINAL_FRAGMENT_PATH"; then + FINAL_FRAGMENT_PATH=$PROJECT_FILE.inc fi +FRAGMENT_PATH="$FINAL_FRAGMENT_PATH.$$.tmp" + BUILD_EXECUTABLE="dotnet build" if ! dotnet --version >& /dev/null; then @@ -59,6 +61,7 @@ fi function upon_exit () { rm -f "$PROJECT_DIR/ProjectInspector.csproj" + rm -f "$FRAGMENT_PATH" } trap upon_exit EXIT cp ProjectInspector.csproj "$PROJECT_DIR" @@ -89,6 +92,7 @@ function delete_tmpproj if test -n "$TMPPROJ"; then rm -f "$TMPPROJ" fi + rm -f "$FRAGMENT_PATH" } trap delete_tmpproj EXIT trap delete_tmpproj ERR @@ -138,5 +142,7 @@ if test -z "$ABSOLUTE_PATHS"; then sed "${SED_INPLACE_FLAGS[@]}" "s@$PROJECT_DIR/@@" "$FRAGMENT_PATH" fi +mv "$FRAGMENT_PATH" "$FINAL_FRAGMENT_PATH" + # Cleanup rm -f "${INPUT_PATHS[@]}" diff --git a/tools/create-dotnet-linker-launch-json/Program.cs b/tools/create-dotnet-linker-launch-json/Program.cs index 9a27932c4b8c..9abba7f86cd5 100644 --- a/tools/create-dotnet-linker-launch-json/Program.cs +++ b/tools/create-dotnet-linker-launch-json/Program.cs @@ -68,7 +68,7 @@ static int Main (string [] args) } - var relevantRecords = records.Where (v => v?.Args?.BuildEventContext?.TaskId == tsea.BuildEventContext.TaskId).Select (v => v.Args).ToArray (); + var relevantRecords = records.Where (v => v?.Args?.BuildEventContext?.TaskId == tsea.BuildEventContext?.TaskId).Select (v => v.Args).ToArray (); var cla = relevantRecords.Where (v => v is BuildMessageEventArgs).Cast ().Where (v => v?.ToString ()?.Contains ("CommandLineArguments") == true).ToArray (); foreach (var rr in relevantRecords) { if (rr is TaskCommandLineEventArgs tclea) { diff --git a/tools/create-dotnet-linker-launch-json/create-dotnet-linker-launch-json.csproj b/tools/create-dotnet-linker-launch-json/create-dotnet-linker-launch-json.csproj index 5e249415c463..628dfa2c197c 100644 --- a/tools/create-dotnet-linker-launch-json/create-dotnet-linker-launch-json.csproj +++ b/tools/create-dotnet-linker-launch-json/create-dotnet-linker-launch-json.csproj @@ -5,7 +5,6 @@ net$(BundledNETCoreAppTargetFrameworkVersion) create_dotnet_linker_launch_json enable - enable diff --git a/tools/devops/README.md b/tools/devops/README.md index 07f4895e8b88..965673046212 100644 --- a/tools/devops/README.md +++ b/tools/devops/README.md @@ -301,7 +301,7 @@ testConfigurations: - label: framework # Framework tests - label: generator # Binding generator tests - label: introspection # Runtime introspection tests - - label: linker # Linker tests + - label: linker # Linker tests (split by platform) - label: monotouch # MonoTouch tests (split by platform) - label: msbuild # MSBuild tests - label: sharpie # Sharpie tests diff --git a/tools/devops/automation/build-pipeline.yml b/tools/devops/automation/build-pipeline.yml index d3e3f8b93895..97824c8abe3b 100644 --- a/tools/devops/automation/build-pipeline.yml +++ b/tools/devops/automation/build-pipeline.yml @@ -45,7 +45,7 @@ resources: - repository: yaml-templates type: git name: xamarin.yaml-templates - ref: e30b445c2ffcbebe75efdd69546d7196a20c5a43 + ref: refs/heads/main - repository: CustomPipelineTemplates type: git diff --git a/tools/devops/automation/build-pull-request.yml b/tools/devops/automation/build-pull-request.yml index b6e7f76620cf..8d71f0ad7231 100644 --- a/tools/devops/automation/build-pull-request.yml +++ b/tools/devops/automation/build-pull-request.yml @@ -36,7 +36,7 @@ resources: - repository: yaml-templates type: git name: xamarin.yaml-templates - ref: e30b445c2ffcbebe75efdd69546d7196a20c5a43 + ref: refs/heads/main - repository: CustomPipelineTemplates type: git diff --git a/tools/devops/automation/publish-pr-html-results.yml b/tools/devops/automation/publish-pr-html-results.yml index c1b7f08c1b2b..254babc35993 100644 --- a/tools/devops/automation/publish-pr-html-results.yml +++ b/tools/devops/automation/publish-pr-html-results.yml @@ -14,7 +14,7 @@ resources: - repository: yaml-templates type: git name: xamarin.yaml-templates - ref: e30b445c2ffcbebe75efdd69546d7196a20c5a43 + ref: refs/heads/main # we need all stages to be completed, else we do not have the test results, this trigger is just for CI, because we have # but because we have device issues, and it needs to be gree to trigger, we will deal with it later diff --git a/tools/devops/automation/run-nightly-codeql.yml b/tools/devops/automation/run-nightly-codeql.yml index 1e4144a6028e..f5375ab46ea2 100644 --- a/tools/devops/automation/run-nightly-codeql.yml +++ b/tools/devops/automation/run-nightly-codeql.yml @@ -21,7 +21,7 @@ resources: - repository: yaml-templates type: git name: xamarin.yaml-templates - ref: e30b445c2ffcbebe75efdd69546d7196a20c5a43 + ref: refs/heads/main variables: - template: /tools/devops/automation/templates/variables/common.yml diff --git a/tools/devops/automation/scripts/GitHub.psm1 b/tools/devops/automation/scripts/GitHub.psm1 index 82436b73540d..c4b001ee52d1 100644 --- a/tools/devops/automation/scripts/GitHub.psm1 +++ b/tools/devops/automation/scripts/GitHub.psm1 @@ -306,7 +306,7 @@ class GitHubComments { return $true } else { # we might have gotten here because of the trigger type. This means that we are in a PR BUT - # we did not get the PR ids, but those can be found in the diff evirtoment vars + # we did not get the PR ids, but those can be found in the diff environment vars if ($Env:BUILD_REASON -eq "PullRequest") { # set the PR ids to the PR we have in the VSTS env vars $this.PRIds = @($Env:SYSTEM_PULLREQUEST_PULLREQUESTNUMBER) @@ -1118,6 +1118,13 @@ function Get-GitHubPRsForHash { Write-Host "Getting related PR ids for commit $Hash" $prs = [System.Collections.ArrayList]@() + + if ($Env:SYSTEM_PULLREQUEST_PULLREQUESTNUMBER) { + Write-Host "Found PR in environment: $Env:SYSTEM_PULLREQUEST_PULLREQUESTNUMBER" + $prs.Add($Env:SYSTEM_PULLREQUEST_PULLREQUESTNUMBER) > $null + return $prs + } + if ($Env:IS_PR -eq "false") { Write-Host "This isn't a PR, IS_PR=false" return $prs diff --git a/tools/devops/automation/scripts/TestResults.Tests.ps1 b/tools/devops/automation/scripts/TestResults.Tests.ps1 index 1a27744780c7..0d29999bc54f 100644 --- a/tools/devops/automation/scripts/TestResults.Tests.ps1 +++ b/tools/devops/automation/scripts/TestResults.Tests.ps1 @@ -1352,4 +1352,76 @@ Test results reported success, but the tests job failed. $sonomaIdx | Should -BeLessThan $sequoiaIdx } } + + Context "VSDrops publish failed" { + It "shows publish failed text instead of VSDrops link" { + $VerbosePreference = "Continue" + $DebugPreference = "Continue" + + $vsdropsMatrix = @" +{ + "cecil": { + "LABEL": "cecil", + "TESTS_LABELS": "--label=skip-all-tests,run-cecil-tests", + "TEST_STAGE": "simulator_tests", + "LABEL_WITH_PLATFORM": "cecil", + "STATUS_CONTEXT": "VSTS: simulator tests - cecil", + "TEST_PREFIX": "simulator_testscecil", + "TEST_PLATFORM": "" + } +} +"@ + $vsdropsFailedStageDeps = @" +{ + "configure_build": { + "configure": { + "outputs": { + "test_matrix.TEST_MATRIX": "$($vsdropsMatrix.Replace("`n", "\n").Replace("`"", "\`""))" + } + } + }, + "simulator_tests": { + "tests": { + "outputs": { + "cecil.PowerShell15.TESTS_ATTEMPT": "1", + "cecil.PowerShell15.TESTS_BOT": "XAMMINI-013.Ventura", + "cecil.PowerShell15.TESTS_LABEL": "cecil", + "cecil.PowerShell15.TESTS_PLATFORM": "", + "cecil.PowerShell15.TESTS_TITLE": "cecil", + "cecil.runTests.TESTS_JOBSTATUS": "Succeeded", + "cecil.setVSDropsPublishResult.VSDROPS_PUBLISHED": "Failed" + }, + "identifier": null, + "name": "tests", + "attempt": 1, + "startTime": null, + "finishTime": null, + "state": "NotStarted", + "result": "Succeeded" + } + } +} +"@ + $testDirectory = Join-Path "." "subdir" + New-Item -Path "$testDirectory" -ItemType "directory" -Force + New-Item -Path "$testDirectory/TestSummary-simulator_testscecil-1" -Name "TestSummary.md" -Value "# :tada: All 1 tests passed :tada:" -Force + + $parallelResults = New-ParallelTestsResults -Path "$testDirectory" -StageDependencies "$vsdropsFailedStageDeps" -Context "context" -VSDropsIndex "vsdropsIndex" + + $parallelResults.IsSuccess() | Should -Be $true + + $sb = [System.Text.StringBuilder]::new() + $parallelResults.WriteComment($sb) + + Remove-Item -Path $testDirectory -Recurse + + $content = $sb.ToString() + + Write-Host $content + + $content | Should -Not -BeLike "*[Html Report (VSDrops)]*" + $content | Should -BeLike "*(:warning: Html Report Publish failed :warning:)*" + $content | Should -BeLike "*[Download]*" + } + } } diff --git a/tools/devops/automation/scripts/TestResults.psm1 b/tools/devops/automation/scripts/TestResults.psm1 index ef5b0eb06457..da6b71d7107e 100644 --- a/tools/devops/automation/scripts/TestResults.psm1 +++ b/tools/devops/automation/scripts/TestResults.psm1 @@ -61,6 +61,7 @@ class TestResult { [string] $TestStage [string] $DisplayName [bool] $IsMacTest + [bool] $VSDropsPublishFailed hidden [int] $Passed hidden [int] $Failed hidden [string[]] $NotTestSummaryLabels = @() @@ -339,9 +340,13 @@ class ParallelTestsResults { } [string] GetDownloadLinks($testResult) { - $dropsIndex = "$($this.VSDropsIndex)/$($testResult.TestStage)$($testResult.Title)-$($testResult.Attempt)/;/tests/vsdrops_index.html" $artifactUrl = "$Env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI$Env:SYSTEM_TEAMPROJECT/_apis/build/builds/$Env:BUILD_BUILDID/artifacts?artifactName=HtmlReport-$($testResult.TestStage)$($testResult.Title)-$($testResult.Attempt)&api-version=6.0&`$format=zip" - $downloadInfo = "[Html Report (VSDrops)]($dropsIndex) [Download]($artifactUrl)" + if ($testResult.VSDropsPublishFailed) { + $downloadInfo = "(:warning: Html Report Publish failed :warning:) [Download]($artifactUrl)" + } else { + $dropsIndex = "$($this.VSDropsIndex)/$($testResult.TestStage)$($testResult.Title)-$($testResult.Attempt)/;/tests/vsdrops_index.html" + $downloadInfo = "[Html Report (VSDrops)]($dropsIndex) [Download]($artifactUrl)" + } return $downloadInfo } @@ -589,6 +594,7 @@ class ParallelTestsResults { $platformKey = $outputs.Keys | Where-Object { $_.EndsWith(".TESTS_PLATFORM") } $attemptKey = $outputs.Keys | Where-Object { $_.EndsWith(".TESTS_ATTEMPT") } $titleKey = $outputs.Keys | Where-Object { $_.EndsWith(".TESTS_TITLE") } + $vsdropsPublishedKey = $outputs.Keys | Where-Object { $_.EndsWith(".VSDROPS_PUBLISHED") } | Sort-Object | Select-Object -Last 1 } else { # matrix job $jobName = $name.Substring(0, $name.IndexOf('.')) @@ -597,6 +603,7 @@ class ParallelTestsResults { $platformKey = $outputs.Keys | Where-Object { $_.StartsWith($jobName + ".") -and $_.EndsWith(".TESTS_PLATFORM") } $attemptKey = $outputs.Keys | Where-Object { $_.StartsWith($jobName + ".") -and $_.EndsWith(".TESTS_ATTEMPT") } $titleKey = $outputs.Keys | Where-Object { $_.StartsWith($jobName + ".") -and $_.EndsWith(".TESTS_TITLE") } + $vsdropsPublishedKey = $outputs.Keys | Where-Object { $_.StartsWith($jobName + ".") -and $_.EndsWith(".VSDROPS_PUBLISHED") } | Sort-Object | Select-Object -Last 1 } Write-Host "Keys for Label='$label' and JobName='$jobName' (dotCount=$dotCount): TitleKey='$titleKey' StatusKey=$statusKey BotKey=$botKey PlatformKey=$platformKey AttemptKey=$attemptKey" @@ -611,6 +618,7 @@ class ParallelTestsResults { $platform = if ($platformKey -eq $null) { "NotFound" } else { $outputs[$platformKey] } $attempt = if ($attemptKey -eq $null) { -2 } else { [int]$outputs[$attemptKey] } $title = if ($titleKey -eq $null) { "NotFound" } else { $outputs[$titleKey] } + $vsdropsPublished = if ($vsdropsPublishedKey -eq $null) { $null } else { $outputs[$vsdropsPublishedKey] } $testResult = [PSCustomObject]@{ Label = $label Title = $title @@ -619,6 +627,7 @@ class ParallelTestsResults { Platform = $platform Attempt = $attempt TestStage = $testStage + VSDropsPublished = $vsdropsPublished } if ($tests.Contains($label)) { $testInfo = $tests[$label] @@ -675,6 +684,7 @@ class ParallelTestsResults { } $result = [TestResult]::new($testSummaryPath, $status, $testConfig, $testAttempt) + $result.VSDropsPublishFailed = ($testResult.VSDropsPublished -eq "Failed") } $testResults += $result diff --git a/tools/devops/automation/scripts/bash/fix-github-ssh-key.sh b/tools/devops/automation/scripts/bash/fix-github-ssh-key.sh deleted file mode 100755 index a603c99bc60d..000000000000 --- a/tools/devops/automation/scripts/bash/fix-github-ssh-key.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -ex - -# ensure that we do remove the old ssh key from github which was leaked: https://blog.gitguardian.com/github-exposed-private-ssh-key/ - -ssh-keygen -R github.com -{ - echo "github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl" - echo "github.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=" - echo "github.com ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEmKSENjQEezOmxkZMy7opKgwFB9nkt5YRrYMjNuG5N87uRgg6CLrbo5wAdT/y6v0mKV0U2w0WZ2YB/++Tpockg=" -} >> ~/.ssh/known_hosts diff --git a/tools/devops/automation/templates/common/configure.yml b/tools/devops/automation/templates/common/configure.yml index c4587316eefe..a7dd354368e7 100644 --- a/tools/devops/automation/templates/common/configure.yml +++ b/tools/devops/automation/templates/common/configure.yml @@ -69,7 +69,8 @@ parameters: }, { label: linker, - splitByPlatforms: false, + splitByPlatforms: true, + needsMultiplePlatforms: false, testPrefix: 'simulator_tests', }, { diff --git a/tools/devops/automation/templates/common/provision.yml b/tools/devops/automation/templates/common/provision.yml index 6424ffd2103d..b60e12e2fb84 100644 --- a/tools/devops/automation/templates/common/provision.yml +++ b/tools/devops/automation/templates/common/provision.yml @@ -35,6 +35,7 @@ steps: - task: AzureCLI@2 displayName: 'Generate BosStorageMirror SAS tokens' condition: and(succeeded(), ${{ parameters.enabled }}) + retryCountOnTaskFailure: 3 inputs: azureSubscription: 'Xamarin - RelEng (BosStorageMirror-Contributor-MI)' scriptType: 'bash' diff --git a/tools/devops/automation/templates/common/setup.yml b/tools/devops/automation/templates/common/setup.yml index a713adac8593..a80833941c2f 100644 --- a/tools/devops/automation/templates/common/setup.yml +++ b/tools/devops/automation/templates/common/setup.yml @@ -22,9 +22,6 @@ steps: name: disableCodeQLOnArm64 condition: and(succeeded(), eq('${{ parameters.disableCodeQL }}', 'true')) -- bash: $(Build.SourcesDirectory)/$(BUILD_REPOSITORY_TITLE)/tools/devops/automation/scripts/bash/fix-github-ssh-key.sh - displayName: 'Fix GitHub SSH host key' - - pwsh: '& "$Env:SYSTEM_DEFAULTWORKINGDIRECTORY/$Env:BUILD_REPOSITORY_TITLE/tools/devops/automation/scripts/show_bot_info.ps1"' displayName: 'Show Bot Info' diff --git a/tools/devops/automation/templates/mac/build.yml b/tools/devops/automation/templates/mac/build.yml index b564d24af9ac..770a2358fb29 100644 --- a/tools/devops/automation/templates/mac/build.yml +++ b/tools/devops/automation/templates/mac/build.yml @@ -210,8 +210,15 @@ steps: condition: succeededOrFailed() # Upload to VSDrops so that the Html Report link in the GitHub comment works. +- bash: | + echo "##vso[task.setvariable variable=JOB_STATUS_BEFORE_VSDROPS]$AGENT_JOBSTATUS" + displayName: 'Capture job status before VSDrops publish' + condition: succeededOrFailed() + continueOnError: true + - task: artifactDropTask@1 displayName: 'Publish to Artifact Services Drop' + name: publishVSDrops inputs: dropServiceURI: 'https://devdiv.artifacts.visualstudio.com/DefaultCollection' dropMetadataContainerName: '${{ parameters.uploadPrefix }}DropMetadata-${{ parameters.stageName }}${{ parameters.label }}-$(System.JobAttempt)' @@ -223,6 +230,19 @@ steps: continueOnError: true condition: succeededOrFailed() +# Azure DevOps doesn't support checking individual step results in step conditions +# (failed('stepName') only works for jobs/stages). Comparing AGENT_JOBSTATUS before +# and after the publish step is the best available approach to detect publish failures. +- bash: | + if [ "$JOB_STATUS_BEFORE_VSDROPS" != "$AGENT_JOBSTATUS" ]; then + echo "VSDrops publish changed job status from '$JOB_STATUS_BEFORE_VSDROPS' to '$AGENT_JOBSTATUS'" + echo "##vso[task.setvariable variable=VSDROPS_PUBLISHED;isOutput=true]Failed" + fi + name: setVSDropsPublishResult + displayName: 'Set VSDrops publish result' + continueOnError: true + condition: succeededOrFailed() + - template: ../common/archive-html-report.yml parameters: rootFolder: '$(BUILD_REPOSITORY_TITLE)/jenkins-results' diff --git a/tools/devops/automation/templates/pipelines/api-diff-pipeline.yml b/tools/devops/automation/templates/pipelines/api-diff-pipeline.yml index 5b81d42282de..26bb8c290581 100644 --- a/tools/devops/automation/templates/pipelines/api-diff-pipeline.yml +++ b/tools/devops/automation/templates/pipelines/api-diff-pipeline.yml @@ -31,7 +31,7 @@ resources: - repository: yaml-templates type: git name: xamarin.yaml-templates - ref: e30b445c2ffcbebe75efdd69546d7196a20c5a43 + ref: refs/heads/main variables: - template: ../variables/common.yml diff --git a/tools/devops/automation/templates/pipelines/build-pipeline.yml b/tools/devops/automation/templates/pipelines/build-pipeline.yml index 0d7af904d237..ebd3ee2f4ae7 100644 --- a/tools/devops/automation/templates/pipelines/build-pipeline.yml +++ b/tools/devops/automation/templates/pipelines/build-pipeline.yml @@ -59,7 +59,7 @@ resources: - repository: yaml-templates type: git name: xamarin.yaml-templates - ref: e30b445c2ffcbebe75efdd69546d7196a20c5a43 + ref: refs/heads/main variables: - ${{ if eq(parameters.isPR, false) }}: diff --git a/tools/devops/automation/templates/pipelines/run-api-scan.yml b/tools/devops/automation/templates/pipelines/run-api-scan.yml index 116c6fcbeb61..44fd63925e64 100644 --- a/tools/devops/automation/templates/pipelines/run-api-scan.yml +++ b/tools/devops/automation/templates/pipelines/run-api-scan.yml @@ -25,7 +25,7 @@ resources: - repository: yaml-templates type: git name: xamarin.yaml-templates - ref: e30b445c2ffcbebe75efdd69546d7196a20c5a43 + ref: refs/heads/main - repository: release-scripts type: github diff --git a/tools/devops/automation/templates/pipelines/run-tests-pipeline.yml b/tools/devops/automation/templates/pipelines/run-tests-pipeline.yml index a3ef20748f63..47e83ca8c65f 100644 --- a/tools/devops/automation/templates/pipelines/run-tests-pipeline.yml +++ b/tools/devops/automation/templates/pipelines/run-tests-pipeline.yml @@ -45,7 +45,7 @@ resources: - repository: yaml-templates type: git name: xamarin.yaml-templates - ref: e30b445c2ffcbebe75efdd69546d7196a20c5a43 + ref: refs/heads/main variables: - template: ../variables/common.yml diff --git a/tools/devops/automation/templates/tests/run-tests.yml b/tools/devops/automation/templates/tests/run-tests.yml index 0ff0d43d39cb..483f3afbb30c 100644 --- a/tools/devops/automation/templates/tests/run-tests.yml +++ b/tools/devops/automation/templates/tests/run-tests.yml @@ -172,6 +172,22 @@ steps: continueOnError: true condition: succeededOrFailed() +# Upload updated expected app size files if the app size tests produced any. +- bash: | + if [ -d "$(Build.ArtifactStagingDirectory)/updated-expected-sizes" ]; then + echo "##vso[task.setvariable variable=HAS_UPDATED_EXPECTED_SIZES]true" + fi + displayName: 'Check for updated expected app size files' + condition: succeededOrFailed() + +- task: PublishPipelineArtifact@1 + displayName: 'Publish Artifact: Updated expected app size files' + inputs: + targetPath: '$(Build.ArtifactStagingDirectory)/updated-expected-sizes' + artifactName: '${{ parameters.uploadPrefix }}updated-expected-sizes-${{ parameters.testPrefix }}-$(System.JobAttempt)' + continueOnError: true + condition: and(succeededOrFailed(), eq(variables['HAS_UPDATED_EXPECTED_SIZES'], 'true')) + - pwsh: | $summaryName = "TestSummary-${{ parameters.testPrefix }}.md" $summaryPath = "$Env:SYSTEM_DEFAULTWORKINGDIRECTORY/$(BUILD_REPOSITORY_TITLE)/tests/TestSummary.md" @@ -182,8 +198,15 @@ steps: continueOnError: true condition: succeededOrFailed() +- bash: | + echo "##vso[task.setvariable variable=JOB_STATUS_BEFORE_VSDROPS]$AGENT_JOBSTATUS" + displayName: 'Capture job status before VSDrops publish' + condition: succeededOrFailed() + continueOnError: true + - task: artifactDropTask@1 displayName: 'Publish to Artifact Services Drop' + name: publishVSDrops inputs: dropServiceURI: 'https://devdiv.artifacts.visualstudio.com/DefaultCollection' dropMetadataContainerName: '${{ parameters.uploadPrefix }}DropMetadata-${{ parameters.testPrefix }}${{ parameters.labelWithPlatform }}-$(System.JobAttempt)' @@ -195,6 +218,19 @@ steps: continueOnError: true condition: succeededOrFailed() +# Azure DevOps doesn't support checking individual step results in step conditions +# (failed('stepName') only works for jobs/stages). Comparing AGENT_JOBSTATUS before +# and after the publish step is the best available approach to detect publish failures. +- bash: | + if [ "$JOB_STATUS_BEFORE_VSDROPS" != "$AGENT_JOBSTATUS" ]; then + echo "VSDrops publish changed job status from '$JOB_STATUS_BEFORE_VSDROPS' to '$AGENT_JOBSTATUS'" + echo "##vso[task.setvariable variable=VSDROPS_PUBLISHED;isOutput=true]Failed" + fi + name: setVSDropsPublishResult + displayName: 'Set VSDrops publish result' + continueOnError: true + condition: succeededOrFailed() + - bash: | set -ex find . -name 'vsts-*.xml' || true diff --git a/tools/devops/automation/vs-insertion.yml b/tools/devops/automation/vs-insertion.yml index 90eef300b8a1..f98208720aed 100644 --- a/tools/devops/automation/vs-insertion.yml +++ b/tools/devops/automation/vs-insertion.yml @@ -12,7 +12,7 @@ resources: - repository: yaml-templates type: git name: xamarin.yaml-templates - ref: e30b445c2ffcbebe75efdd69546d7196a20c5a43 + ref: refs/heads/main # we need all stages to be completed, else we do not have the test results, this trigger is just for CI, because we have # but because we have device issues, and it needs to be gree to trigger, we will deal with it later diff --git a/tools/dotnet-linker/AppBundleRewriter.cs b/tools/dotnet-linker/AppBundleRewriter.cs index f49c71d518bd..1b3908f009ea 100644 --- a/tools/dotnet-linker/AppBundleRewriter.cs +++ b/tools/dotnet-linker/AppBundleRewriter.cs @@ -70,6 +70,7 @@ public AssemblyDefinition SystemConsoleAssembly { Dictionary> type_map = new (); Dictionary method_map = new (); Dictionary field_map = new (); + Dictionary created_types = new (); public AppBundleRewriter (LinkerConfiguration configuration) { @@ -422,6 +423,12 @@ public TypeReference ObjCRuntime_Class { } } + public TypeReference ObjCRuntime_Dlfcn { + get { + return GetTypeReference (PlatformAssembly, "ObjCRuntime.Dlfcn", out var _); + } + } + public TypeReference ObjCRuntime_IManagedRegistrar { get { return GetTypeReference (PlatformAssembly, "ObjCRuntime.IManagedRegistrar", out var _); @@ -464,6 +471,12 @@ public TypeReference ObjCRuntime_NSObjectProxyAttribute { } } + public TypeReference ObjCRuntime_ObjectiveCFrameworkAttribute { + get { + return GetTypeReference (PlatformAssembly, "ObjCRuntime.ObjectiveCFrameworkAttribute", out var _); + } + } + public TypeReference ObjCRuntime_ProtocolProxyAttribute { get { return GetTypeReference (PlatformAssembly, "ObjCRuntime.ProtocolProxyAttribute", out var _); @@ -726,6 +739,17 @@ public MethodReference Class_GetHandle__System_String { } } + public MethodReference ObjectiveCFrameworkAttribute_ctor_String { + get { + return GetMethodReference (PlatformAssembly, ObjCRuntime_ObjectiveCFrameworkAttribute, ".ctor", (v) => + v.IsConstructor + && v.HasParameters + && v.Parameters.Count == 1 + && v.Parameters [0].ParameterType.Is ("System", "String") + && !v.HasGenericParameters); + } + } + public MethodReference ObjCRuntime_INativeObjectProxyAttribute__ctor { get { return GetMethodReference (PlatformAssembly, ObjCRuntime_INativeObjectProxyAttribute, ".ctor", (v) => v.IsDefaultConstructor ()); @@ -1427,6 +1451,7 @@ public void ClearCurrentAssembly () type_map.Clear (); method_map.Clear (); field_map.Clear (); + created_types.Clear (); } public CustomAttribute CreateAttribute (MethodReference constructor) @@ -1653,5 +1678,53 @@ static bool DebugAttributes { return debug_attributes.Value; } } + + public TypeDefinition GetOrCreateType (ModuleDefinition module, string @namespace, string @typename, out bool created) + { + created = false; + + var fullName = @namespace + "." + typename; + if (!created_types.TryGetValue (fullName, out var cachedTypeDefinition)) { + cachedTypeDefinition = module.Types.FirstOrDefault (t => t.Namespace == @namespace && t.Name == typename); + if (cachedTypeDefinition is null) { + cachedTypeDefinition = new TypeDefinition (@namespace, typename, TypeAttributes.Public | TypeAttributes.Sealed, module.TypeSystem.Object); + module.Types.Add (cachedTypeDefinition); + created = true; + } + created_types [fullName] = cachedTypeDefinition; + } + + return cachedTypeDefinition; + } + + public MethodDefinition CreateInternalPInvoke (ModuleDefinition module, string @namespace, string @typename, string methodName, out bool created) + { + var cachedTypeDefinition = GetOrCreateType (module, @namespace, @typename, out _); + var nativeMethod = methodName; + var rv = cachedTypeDefinition.Methods.FirstOrDefault (m => m.Name == methodName); + if (rv is not null) { + created = false; + return rv; // already exists, no need to create it again + } + + // [DllImport ("__Internal")] + // static extern IntPtr {methodName} (); + + rv = new MethodDefinition (methodName, MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PInvokeImpl, System_IntPtr); + rv.IsPreserveSig = true; + + var mod = module.ModuleReferences.FirstOrDefault (mr => mr.Name == "__Internal"); + if (mod is null) { + mod = new ModuleReference ("__Internal"); + module.ModuleReferences.Add (mod); + } + rv.PInvokeInfo = new PInvokeInfo (PInvokeAttributes.CharSetNotSpec | PInvokeAttributes.CallConvCdecl, nativeMethod, mod); + + cachedTypeDefinition.Methods.Add (rv); + + created = true; + + return rv; + } } } diff --git a/tools/dotnet-linker/ApplyPreserveAttributeStep.cs b/tools/dotnet-linker/ApplyPreserveAttributeStep.cs index d25a335b4d0c..18436ab2de88 100644 --- a/tools/dotnet-linker/ApplyPreserveAttributeStep.cs +++ b/tools/dotnet-linker/ApplyPreserveAttributeStep.cs @@ -25,7 +25,7 @@ public XmlTypeDescription (TypeDefinition type) public bool PreserveFields { get; set; } public bool PreserveType { get; set; } public Dictionary Fields { get; } = new (StringComparer.Ordinal); - public Dictionary Methods { get; } = new (StringComparer.Ordinal); + public Dictionary Methods { get; } = new (StringComparer.Ordinal); } ApplyPreserveAttributeImpl impl; @@ -186,6 +186,20 @@ static string GetXmlSignature (MethodDefinition method) return method.FullName.Substring (0, index) + method.FullName.Substring (index + marker.Length); } + // Check if a method has any generic parameters in its signature (return type or parameter types). + // This includes generic parameters nested inside other types (e.g. Action, T[], ref T, Nullable). + // The linker XML descriptor can't resolve generic parameter names like 'T' in method signatures. + static bool HasGenericParameterInSignature (MethodDefinition method) + { + if (method.ReturnType.ContainsGenericParameter) + return true; + foreach (var param in method.Parameters) { + if (param.ParameterType.ContainsGenericParameter) + return true; + } + return false; + } + XmlTypeDescription GetOrCreateXmlDescription (TypeDefinition type) { var assemblyName = type.Module.Assembly.Name.Name; @@ -222,7 +236,7 @@ void AddXmlDescription (TypeDefinition onType, MethodDefinition forMethod, bool var description = GetOrCreateXmlDescription (onType); if (!conditional) description.PreserveType = true; - description.Methods [GetXmlSignature (forMethod)] = conditional; + description.Methods [GetXmlSignature (forMethod)] = (conditional, forMethod); } void AddUnconditionalXmlDescription (IMetadataTokenProvider provider) @@ -261,8 +275,18 @@ XElement CreateXmlTypeElement (XmlTypeDescription description) foreach (var field in description.Fields.OrderBy (v => v.Key, System.StringComparer.Ordinal)) type.Add (new XElement ("field", new XAttribute ("name", field.Key), new XAttribute ("required", field.Value ? "false" : "true"))); - foreach (var method in description.Methods.OrderBy (v => v.Key, System.StringComparer.Ordinal)) - type.Add (new XElement ("method", new XAttribute ("signature", method.Key), new XAttribute ("required", method.Value ? "false" : "true"))); + foreach (var method in description.Methods.OrderBy (v => v.Key, System.StringComparer.Ordinal)) { + var element = new XElement ("method"); + // ILC (NativeAOT compiler) can't resolve generic parameter names (like 'T') in XML descriptor + // method signatures (see https://github.com/dotnet/runtime/issues/128121), so use the method + // name instead of the full signature when the method has generic parameter types. + if (HasGenericParameterInSignature (method.Value.Method)) + element.SetAttributeValue ("name", method.Value.Method.Name); + else + element.SetAttributeValue ("signature", method.Key); + element.SetAttributeValue ("required", method.Value.Conditional ? "false" : "true"); + type.Add (element); + } return type; } diff --git a/tools/dotnet-linker/BackingFieldDelayHandler.cs b/tools/dotnet-linker/BackingFieldDelayHandler.cs index be9b46adf828..c77ad969e721 100644 --- a/tools/dotnet-linker/BackingFieldDelayHandler.cs +++ b/tools/dotnet-linker/BackingFieldDelayHandler.cs @@ -68,6 +68,7 @@ protected override void Process (MethodDefinition method) public static void ReapplyDisposedFields (DerivedLinkContext context, string operation) { // note: all methods in the dictionary are marked (since they were added from an IMarkHandler) + var app = context.App; foreach ((var method, var body) in dispose) { foreach (var ins in body.Instructions) { switch (ins.OpCode.OperandType) { @@ -79,9 +80,9 @@ public static void ReapplyDisposedFields (DerivedLinkContext context, string ope var store_field = ins; var load_null = ins.Previous; var load_this = ins.Previous.Previous; - if (OptimizeGeneratedCodeHandler.ValidateInstruction (method, store_field, operation, Code.Stfld) && - OptimizeGeneratedCodeHandler.ValidateInstruction (method, load_null, operation, Code.Ldnull) && - OptimizeGeneratedCodeHandler.ValidateInstruction (method, load_this, operation, Code.Ldarg_0)) { + if (OptimizeGeneratedCodeHandler.ValidateInstruction (app, method, store_field, operation, Code.Stfld) && + OptimizeGeneratedCodeHandler.ValidateInstruction (app, method, load_null, operation, Code.Ldnull) && + OptimizeGeneratedCodeHandler.ValidateInstruction (app, method, load_this, operation, Code.Ldarg_0)) { store_field.OpCode = OpCodes.Nop; load_null.OpCode = OpCodes.Nop; load_this.OpCode = OpCodes.Nop; diff --git a/tools/dotnet-linker/DotNetResolver.cs b/tools/dotnet-linker/DotNetResolver.cs index 37e04bb9e1f9..f71c2ec5b4cb 100644 --- a/tools/dotnet-linker/DotNetResolver.cs +++ b/tools/dotnet-linker/DotNetResolver.cs @@ -8,6 +8,10 @@ namespace Xamarin.Linker { public class DotNetResolver : CoreResolver { + public DotNetResolver (Application app) + { + } + public override AssemblyDefinition Resolve (AssemblyNameReference name, ReaderParameters parameters) { throw new NotImplementedException ($"Unable to resolve the assembly reference {name}"); diff --git a/tools/dotnet-linker/LinkerConfiguration.cs b/tools/dotnet-linker/LinkerConfiguration.cs index 3acbcd16362e..a7d9909785ed 100644 --- a/tools/dotnet-linker/LinkerConfiguration.cs +++ b/tools/dotnet-linker/LinkerConfiguration.cs @@ -30,6 +30,14 @@ public class LinkerConfiguration { public string IntermediateLinkDir { get; private set; } = string.Empty; public bool InvariantGlobalization { get; private set; } public bool HybridGlobalization { get; private set; } + public InlineDlfcnMethodsMode InlineDlfcnMethods { get; set; } + public bool InlineDlfcnMethodsEnabled => InlineDlfcnMethods != InlineDlfcnMethodsMode.Disabled; + public InlineClassGetHandleMode InlineClassGetHandle { get; set; } + // Per-assembly field symbols collected by InlineDlfcnMethodsStep, keyed by assembly name. + public Dictionary> InlinedDlfcnFields { get; } = new Dictionary> (); + // All [Field] symbol names collected by ProcessExportedFields, used in compatibility mode. + public HashSet FieldSymbols { get; } = new HashSet (); + public string IntermediateOutputPath { get; private set; } = string.Empty; public string ItemsDirectory { get; private set; } = string.Empty; public bool IsSimulatorBuild { get; private set; } public string PartialStaticRegistrarLibrary { get; set; } = string.Empty; @@ -38,7 +46,8 @@ public class LinkerConfiguration { public string RelativeAppBundlePath { get; private set; } = string.Empty; public Version? SdkVersion { get; private set; } public string SdkRootDirectory { get; private set; } = string.Empty; - public int Verbosity => Driver.Verbosity; + public string TypeMapFilePath { get; set; } = string.Empty; + public int Verbosity => Application.Verbosity; public string XamarinNativeLibraryDirectory { get; private set; } = string.Empty; static ConditionalWeakTable configurations = new ConditionalWeakTable (); @@ -46,6 +55,7 @@ public class LinkerConfiguration { public Application Application { get; private set; } public IList RegistrationMethods { get; set; } = new List (); + public List NativeCodeToCompileAndLink { get; private set; } = new List (); public CompilerFlags CompilerFlags; LinkContext? context; @@ -202,9 +212,28 @@ public static LinkerConfiguration GetInstance (LinkContext context) case "FrameworkAssembly": FrameworkAssemblies.Add (value); break; + case "InlineClassGetHandle": + if (Enum.TryParse (value, true, out var inlineClassGetHandleMode)) + InlineClassGetHandle = inlineClassGetHandleMode; + else if (string.IsNullOrEmpty (value)) + InlineClassGetHandle = InlineClassGetHandleMode.Disabled; + else + throw new InvalidOperationException ($"Unknown InlineClassGetHandle value: {value}"); + break; + case "InlineDlfcnMethods": + if (Enum.TryParse (value, true, out var inlineDlfcnMode)) + InlineDlfcnMethods = inlineDlfcnMode; + else if (string.IsNullOrEmpty (value)) + InlineDlfcnMethods = InlineDlfcnMethodsMode.Disabled; + else + throw new InvalidOperationException ($"Unknown InlineDlfcnMethods value: {value}"); + break; case "IntermediateLinkDir": IntermediateLinkDir = value; break; + case "IntermediateOutputPath": + IntermediateOutputPath = value; + break; case "Interpreter": if (!string.IsNullOrEmpty (value)) Application.ParseInterpreter (value); @@ -356,6 +385,9 @@ public static LinkerConfiguration GetInstance (LinkContext context) case "TypeMapAssemblyName": Application.TypeMapAssemblyName = value; break; + case "TypeMapFilePath": + TypeMapFilePath = value; + break; case "TypeMapOutputDirectory": Application.TypeMapOutputDirectory = value; break; @@ -365,7 +397,7 @@ public static LinkerConfiguration GetInstance (LinkContext context) case "Verbosity": if (!int.TryParse (value, out var verbosity)) throw new InvalidOperationException ($"Invalid Verbosity '{value}' in {linker_file}"); - Driver.Verbosity += verbosity; + Application.Verbosity += verbosity; break; case "Warn": try { @@ -403,10 +435,10 @@ public static LinkerConfiguration GetInstance (LinkContext context) ErrorHelper.Platform = Platform; // Optimizations.Parse can only be called after setting ErrorHelper.Platform - if (!string.IsNullOrEmpty (user_optimize_flags)) { + if (!StringUtils.IsNullOrEmpty (user_optimize_flags)) { var messages = new List (); Application.Optimizations.Parse (Application.Platform, user_optimize_flags, messages); - ErrorHelper.Show (messages); + ErrorHelper.Show (Application, messages); } if (use_llvm) { @@ -415,7 +447,7 @@ public static LinkerConfiguration GetInstance (LinkContext context) Application.CreateCache (significantLines.ToArray ()); if (Application.Cache is not null) - Application.Cache.Location = CacheDirectory; + Application.Cache.SetLocation (Application, CacheDirectory); if (DeploymentTarget is not null) Application.DeploymentTarget = DeploymentTarget; if (SdkVersion is not null) { @@ -440,7 +472,7 @@ public static LinkerConfiguration GetInstance (LinkContext context) throw ErrorHelper.CreateError (99, "Inconsistent platforms. TargetFramework={0}, Platform={1}", Driver.TargetFramework.Platform, Platform); if (Application.XamarinRuntime != XamarinRuntime.MonoVM && Application.UseInterpreter) { - Driver.Log (4, "The interpreter is enabled, but the current runtime isn't MonoVM. The interpreter settings will be ignored."); + Application.Log (4, "The interpreter is enabled, but the current runtime isn't MonoVM. The interpreter settings will be ignored."); Application.UnsetInterpreter (); } @@ -507,49 +539,52 @@ AssemblyBuildTarget ParseLinkMode (string value, string variableName) public void Write () { if (Verbosity > 0) { - Console.WriteLine ($"LinkerConfiguration:"); - Console.WriteLine ($" ABI: {Abi.AsArchString ()}"); - Console.WriteLine ($" AOTArguments: {string.Join (", ", Application.AotArguments)}"); - Console.WriteLine ($" AOTOutputDirectory: {AOTOutputDirectory}"); - Console.WriteLine ($" DedupAssembly: {DedupAssembly}"); - Console.WriteLine ($" AppBundleManifestPath: {Application.InfoPListPath}"); - Console.WriteLine ($" AreAnyAssembliesTrimmed: {Application.AreAnyAssembliesTrimmed}"); - Console.WriteLine ($" AssemblyName: {Application.AssemblyName}"); - Console.WriteLine ($" CacheDirectory: {CacheDirectory}"); - Console.WriteLine ($" Debug: {Application.EnableDebug}"); - Console.WriteLine ($" Dlsym: {Application.DlsymOptions} {(Application.DlsymAssemblies is not null ? string.Join (" ", Application.DlsymAssemblies.Select (v => (v.Item2 ? "+" : "-") + v.Item1)) : string.Empty)}"); - Console.WriteLine ($" DeploymentTarget: {DeploymentTarget}"); - Console.WriteLine ($" EnableSGenConc {Application.EnableSGenConc}"); - Console.WriteLine ($" IntermediateLinkDir: {IntermediateLinkDir}"); - Console.WriteLine ($" InterpretedAssemblies: {string.Join (", ", Application.InterpretedAssemblies)}"); - Console.WriteLine ($" ItemsDirectory: {ItemsDirectory}"); - Console.WriteLine ($" {FrameworkAssemblies.Count} framework assemblies:"); + Application.Log ($"LinkerConfiguration:"); + Application.Log ($" ABI: {Abi.AsArchString ()}"); + Application.Log ($" AOTArguments: {string.Join (", ", Application.AotArguments)}"); + Application.Log ($" AOTOutputDirectory: {AOTOutputDirectory}"); + Application.Log ($" DedupAssembly: {DedupAssembly}"); + Application.Log ($" AppBundleManifestPath: {Application.InfoPListPath}"); + Application.Log ($" AreAnyAssembliesTrimmed: {Application.AreAnyAssembliesTrimmed}"); + Application.Log ($" AssemblyName: {Application.AssemblyName}"); + Application.Log ($" CacheDirectory: {CacheDirectory}"); + Application.Log ($" Debug: {Application.EnableDebug}"); + Application.Log ($" Dlsym: {Application.DlsymOptions} {(Application.DlsymAssemblies is not null ? string.Join (" ", Application.DlsymAssemblies.Select (v => (v.Item2 ? "+" : "-") + v.Item1)) : string.Empty)}"); + Application.Log ($" DeploymentTarget: {DeploymentTarget}"); + Application.Log ($" EnableSGenConc {Application.EnableSGenConc}"); + Application.Log ($" InlineDlfcnMethods: {InlineDlfcnMethods}"); + Application.Log ($" IntermediateLinkDir: {IntermediateLinkDir}"); + Application.Log ($" IntermediateOutputPath: {IntermediateOutputPath}"); + Application.Log ($" InterpretedAssemblies: {string.Join (", ", Application.InterpretedAssemblies)}"); + Application.Log ($" ItemsDirectory: {ItemsDirectory}"); + Application.Log ($" {FrameworkAssemblies.Count} framework assemblies:"); foreach (var fw in FrameworkAssemblies.OrderBy (v => v)) - Console.WriteLine ($" {fw}"); - Console.WriteLine ($" IsSimulatorBuild: {IsSimulatorBuild}"); - Console.WriteLine ($" MarshalManagedExceptions: {Application.MarshalManagedExceptions} (IsDefault: {Application.IsDefaultMarshalManagedExceptionMode})"); - Console.WriteLine ($" MarshalObjectiveCExceptions: {Application.MarshalObjectiveCExceptions}"); - Console.WriteLine ($" {Application.MonoLibraries.Count} mono libraries:"); + Application.Log ($" {fw}"); + Application.Log ($" IsSimulatorBuild: {IsSimulatorBuild}"); + Application.Log ($" MarshalManagedExceptions: {Application.MarshalManagedExceptions} (IsDefault: {Application.IsDefaultMarshalManagedExceptionMode})"); + Application.Log ($" MarshalObjectiveCExceptions: {Application.MarshalObjectiveCExceptions}"); + Application.Log ($" {Application.MonoLibraries.Count} mono libraries:"); foreach (var lib in Application.MonoLibraries.OrderBy (v => v)) - Console.WriteLine ($" {lib}"); - Console.WriteLine ($" Optimize: {user_optimize_flags} => {Application.Optimizations}"); - Console.WriteLine ($" PartialStaticRegistrarLibrary: {PartialStaticRegistrarLibrary}"); - Console.WriteLine ($" Platform: {Platform}"); - Console.WriteLine ($" PlatformAssembly: {PlatformAssembly}.dll"); - Console.WriteLine ($" RelativeAppBundlePath: {RelativeAppBundlePath}"); - Console.WriteLine ($" Registrar: {Application.Registrar} (Options: {Application.RegistrarOptions})"); - Console.WriteLine ($" RuntimeConfigurationFile: {Application.RuntimeConfigurationFile}"); - Console.WriteLine ($" RequirePInvokeWrappers: {Application.RequiresPInvokeWrappers}"); - Console.WriteLine ($" SdkDevPath: {Driver.SdkRoot}"); - Console.WriteLine ($" SdkRootDirectory: {SdkRootDirectory}"); - Console.WriteLine ($" SdkVersion: {SdkVersion}"); - Console.WriteLine ($" TypeMapAssemblyName: {Application.TypeMapAssemblyName}"); - Console.WriteLine ($" TypeMapOutputDirectory: {Application.TypeMapOutputDirectory}"); - Console.WriteLine ($" UseInterpreter: {Application.UseInterpreter}"); - Console.WriteLine ($" UseLlvm: {Application.IsLLVM}"); - Console.WriteLine ($" Verbosity: {Verbosity}"); - Console.WriteLine ($" XamarinNativeLibraryDirectory: {XamarinNativeLibraryDirectory}"); - Console.WriteLine ($" XamarinRuntime: {Application.XamarinRuntime}"); + Application.Log ($" {lib}"); + Application.Log ($" Optimize: {user_optimize_flags} => {Application.Optimizations}"); + Application.Log ($" PartialStaticRegistrarLibrary: {PartialStaticRegistrarLibrary}"); + Application.Log ($" Platform: {Platform}"); + Application.Log ($" PlatformAssembly: {PlatformAssembly}.dll"); + Application.Log ($" RelativeAppBundlePath: {RelativeAppBundlePath}"); + Application.Log ($" Registrar: {Application.Registrar} (Options: {Application.RegistrarOptions})"); + Application.Log ($" RuntimeConfigurationFile: {Application.RuntimeConfigurationFile}"); + Application.Log ($" RequirePInvokeWrappers: {Application.RequiresPInvokeWrappers}"); + Application.Log ($" SdkDevPath: {Driver.SdkRoot}"); + Application.Log ($" SdkRootDirectory: {SdkRootDirectory}"); + Application.Log ($" SdkVersion: {SdkVersion}"); + Application.Log ($" TypeMapAssemblyName: {Application.TypeMapAssemblyName}"); + Application.Log ($" TypeMapFilePath: {TypeMapFilePath}"); + Application.Log ($" TypeMapOutputDirectory: {Application.TypeMapOutputDirectory}"); + Application.Log ($" UseInterpreter: {Application.UseInterpreter}"); + Application.Log ($" UseLlvm: {Application.IsLLVM}"); + Application.Log ($" Verbosity: {Verbosity}"); + Application.Log ($" XamarinNativeLibraryDirectory: {XamarinNativeLibraryDirectory}"); + Application.Log ($" XamarinRuntime: {Application.XamarinRuntime}"); } } @@ -609,7 +644,7 @@ public static void Report (LinkContext context, IList exceptions) context.LogMessage (msg); } // ErrorHelper.Show will print our errors and warnings to stderr. - ErrorHelper.Show (list); + ErrorHelper.Show (ConsoleLog.Instance, list); } public IEnumerable GetNonDeletedAssemblies (BaseStep step) @@ -637,3 +672,17 @@ public MSBuildItem (string include, Dictionary metadata) Metadata = metadata; } } + +public enum InlineDlfcnMethodsMode { + Disabled, + Strict, + Compat, + Compatibility = Compat, +} + +public enum InlineClassGetHandleMode { + Disabled, + Strict, + Compat, + Compatibility = Compat, +} diff --git a/tools/dotnet-linker/PreserveSmartEnumConversionsStep.cs b/tools/dotnet-linker/PreserveSmartEnumConversionsStep.cs index 75ebca8360dd..7dae7ba20e13 100644 --- a/tools/dotnet-linker/PreserveSmartEnumConversionsStep.cs +++ b/tools/dotnet-linker/PreserveSmartEnumConversionsStep.cs @@ -94,6 +94,7 @@ class PreserveSmartEnumConversion { Dictionary> cache = new (); public DerivedLinkContext LinkContext { get; private set; } + public Application App => LinkContext.App; Func, bool, MethodDefinition? [], bool> preserve { get; set; } @@ -122,14 +123,14 @@ public bool ProcessAttributeProvider (ICustomAttributeProvider provider, params continue; if (ca.ConstructorArguments.Count != 1) { - ErrorHelper.Show (ErrorHelper.CreateWarning (LinkContext.App, 4124, provider, Errors.MT4124_E, provider.AsString (), ca.ConstructorArguments.Count)); + ErrorHelper.Show (App, ErrorHelper.CreateWarning (LinkContext.App, 4124, provider, Errors.MT4124_E, provider.AsString (), ca.ConstructorArguments.Count)); continue; } var managedType = ca.ConstructorArguments [0].Value as TypeReference; var managedEnumType = managedType?.GetElementType ().Resolve (); if (managedEnumType is null) { - ErrorHelper.Show (ErrorHelper.CreateWarning (LinkContext.App, 4124, provider, Errors.MT4124_H, provider.AsString (), managedType?.FullName ?? "(null)")); + ErrorHelper.Show (App, ErrorHelper.CreateWarning (LinkContext.App, 4124, provider, Errors.MT4124_H, provider.AsString (), managedType?.FullName ?? "(null)")); continue; } @@ -155,7 +156,7 @@ public bool ProcessAttributeProvider (ICustomAttributeProvider provider, params break; } if (extensionType is null) { - Driver.Log (1, $"Could not find a smart extension type for the enum {managedEnumType.FullName} (due to BindAs attribute on {provider.AsString ()}): most likely this is because the enum isn't a smart enum."); + App.Log (1, $"Could not find a smart extension type for the enum {managedEnumType.FullName} (due to BindAs attribute on {provider.AsString ()}): most likely this is because the enum isn't a smart enum."); continue; } @@ -184,12 +185,12 @@ public bool ProcessAttributeProvider (ICustomAttributeProvider provider, params } if (getConstant is null) { - Driver.Log (1, $"Could not find the GetConstant method on the supposedly smart extension type {extensionType.FullName} for the enum {managedEnumType.FullName} (due to BindAs attribute on {provider.AsString ()}): most likely this is because the enum isn't a smart enum."); + App.Log (1, $"Could not find the GetConstant method on the supposedly smart extension type {extensionType.FullName} for the enum {managedEnumType.FullName} (due to BindAs attribute on {provider.AsString ()}): most likely this is because the enum isn't a smart enum."); continue; } if (getValue is null) { - Driver.Log (1, $"Could not find the GetValue method on the supposedly smart extension type {extensionType.FullName} for the enum {managedEnumType.FullName} (due to BindAs attribute on {provider.AsString ()}): most likely this is because the enum isn't a smart enum."); + App.Log (1, $"Could not find the GetValue method on the supposedly smart extension type {extensionType.FullName} for the enum {managedEnumType.FullName} (due to BindAs attribute on {provider.AsString ()}): most likely this is because the enum isn't a smart enum."); continue; } diff --git a/tools/dotnet-linker/Steps/AssemblyModifierStep.cs b/tools/dotnet-linker/Steps/AssemblyModifierStep.cs index 2e3e971d4d87..8e2899fb0660 100644 --- a/tools/dotnet-linker/Steps/AssemblyModifierStep.cs +++ b/tools/dotnet-linker/Steps/AssemblyModifierStep.cs @@ -31,7 +31,8 @@ protected sealed override void TryProcessAssembly (AssemblyDefinition assembly) protected virtual bool ModifyAssembly (AssemblyDefinition assembly) { var modified = false; - foreach (var type in assembly.MainModule.Types) + // ToArray () is needed because subclasses (e.g. InlineDlfcnMethodsStep) may add new types during iteration. + foreach (var type in assembly.MainModule.Types.ToArray ()) modified |= ProcessTypeImpl (type); return modified; } @@ -50,7 +51,8 @@ bool ProcessTypeImpl (TypeDefinition type) { var modified = ProcessType (type); if (type.HasNestedTypes) { - foreach (var nested in type.NestedTypes) + // ToArray () is needed because subclasses may add new types during iteration. + foreach (var nested in type.NestedTypes.ToArray ()) modified |= ProcessTypeImpl (nested); } return modified; diff --git a/tools/dotnet-linker/Steps/ExceptionalMarkHandler.cs b/tools/dotnet-linker/Steps/ExceptionalMarkHandler.cs index 4eda1e9f18f3..25153aca76fa 100644 --- a/tools/dotnet-linker/Steps/ExceptionalMarkHandler.cs +++ b/tools/dotnet-linker/Steps/ExceptionalMarkHandler.cs @@ -34,6 +34,8 @@ public virtual void Initialize (LinkContext context) protected Profile Profile => Configuration.Profile; + protected Application App => Configuration.Application; + public void ProcessAssembly (AssemblyDefinition assembly) { try { diff --git a/tools/dotnet-linker/Steps/GatherFrameworksStep.cs b/tools/dotnet-linker/Steps/GatherFrameworksStep.cs index 4d5eb1fbfca7..5fb658b02f89 100644 --- a/tools/dotnet-linker/Steps/GatherFrameworksStep.cs +++ b/tools/dotnet-linker/Steps/GatherFrameworksStep.cs @@ -20,10 +20,7 @@ protected override void TryProcessAssembly (AssemblyDefinition assembly) { base.TryProcessAssembly (assembly); - if (Configuration.PlatformAssembly != assembly.Name.Name) - return; - - global::Frameworks.Gather (Configuration.Application, assembly, Frameworks, WeakFrameworks); + global::Frameworks.Gather (Configuration.Application, [assembly], Frameworks, WeakFrameworks); } protected override void TryEndProcess () diff --git a/tools/dotnet-linker/Steps/GenerateReferencesStep.cs b/tools/dotnet-linker/Steps/GenerateReferencesStep.cs index 7d1f08537fb3..4a3959aa0f80 100644 --- a/tools/dotnet-linker/Steps/GenerateReferencesStep.cs +++ b/tools/dotnet-linker/Steps/GenerateReferencesStep.cs @@ -38,7 +38,7 @@ protected override void TryEndProcess () break; case SymbolMode.Linker: foreach (var symbol in required_symbols) { - var item = new MSBuildItem (symbol.Prefix + symbol.Name); + var item = new MSBuildItem (Symbol.Prefix + symbol.Name); item.Metadata ["SymbolType"] = symbol.Type.ToString (); items.Add (item); } diff --git a/tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs b/tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs new file mode 100644 index 000000000000..4cb66ed8fd27 --- /dev/null +++ b/tools/dotnet-linker/Steps/InlineClassGetHandleStep.cs @@ -0,0 +1,264 @@ +using System.Linq; +using System.Text; + +using Mono.Cecil; +using Mono.Cecil.Cil; +using Mono.Linker; +using Mono.Tuner; + +using Xamarin.Bundler; +using Xamarin.Utils; + +#nullable enable + +namespace Xamarin.Linker.Steps; + +// See docs/code/class-handles.md for an overview of class handle handling. + +// Find all the references to Objective-C classes for each assembly. +// * If an assembly is trimmed, we replace calls to (inline) Class.GetHandle with a P/Invoke that fetches the class in question. +// * If an assembly is not trimmed, we do not inline Class.GetHandle, but we keep a list of all the Objective-C classes that are used, so that we can tell the native linker about them so they're not linked away by the native linker. +// +// The sticky problem is that we can't inspect the managed output from NativeAOT, which means +// we can't list the Objective-C classes NativeAOT-compiled assemblies using. To get around this +// problem, we convert calls to Class.GetHandle to a P/Invoke which fetches the native Objective-C +// class handle directly - because we _can_ list the P/Invoke calls from NativeAOT-compiled code. +// +// For non-trimmed assemblies, we don't need to do this, because we know nothing from the assembly +// will be trimmed away. This has the added advantage of being Hot Reload compatible, because we +// can't modify assemblies when we're doing Hot Reload. + +public class InlineClassGetHandleStep : AssemblyModifierStep { + + protected override string Name { get; } = "Inline Class GetHandle"; + protected override int ErrorCode { get; } = 2262; + + bool strictMode; + bool? inlining_enabled; + + Dictionary objectiveCTypeMap = new (); + + public const string PInvokePrefix = "xamarin_Class_GetHandle_"; + public const string PInvokeSuffix = "_Native"; + + protected override void TryProcess () + { + strictMode = Configuration.InlineClassGetHandle == InlineClassGetHandleMode.Strict; + + if (strictMode && Configuration.Application.Registrar == Bundler.RegistrarMode.Dynamic) { + Report (ErrorHelper.CreateError (Configuration.Application, 2262, null, Errors.MX2262)); + } + + objectiveCTypeMap = DerivedLinkContext.StaticRegistrar.Types.ToDictionary (v => v.Value.ExportedName, v => v.Value); + + if (!string.IsNullOrEmpty (Configuration.TypeMapFilePath)) { + var sb = new StringBuilder (); + foreach (var info in objectiveCTypeMap.Values.OrderBy (v => v.ExportedName)) { + var td = info.Type.Resolve (); + if (td is null) + continue; + var introduced = DerivedLinkContext.StaticRegistrar.GetSdkIntroducedVersion (td, out _); + Frameworks.TryGetFramework (App, td, out string? framework); + sb.AppendLine ($"Class={info.ExportedName}|Framework={framework}|Introduced={introduced}|IsWrapper={info.IsWrapper}|IsStubClass={info.IsStubClass}"); + } + Driver.WriteIfDifferent (App, Configuration.TypeMapFilePath, sb.ToString ()); + } + + base.TryProcess (); + } + + protected override bool IsActiveFor (AssemblyDefinition assembly) + { + if (!Configuration.Profile.IsOrReferencesProductAssembly (assembly)) + return false; + + // we have to process both trimmed and non-trimmed assemblies. + + return true; + } + + protected override bool ModifyAssembly (AssemblyDefinition assembly) + { + inlining_enabled = Annotations.GetAction (assembly) == AssemblyAction.Link; + var modified = base.ModifyAssembly (assembly); + inlining_enabled = null; + return modified; + } + + protected override bool ProcessType (TypeDefinition type) + { + var modified = false; + + if (inlining_enabled == true) { + modified |= ProcessMethods (type); + } else { + if (ListExportedSymbols.TryGetRequiredObjectiveCType (DerivedLinkContext, type, out var exportedName)) { + DerivedLinkContext.RequiredSymbols.AddObjectiveCClass (exportedName).AddMember (type); + } + } + return modified; + } + + MethodDefinition GetOrCreatePInvokeMethod (MethodDefinition callingMethod, string objectiveCClassName) + { + // [DllImport ("__Internal")] + // static extern IntPtr xamarin_Class_GetClassHandle_{objectiveCClassName}_Native (); + + return abr.CreateInternalPInvoke (callingMethod.Module, "ObjCRuntime", "Class", $"{PInvokePrefix}{objectiveCClassName}{PInvokeSuffix}", out _); + } + + protected override bool ProcessMethod (MethodDefinition method) + { + var modified = false; + + if (!method.HasBody) + return modified; + + if (method.DeclaringType.Name == "Class" && method.DeclaringType.Namespace == "ObjCRuntime") + return modified; // don't process the Class methods themselves + + bool isOurOwnCode () + { + // Don't show warnings for a few places in our own code where we call Class.GetHandle in un-inlinable ways. + switch (method.DeclaringType.Namespace) { + case "Registrar": + switch (method.DeclaringType.Name) { + case "DynamicRegistrar": + switch (method.Name) { + case "OnReloadType": + case "OnRegisterType": + return true; + } + break; + } + break; + } + return false; + } + + foreach (var instr in method.Body.Instructions) { + if (instr.Operand is not MethodReference mr) + continue; + if (mr.DeclaringType.Name != "Class" || mr.DeclaringType.Namespace != "ObjCRuntime") + continue; + if (mr.Name != "GetHandle" && mr.Name != "GetHandleIntrinsic") + continue; + if (mr.Parameters.Count != 1) + continue; + if (!mr.Parameters [0].ParameterType.Is ("System", "String")) + continue; + if (!mr.ReturnType.Is ("ObjCRuntime", "NativeHandle")) + continue; + + var ldstr = instr.Previous; + if (ldstr.OpCode != OpCodes.Ldstr) { + if (!isOurOwnCode ()) + App.Log (3, "Unknown or unsupported pattern in call to Class.GetHandle in '{0}': {1}. The call will not be inlined.", FormatMethod (method), ldstr); + continue; + } + if (ldstr.Operand is not string objectiveCClassName) { + if (!isOurOwnCode ()) + App.Log (3, "Unknown or unsupported pattern in call to Class.GetHandle in '{0}': {1}. The call will not be inlined.", FormatMethod (method), ldstr.Operand); + continue; + } + + if (!objectiveCTypeMap.TryGetValue (objectiveCClassName, out var objCType)) { + App.Log (3, "Could not find a managed type for the Objective-C type '{1}' in the call to Class.GetHandle in '{0}', assuming the Objective-C type is available in the simulator.", FormatMethod (method), objectiveCClassName); + } + + if (!strictMode) { + if (objCType is not null && objCType.Type == method.DeclaringType) { + // This is a call to Class.GetHandle for the same class that it's being called from, this is OK. + } else if (ListExportedSymbols.TryGetRequiredObjectiveCType (DerivedLinkContext, method.DeclaringType, out var exportedName)) { + if (exportedName != objectiveCClassName) { + App.Log (3, "The call to Class.GetHandle in '{0}' is trying to get the handle for the Objective-C class '{1}', but the declaring type's exported name is '{2}', not '{1}'. Since we're in compat mode, we're assuming the class should not be preserved.", FormatMethod (method), objectiveCClassName, exportedName); + continue; + } + } else { + if (App.StaticRegistrar.GetCategoryAttribute (method.DeclaringType) is not null) + App.Log (3, "The call to Class.GetHandle in '{0}' is trying to get the handle for the Objective-C class '{1}', but we couldn't determine whether this class should be statically preserved or not. Since we're in compat mode, we're assuming the class should not be statically preserved.", FormatMethod (method), objectiveCClassName); + continue; + } + } + + // Check if the Objective-C class is listed as a ReferenceNativeSymbol with Ignore mode, and if so, don't inline the call to Class.GetHandle (because the native symbol won't be available at link time) + var existingSymbol = DerivedLinkContext.RequiredSymbols.Find (Symbol.ObjectiveCPrefix + objectiveCClassName); + if (existingSymbol is not null && existingSymbol.Type == SymbolType.ObjectiveCClass && existingSymbol.Mode == SymbolMode.Ignore) { + App.Log (3, "Not inlining the call to Class.GetHandle (\"{0}\") in method {1} because the class is listed as a ReferenceNativeSymbol with Ignore mode.", objectiveCClassName, FormatMethod (method)); + continue; + } + + if (objCType is not null) { + if (DerivedLinkContext.App.IsSimulatorBuild) { + if (DerivedLinkContext.HasAvailabilityAttributesShowingUnavailableInSimulator (objCType.Type.Resolve (), method)) { + App.Log (3, "Not inlining the call to Class.GetHandle (\"{0}\") in method {1} because the type is marked with an attribute indicating it's not available in the simulator.", objectiveCClassName, FormatMethod (method)); + continue; + } + } + + if (IsUnsupported (objCType.Type.Resolve ())) { + App.Log (3, "Not inlining the call to Class.GetHandle (\"{0}\") in method {1} because the type is marked with an [UnsupportedOSPlatform] attribute.", objectiveCClassName, FormatMethod (method)); + continue; + } + + if (objCType.Methods is null && DerivedLinkContext.StaticRegistrar.IsPlatformType (objCType.Type) && !objCType.IsProtocol && !objCType.IsCategory && objCType.IsModel) { + // The static registrar skips generating code for this type, so we shouldn't inline calls to Class.GetHandle for it, because the P/Invoke we generate won't be able to find the native symbol for it. + continue; + } + + if (Frameworks.TryGetFramework (App, objCType.Type.Resolve (), out Framework? framework) && framework.IsFrameworkUnavailable (App)) { + App.Log (3, "Not inlining the call to Class.GetHandle (\"{0}\") in method {1} because the framework {2} is unavailable.", objectiveCClassName, FormatMethod (method), framework.Name); + continue; + } + + if (objCType.Type.Is ("UIKit", "UITitlebar")) { + // UITitlebar is a weird special case, the class exists in the headers, and it's documented online, but it's not possible to link with it (not even in an Xcode project, it's not in any .tbd files). + continue; + } + } + + ldstr.OpCode = OpCodes.Call; + ldstr.Operand = GetOrCreatePInvokeMethod (method, objectiveCClassName); + + instr.OpCode = OpCodes.Call; + instr.Operand = abr.NativeObject_op_Implicit_NativeHandle; + + modified = true; + } + + return modified; + } + + bool IsUnsupported (TypeDefinition? type) + { + if (type is null) + return false; + + if (!type.HasCustomAttributes) + return false; + + foreach (var ca in type.CustomAttributes) { + if (!ca.AttributeType.Is ("System.Runtime.Versioning", "UnsupportedOSPlatformAttribute")) + continue; + + if (!DerivedLinkContext.StaticRegistrar.GetDotNetAvailabilityAttribute (ca, App.Platform, out var sdkVersion, out _)) + continue; + + if (sdkVersion is null) + return true; // if there's no version, then it's always unavailable + + return sdkVersion <= App.SdkVersion; + } + + return false; + } + + static string FormatMethod (MethodReference method) + { + var rv = method.FullName; + var idx = rv.IndexOf (' '); + if (idx > 0) + rv = rv.Substring (idx + 1); + return rv; + } +} diff --git a/tools/dotnet-linker/Steps/InlineDlfcnMethodsStep.cs b/tools/dotnet-linker/Steps/InlineDlfcnMethodsStep.cs new file mode 100644 index 000000000000..95913f88ead9 --- /dev/null +++ b/tools/dotnet-linker/Steps/InlineDlfcnMethodsStep.cs @@ -0,0 +1,1010 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +using Mono.Cecil; +using Mono.Cecil.Cil; +using Mono.Cecil.Rocks; +using Mono.Linker; +using Mono.Linker.Steps; +using Mono.Tuner; +using MonoTouch.Tuner; + +using Xamarin.Bundler; + +#nullable enable + +namespace Xamarin.Linker.Steps; + +// See docs/code/native-symbols.md for an overview of native symbol handling. +public class InlineDlfcnMethodsStep : AssemblyModifierStep { + + protected override string Name { get; } = "Inline Dlfcn Methods"; + protected override int ErrorCode { get; } = 2250; + + bool strictMode; + + public const string PInvokePrefix = "xamarin_Dlfcn_"; + public const string PInvokeSuffix = "_Native"; + + protected override void TryProcess () + { + strictMode = Configuration.InlineDlfcnMethods == InlineDlfcnMethodsMode.Strict; + base.TryProcess (); + } + + string? current_framework; + protected override bool ProcessType (TypeDefinition type) + { + var modified = false; + if (type.HasMethods) { + if (Frameworks.TryGetFramework (App, type, out Framework? framework) && framework.IsFrameworkUnavailable (App)) { + App.Log (3, $"Type {type.FullName} appears to be part of the '{framework.Name}' framework, which is not available in the current SDK. Skipping inlining Dlfcn calls for this type."); + return modified; + } + + current_framework = framework?.Namespace; + + foreach (var method in type.Methods) + modified |= ProcessMethod (method); + + current_framework = null; + } + return modified; + } + + TypeDefinition GetDlfcnType (MethodDefinition callingMethod) + { + // Check if there's a [Field] attribute with a second string argument (the library/namespace). + // The [Field] attribute can be on the method itself, or on the property the method is a getter/setter for. + var libraryName = callingMethod.HasCustomAttributes ? GetFieldAttributeLibraryName (callingMethod.CustomAttributes) : null; + if (libraryName is null && callingMethod.DeclaringType.HasProperties) { + foreach (var property in callingMethod.DeclaringType.Properties) { + if (property.GetMethod == callingMethod || property.SetMethod == callingMethod) { + libraryName = GetFieldAttributeLibraryName (property.CustomAttributes); + break; + } + } + } + + if (libraryName is not null) + return GetDlfcnType (callingMethod.Module, callingMethod.DeclaringType.Namespace, libraryName); + + return GetDlfcnType (callingMethod.Module, callingMethod.DeclaringType.Namespace); + } + + static string? GetFieldAttributeLibraryName (IList? attributes) + { + if (attributes is null || attributes.Count == 0) + return null; + + foreach (var attrib in attributes) { + if (attrib.AttributeType.Name != "FieldAttribute") + continue; + if (attrib.ConstructorArguments.Count == 2 && + attrib.ConstructorArguments [1].Type.Name == "String" && + attrib.ConstructorArguments [1].Value is string libraryName && + !string.IsNullOrEmpty (libraryName)) { + return libraryName; + } + } + + return null; + } + + // It's important to use a type in the same namespace as the calling code, so that + // we correctly compute which frameworks to link with. + TypeDefinition GetDlfcnType (ModuleDefinition module, string @namespace, string? fieldLibraryName = null) + { + var frameworkOverride = !string.IsNullOrEmpty (fieldLibraryName) ? fieldLibraryName : current_framework; + var ns = string.IsNullOrEmpty (frameworkOverride) ? @namespace : frameworkOverride; + var rv = abr.GetOrCreateType (module, ns, "Dlfcn", out var created); + if (created) { + if (!string.IsNullOrEmpty (frameworkOverride)) { + var attrib = abr.CreateAttribute (abr.ObjectiveCFrameworkAttribute_ctor_String); + attrib.ConstructorArguments.Add (new CustomAttributeArgument (abr.System_String, frameworkOverride)); + rv.CustomAttributes.Add (attrib); + } + } + return rv; + } + + void AddField (string assemblyName, string symbolName) + { + if (!Configuration.InlinedDlfcnFields.TryGetValue (assemblyName, out var set)) { + set = new HashSet (); + Configuration.InlinedDlfcnFields [assemblyName] = set; + } + set.Add (symbolName); + } + + MethodDefinition GetOrCreatePInvokeMethod (MethodDefinition callingMethod, string symbolName) + { + // [DllImport ("__Internal")] + // static extern IntPtr xamarin_Dlfcn_{symbolName}_Native (); + + var methodName = $"{PInvokePrefix}{symbolName}{PInvokeSuffix}"; + var rv = abr.CreateInternalPInvoke (callingMethod.Module, callingMethod.DeclaringType.Namespace, "Dlfcn", methodName, out var created); + if (created) + AddField (callingMethod.Module.Assembly.Name.Name, symbolName); + return rv; + } + + MethodDefinition GetOrCreateGetSymbolMethod (MethodDefinition callingMethod, string symbolName) + { + var dlfcn = GetDlfcnType (callingMethod); + var methodName = $"Get__{symbolName}"; + var symbolMethod = dlfcn.Methods.FirstOrDefault (m => m.Name == methodName); + if (symbolMethod is not null) + return symbolMethod; // already exists, no need to create it again + + // static bool Get__{symbolName}_Initialized; + // static IntPtr Get__{symbolName}_Cached; + // static IntPtr Get__{symbolName} () + // { + // if (!Get__{symbolName}_Initialized) { + // Get__{symbolName}_Cached = xamarin_Dlfcn_{symbolName}_Native (); + // Get__{symbolName}_Initialized = true; + // } + // return Get__{symbolName}_Cached; + // } + + var initializedField = new FieldDefinition ($"Get__{symbolName}_Initialized", FieldAttributes.Private | FieldAttributes.Static, callingMethod.Module.TypeSystem.Boolean); + dlfcn.Fields.Add (initializedField); + + var cachedField = new FieldDefinition ($"Get__{symbolName}_Cached", FieldAttributes.Private | FieldAttributes.Static, abr.System_IntPtr); + dlfcn.Fields.Add (cachedField); + + var intptr = abr.System_IntPtr; + symbolMethod = new MethodDefinition (methodName, MethodAttributes.Public | MethodAttributes.Static, intptr); + dlfcn.Methods.Add (symbolMethod); + + var body = symbolMethod.Body; + var il = body.GetILProcessor (); + + var loadCachedFieldInstruction = il.Create (OpCodes.Ldsfld, cachedField); + + // if (!Get__{symbolName}_Initialized) { + // The initialized field must use volatile semantics to prevent ARM64 store + // reordering: without it, another thread could see Initialized=true before + // the Cached value is written, and return a stale IntPtr.Zero. + // Note that we don't care if we call the P/Invoke more than once, that's + // a safe operation, we just don't want to call it every time. + il.Append (il.Create (OpCodes.Volatile)); + il.Append (il.Create (OpCodes.Ldsfld, initializedField)); + il.Append (il.Create (OpCodes.Brtrue, loadCachedFieldInstruction)); + + // Get__{symbolName}_Cached = xamarin_Dlfcn_{symbolName}_Native (); + il.Append (il.Create (OpCodes.Call, GetOrCreatePInvokeMethod (callingMethod, symbolName))); + il.Append (il.Create (OpCodes.Stsfld, cachedField)); + + // Get__{symbolName}_Initialized = true; + il.Append (il.Create (OpCodes.Ldc_I4_1)); + il.Append (il.Create (OpCodes.Volatile)); + il.Append (il.Create (OpCodes.Stsfld, initializedField)); + + // return Get__{symbolName}_Cached; + il.Append (loadCachedFieldInstruction); + il.Append (il.Create (OpCodes.Ret)); + + return symbolMethod; + } + + MethodDefinition GetOrCreateGetNativeFieldMethod (MethodDefinition callingMethod, TypeReference fieldType, string symbolName) + { + var dlfcn = GetDlfcnType (callingMethod); + var methodName = $"Get__{symbolName}_{fieldType.Name}"; + var rv = dlfcn.Methods.FirstOrDefault (m => m.Name == methodName); + if (rv is not null) + return rv; // already exists, no need to create it again + + // static FieldType Get__{symbolName}_{fieldType} () + // { + // var ptr = Get__{symbolName} (); + // if (ptr == IntPtr.Zero) + // return default; + // + // /* if value type */ + // return *(FieldType*)ptr; + // + // /* if not value type */ + // return Runtime.GetNSObject (*ptr); + // } + + var importedFieldType = callingMethod.Module.ImportReference (fieldType); + rv = new MethodDefinition (methodName, MethodAttributes.Public | MethodAttributes.Static, importedFieldType); + dlfcn.Methods.Add (rv); + + var body = rv.Body; + var il = body.GetILProcessor (); + + var ptrVariable = new VariableDefinition (abr.System_IntPtr); + body.Variables.Add (ptrVariable); + + var loadPointerInstructionStart = il.Create (OpCodes.Ldloc, ptrVariable); + + // var ptr = Get__{symbolName} (); + il.Append (il.Create (OpCodes.Call, GetOrCreateGetSymbolMethod (callingMethod, symbolName))); + il.Append (il.Create (OpCodes.Stloc, ptrVariable)); + + // if (ptr == IntPtr.Zero) + il.Append (il.Create (OpCodes.Ldloc, ptrVariable)); + il.Append (il.Create (OpCodes.Ldsfld, abr.System_IntPtr_Zero)); + il.Append (il.Create (OpCodes.Bne_Un, loadPointerInstructionStart)); + + // return default; + var fullFieldTypeName = fieldType.FullName; + switch (fullFieldTypeName) { + case "System.Byte": + case "System.SByte": + case "System.Int16": + case "System.UInt16": + case "System.Int32": + case "System.UInt32": + il.Append (il.Create (OpCodes.Ldc_I4_0)); + break; + case "System.Int64": + il.Append (il.Create (OpCodes.Ldc_I4_0)); + il.Append (il.Create (OpCodes.Conv_I8)); + break; + case "System.UInt64": + il.Append (il.Create (OpCodes.Ldc_I4_0)); + il.Append (il.Create (OpCodes.Conv_U8)); + break; + case "System.Single": + il.Append (il.Create (OpCodes.Ldc_R4, 0f)); + break; + case "System.Double": + il.Append (il.Create (OpCodes.Ldc_R8, 0.0)); + break; + case "System.IntPtr": + case "System.UIntPtr": + il.Append (il.Create (OpCodes.Ldc_I4_0)); + il.Append (il.Create (OpCodes.Conv_I)); + break; + default: + if (fieldType.IsValueType) { + if (fieldType.IsPrimitive) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2254 /* Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new. */, callingMethod, Errors.MX2254, fieldType.FullName, symbolName, FormatMethod (callingMethod))); + } + var defaultTemporary = new VariableDefinition (importedFieldType); + body.Variables.Add (defaultTemporary); + il.Append (il.Create (OpCodes.Ldloca, defaultTemporary)); + il.Append (il.Create (OpCodes.Initobj, importedFieldType)); + il.Append (il.Create (OpCodes.Ldloc, defaultTemporary)); + } else { + il.Append (il.Create (OpCodes.Ldnull)); + } + break; + } + il.Append (il.Create (OpCodes.Ret)); + + // /* if value type */ + // return *(FieldType*)ptr; + // /* if not value type */ + // return Runtime.GetNSObject (*(IntPtr*)ptr); + il.Append (loadPointerInstructionStart); // il.Create (OpCodes.Ldloc, ptrVariable); + if (fieldType.IsValueType) { + switch (fieldType.FullName) { + case "System.Byte": + il.Append (il.Create (OpCodes.Ldind_U1)); + break; + case "System.SByte": + il.Append (il.Create (OpCodes.Ldind_I1)); + break; + case "System.Int16": + il.Append (il.Create (OpCodes.Ldind_I2)); + break; + case "System.UInt16": + il.Append (il.Create (OpCodes.Ldind_U2)); + break; + case "System.Int32": + il.Append (il.Create (OpCodes.Ldind_I4)); + break; + case "System.UInt32": + il.Append (il.Create (OpCodes.Ldind_U4)); + break; + case "System.Int64": + case "System.UInt64": + il.Append (il.Create (OpCodes.Ldind_I8)); + break; + case "System.Single": + il.Append (il.Create (OpCodes.Ldind_R4)); + break; + case "System.Double": + il.Append (il.Create (OpCodes.Ldind_R8)); + break; + case "System.IntPtr": + case "System.UIntPtr": + il.Append (il.Create (OpCodes.Ldind_I)); + break; + default: + if (fieldType.IsPrimitive) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2254 /* Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new. */, callingMethod, Errors.MX2254, fieldType.FullName, symbolName, FormatMethod (callingMethod))); + } + il.Append (il.Create (OpCodes.Ldobj, importedFieldType)); + break; + } + } else if (IsNSObjectSubclass (fieldType)) { + il.Append (il.Create (OpCodes.Ldind_I)); + var getnsobject = abr.Runtime_GetNSObject_T___System_IntPtr.CreateGenericInstanceMethod (importedFieldType); + il.Append (il.Create (OpCodes.Call, getnsobject)); + } else { + Report (ErrorHelper.CreateError (Configuration.Application, 2256 /* The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new */, callingMethod, Errors.MX2256, fieldType.FullName, symbolName, FormatMethod (callingMethod))); + } + il.Append (il.Create (OpCodes.Ret)); + + return rv; + } + + MethodDefinition GetOrCreateSetNativeFieldMethod (MethodDefinition callingMethod, TypeReference fieldType, string symbolName) + { + var dlfcn = GetDlfcnType (callingMethod); + var methodName = $"Set__{symbolName}_{fieldType.Name}"; + var rv = dlfcn.Methods.FirstOrDefault (m => m.Name == methodName); + if (rv is not null) + return rv; // already exists, no need to create it again + + // static void Set__{symbolName}_{fieldType} ({FieldType} value) + // { + // var ptr = Get__{symbolName} (); + // if (ptr == IntPtr.Zero) + // return; + // + // /* if value type */ + // *(FieldType*)ptr = value; + // + // /* if not value type */ + // *(IntPtr*)ptr = (IntPtr) Runtime.RetainNSObject (value) + // } + // + // Notes: + // * Just like the Dlfcn method(s), this generated code does not release an existing value of a field. + + var importedFieldType = callingMethod.Module.ImportReference (fieldType); + rv = new MethodDefinition (methodName, MethodAttributes.Public | MethodAttributes.Static, abr.System_Void); + rv.Parameters.Add (new ParameterDefinition ("value", ParameterAttributes.None, importedFieldType)); + dlfcn.Methods.Add (rv); + + var body = rv.Body; + var il = body.GetILProcessor (); + + var ptrVariable = new VariableDefinition (abr.System_IntPtr); + body.Variables.Add (ptrVariable); + + var loadPointerInstructionStart = il.Create (OpCodes.Ldloc, ptrVariable); + + // var ptr = Get__{symbolName} (); + il.Append (il.Create (OpCodes.Call, GetOrCreateGetSymbolMethod (callingMethod, symbolName))); + il.Append (il.Create (OpCodes.Stloc, ptrVariable)); + + // if (ptr == IntPtr.Zero) + il.Append (il.Create (OpCodes.Ldloc, ptrVariable)); + il.Append (il.Create (OpCodes.Ldsfld, abr.System_IntPtr_Zero)); + il.Append (il.Create (OpCodes.Bne_Un, loadPointerInstructionStart)); + // return; + il.Append (il.Create (OpCodes.Ret)); + + // /* if value type */ + // *(FieldType*)ptr = value; + // /* if not value type */ + // *(IntPtr*)ptr = (IntPtr) Runtime.RetainNSObject (value) + il.Append (loadPointerInstructionStart); // il.Create (OpCodes.Ldloc, ptrVariable); + il.Append (il.Create (OpCodes.Ldarg_0)); + if (fieldType.IsValueType) { + switch (fieldType.FullName) { + case "System.Byte": + case "System.SByte": + il.Append (il.Create (OpCodes.Stind_I1)); + break; + case "System.Int16": + case "System.UInt16": + il.Append (il.Create (OpCodes.Stind_I2)); + break; + case "System.Int32": + case "System.UInt32": + il.Append (il.Create (OpCodes.Stind_I4)); + break; + case "System.Int64": + case "System.UInt64": + il.Append (il.Create (OpCodes.Stind_I8)); + break; + case "System.Single": + il.Append (il.Create (OpCodes.Stind_R4)); + break; + case "System.Double": + il.Append (il.Create (OpCodes.Stind_R8)); + break; + case "System.IntPtr": + case "System.UIntPtr": + il.Append (il.Create (OpCodes.Stind_I)); + break; + default: + if (fieldType.IsPrimitive) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2254 /* Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new. */, callingMethod, Errors.MX2254, fieldType.FullName, symbolName, FormatMethod (callingMethod))); + } + il.Append (il.Create (OpCodes.Stobj, importedFieldType)); + break; + } + } else if (IsNSObjectSubclass (fieldType)) { + il.Append (il.Create (OpCodes.Call, abr.Runtime_RetainNSObject)); + il.Append (il.Create (OpCodes.Call, abr.NativeObject_op_Implicit_IntPtr)); + il.Append (il.Create (OpCodes.Stind_I)); + } else { + Report (ErrorHelper.CreateError (Configuration.Application, 2256 /* The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new */, callingMethod, Errors.MX2256, fieldType.FullName, symbolName, FormatMethod (callingMethod))); + } + il.Append (il.Create (OpCodes.Ret)); + + return rv; + } + + MethodDefinition GetOrCreateSetNativeStringMethod (MethodDefinition callingMethod, string symbolName) + { + var dlfcn = GetDlfcnType (callingMethod); + var methodName = $"Set__{symbolName}_String"; + var rv = dlfcn.Methods.FirstOrDefault (m => m.Name == methodName); + if (rv is not null) + return rv; // already exists, no need to create it again + + // static FieldType Set__{symbolName}_String (string? value) + // { + // var ptr = Get__{symbolName} (); + // if (ptr == IntPtr.Zero) + // return; + // + // *(IntPtr*)ptr = (IntPtr) CFString.CreateNative (value); + // } + // + // Notes: + // * Just like the Dlfcn method(s), this generated code does not release an existing value of a field. + + rv = new MethodDefinition (methodName, MethodAttributes.Public | MethodAttributes.Static, abr.System_Void); + rv.Parameters.Add (new ParameterDefinition ("value", ParameterAttributes.None, abr.System_String)); + dlfcn.Methods.Add (rv); + + var body = rv.Body; + var il = body.GetILProcessor (); + + var ptrVariable = new VariableDefinition (abr.System_IntPtr); + body.Variables.Add (ptrVariable); + + var loadPointerInstructionStart = il.Create (OpCodes.Ldloc, ptrVariable); + + // var ptr = Get__{symbolName} (); + il.Append (il.Create (OpCodes.Call, GetOrCreateGetSymbolMethod (callingMethod, symbolName))); + il.Append (il.Create (OpCodes.Stloc, ptrVariable)); + + // if (ptr == IntPtr.Zero) + il.Append (il.Create (OpCodes.Ldloc, ptrVariable)); + il.Append (il.Create (OpCodes.Ldsfld, abr.System_IntPtr_Zero)); + il.Append (il.Create (OpCodes.Bne_Un, loadPointerInstructionStart)); + // return; + il.Append (il.Create (OpCodes.Ret)); + + // *(IntPtr*)ptr = (IntPtr) CFString.CreateNative (value); + il.Append (loadPointerInstructionStart); // il.Create (OpCodes.Ldloc, ptrVariable); + il.Append (il.Create (OpCodes.Ldarg_0)); + il.Append (il.Create (OpCodes.Call, abr.CFString_CreateNative)); + il.Append (il.Create (OpCodes.Call, abr.NativeObject_op_Implicit_IntPtr)); + il.Append (il.Create (OpCodes.Stind_I)); + il.Append (il.Create (OpCodes.Ret)); + + return rv; + } + + bool InlineSymbol (string symbolName) + { + // In compatibility mode, only inline symbols from [Field] attributes. + if (!strictMode && !Configuration.FieldSymbols.Contains (symbolName)) + return false; + + // These symbols already come from [Objective-]C code, so they should already be valid identifiers, + // which means we don't have to validate them. + + var requiredSymbol = DerivedLinkContext.RequiredSymbols.Find (symbolName); + if (requiredSymbol?.Mode == SymbolMode.Ignore) + return false; // don't inline if the symbol is to be ignored + + return true; + } + + protected override bool ProcessMethod (MethodDefinition method) + { + var modified = false; + + if (!method.HasBody) + return modified; + + if (method.DeclaringType.Name == "Dlfcn" && method.DeclaringType.Namespace == "ObjCRuntime") + return modified; // don't process the Dlfcn methods themselves + + if (DerivedLinkContext.App.IsSimulatorBuild) { + // if the method or its declaring type aren't available in the simulator, and we're building for the simulator, then don't inline. + if (DerivedLinkContext.HasAvailabilityAttributesShowingUnavailableInSimulator (method, method)) { + App.Log (3, $"Method {method.FullName} is not available in the simulator. Skipping inlining Dlfcn calls for this method."); + return modified; + } + if (DerivedLinkContext.HasAvailabilityAttributesShowingUnavailableInSimulator (method.DeclaringType, method)) { + App.Log (3, $"Type {method.DeclaringType.FullName} is not available in the simulator. Skipping inlining Dlfcn calls for this type."); + return modified; + } + } + + foreach (var instr in method.Body.Instructions) { + if (instr.Operand is not MethodReference mr) + continue; + if (mr.DeclaringType.Name != "Dlfcn" || mr.DeclaringType.Namespace != "ObjCRuntime") + continue; + + // Handle Dlfcn functions of the form (libraryHandle, symbolName) + if (mr.Parameters.Count == 2 && mr.Parameters [0].ParameterType.FullName == "System.IntPtr" && mr.Parameters [1].ParameterType.FullName == "System.String") { + if (instr.Previous.OpCode != OpCodes.Ldstr) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + continue; + } + + // In compatibility mode, only inline symbols from [Field] attributes. + var ldstr = instr.Previous; + if (ldstr.Operand is not string symbolName) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + continue; + } + if (!InlineSymbol (symbolName)) + continue; + + switch (mr.Name) { + // primitive types + case "GetDouble": + case "GetFloat": + case "GetNFloat": + case "GetIntPtr": + case "GetUIntPtr": + case "GetNInt": + case "GetNUInt": + case "GetInt16": + case "GetUInt16": + case "GetInt32": + case "GetUInt32": + case "GetInt64": + case "GetUInt64": + // non-primitive value types + case "GetCGSize": + case "GetCGRect": + // classes + case "GetNSNumber": + case "GetStringConstant": + ldstr.OpCode = OpCodes.Pop; // just pop the library handle/name, we don't need it + ldstr.Operand = null; + + instr.OpCode = OpCodes.Call; + instr.Operand = GetOrCreateGetNativeFieldMethod (method, mr.ReturnType, symbolName); + + modified = true; + continue; + case "GetStruct": + if (mr is not GenericInstanceMethod gim || gim.GenericArguments.Count != 1) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + continue; + } + var returnType = gim.GenericArguments [0]; + if (returnType.IsGenericInstance) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + continue; + } + + ldstr.OpCode = OpCodes.Pop; // just pop the library handle/name, we don't need it + ldstr.Operand = null; + + instr.OpCode = OpCodes.Call; + instr.Operand = GetOrCreateGetNativeFieldMethod (method, returnType, symbolName); + + modified = true; + continue; + case "GetIndirect": + case "dlsym": + ldstr.OpCode = OpCodes.Pop; // just pop the library handle/name, we don't need it + ldstr.Operand = null; + + instr.OpCode = OpCodes.Call; + instr.Operand = GetOrCreateGetSymbolMethod (method, symbolName); + + modified = true; + continue; + } + } + + // Handle Dlfcn functions of the form (RTLD, symbolName) + if (mr.Parameters.Count == 2 && mr.Parameters [0].ParameterType.FullName == "ObjCRuntime.Dlfcn/RTLD" && mr.Parameters [1].ParameterType.FullName == "System.String") { + if (instr.Previous.OpCode != OpCodes.Ldstr) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + continue; + } + var ldstr = instr.Previous; + if (ldstr.Operand is not string symbolName) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + continue; + } + + if (!InlineSymbol (symbolName)) + continue; + + + switch (mr.Name) { + case "dlsym": + ldstr.OpCode = OpCodes.Pop; // just pop the library handle/name, we don't need it + ldstr.Operand = null; + + instr.OpCode = OpCodes.Call; + instr.Operand = GetOrCreateGetSymbolMethod (method, symbolName); + + modified = true; + continue; + } + } + + // Handle Dlfcn functions of the form (libraryName, symbolName) + if (mr.Parameters.Count == 2 && mr.Parameters [0].ParameterType.FullName == "System.String" && mr.Parameters [1].ParameterType.FullName == "System.String") { + if (instr.Previous.OpCode != OpCodes.Ldstr) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + continue; + } + var ldstr = instr.Previous; + if (ldstr.Operand is not string symbolName) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + continue; + } + + if (!InlineSymbol (symbolName)) + continue; + + switch (mr.Name) { + // primitive types + case "SlowGetDouble": + case "SlowGetIntPtr": + case "SlowGetInt32": + case "SlowGetInt64": + // classes + case "SlowGetStringConstant": + ldstr.OpCode = OpCodes.Pop; // just pop the library handle/name, we don't need it + ldstr.Operand = null; + + instr.OpCode = OpCodes.Call; + instr.Operand = GetOrCreateGetNativeFieldMethod (method, mr.ReturnType, symbolName); + + modified = true; + continue; + } + } + + // Handle Dlfcn functions of the form void (libraryHandle|libraryName, symbolName, value) + if (mr.Parameters.Count == 3 && + (mr.Parameters [0].ParameterType.FullName == "System.String" || mr.Parameters [0].ParameterType.FullName == "System.IntPtr") && + mr.Parameters [1].ParameterType.FullName == "System.String") { + + var ins = instr; + Instruction? ldstr = null; + + // skip any call instructions that take a single argument and return a value, as those are likely to be calls to op_Implicit or op_Explicit functions. + while (ins.Previous.OpCode == OpCodes.Call && ins.Previous.Operand is MethodReference prevMr && !prevMr.ReturnType.Is ("System", "Void") && prevMr.HasParameters && prevMr.Parameters.Count == 1) { + ins = ins.Previous; + } + + switch (ins.Previous.OpCode.StackBehaviourPop) { + case StackBehaviour.Pop0: + switch (ins.Previous.OpCode.StackBehaviourPush) { + case StackBehaviour.Push1: + case StackBehaviour.Pushi: + case StackBehaviour.Pushi8: + case StackBehaviour.Pushr4: + case StackBehaviour.Pushr8: + case StackBehaviour.Pushref: + ldstr = ins.Previous.Previous; + break; + } + break; + case StackBehaviour.Pop1: + case StackBehaviour.Popref: + switch (ins.Previous.OpCode.StackBehaviourPush) { + case StackBehaviour.Push1: + case StackBehaviour.Pushi: + case StackBehaviour.Pushi8: + case StackBehaviour.Pushr4: + case StackBehaviour.Pushr8: + case StackBehaviour.Pushref: + ldstr = ins.Previous.Previous.Previous; + break; + } + break; + } + if (ldstr is null) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255, method, "Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. Unknown instruction sequence: {2} ({3}/{4}). The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new.", FormatMethod (mr), FormatMethod (method), instr.Previous, instr.Previous.OpCode.StackBehaviourPop, instr.Previous.OpCode.StackBehaviourPush)); + continue; + } + + if (ldstr.OpCode != OpCodes.Ldstr) { + // Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255, method, "Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. Expected 'ldstr' opcode, got '{2}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new.", FormatMethod (mr), FormatMethod (method), ldstr)); + continue; + } + if (ldstr.Operand is not string symbolName) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + continue; + } + + if (!InlineSymbol (symbolName)) + continue; + + switch (mr.Name) { + // primitive types + case "SetSByte": + case "SetByte": + case "SetInt16": + case "SetUInt16": + case "SetInt32": + case "SetUInt32": + case "SetInt64": + case "SetUInt64": + case "SetArray": + case "SetObject": + case "SetNInt": + case "SetNUInt": + case "SetNFloat": + case "SetUIntPtr": + case "SetIntPtr": + case "SetCGSize": + case "SetDouble": + case "SetFloat": + ldstr.OpCode = OpCodes.Pop; // just pop the library handle/name, we don't need it + ldstr.Operand = null; + + instr.OpCode = OpCodes.Call; + instr.Operand = GetOrCreateSetNativeFieldMethod (method, mr.Parameters [2].ParameterType, symbolName); + + modified = true; + continue; + // classes + case "SetString": + if (mr.Parameters [2].ParameterType.FullName == "System.String") { + ldstr.OpCode = OpCodes.Pop; // just pop the library handle/name, we don't need it + ldstr.Operand = null; + + instr.OpCode = OpCodes.Call; + instr.Operand = GetOrCreateSetNativeStringMethod (method, symbolName); + modified = true; + continue; + } else if (mr.Parameters [2].ParameterType.FullName == "Foundation.NSString") { + ldstr.OpCode = OpCodes.Pop; // just pop the library handle/name, we don't need it + ldstr.Operand = null; + + instr.OpCode = OpCodes.Call; + instr.Operand = GetOrCreateSetNativeFieldMethod (method, mr.Parameters [2].ParameterType, symbolName); + modified = true; + continue; + } + + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + continue; + case "CachePointer": + if (!(mr.Parameters [2].ParameterType is PointerType pt && pt.ElementType.FullName == "System.IntPtr")) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + continue; + } + + // + // we're going to replace the entire method body with something like: + // + // var ptr = Get__{symbolName} (); + // if (ptr == IntPtr.Zero) + // return IntPtr.Zero; + // return *(IntPtr *) ptr; + // + + if (!IsGeneratedCachePointerMethod (method, out var cachePointerSymbolName, out var failureMessage)) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2257 /* Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2257, failureMessage, FormatMethod (method))); + continue; + } + + if (cachePointerSymbolName != symbolName) { + Report (ErrorHelper.CreateWarning (Configuration.Application, 2257 /* Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2257, $"Could not determine symbol name", FormatMethod (method))); + continue; + } + + ldstr.OpCode = OpCodes.Pop; // just pop the library handle/name, we don't need it + ldstr.Operand = null; + + method.Body.Instructions.Clear (); + var il = method.Body.GetILProcessor (); + var ptrVariable = new VariableDefinition (abr.System_IntPtr); + method.Body.Variables.Add (ptrVariable); + var loadPointerInstructionStart = il.Create (OpCodes.Ldloc, ptrVariable); + // var ptr = Get__{symbolName} () + il.Append (il.Create (OpCodes.Call, GetOrCreateGetSymbolMethod (method, symbolName))); + il.Append (il.Create (OpCodes.Stloc, ptrVariable)); + // if (ptr == IntPtr.Zero) + il.Append (il.Create (OpCodes.Ldloc, ptrVariable)); + il.Append (il.Create (OpCodes.Brtrue_S, loadPointerInstructionStart)); + // return IntPtr.Zero; + il.Append (il.Create (OpCodes.Ldc_I4_0)); + il.Append (il.Create (OpCodes.Conv_I)); + il.Append (il.Create (OpCodes.Ret)); + // return *(IntPtr *) ptr; + il.Append (loadPointerInstructionStart); // il.Create (OpCodes.Ldloc, ptrVariable) + il.Append (il.Create (OpCodes.Ldind_I)); + il.Append (il.Create (OpCodes.Ret)); + + modified = true; + return modified; // we replace the whole method body, so no need to continue processing the method + } + } + + switch (mr.Name) { + case "_dlopen": // nothing to inline here + case "dlopen": // nothing to inline here + case "dlerror": // nothing to inline here + continue; + case "dlclose": + // It might be possible to just remove these calls, because + // (PENDING CONFIRMATION) I believe dlclose is a no-op on at least some Apple platforms. + continue; + default: + Report (ErrorHelper.CreateWarning (Configuration.Application, 2255 /* Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. */, method, Errors.MX2255, FormatMethod (mr), FormatMethod (method))); + continue; + } + } + + return modified; + } + + static bool IsGeneratedCachePointerMethod (MethodDefinition method, [NotNullWhen (true)] out string? fieldName, [NotNullWhen (false)] out string? failureMessage) + { + fieldName = null; + failureMessage = null; + + // The following code: + // + // get { + // fixed (IntPtr *storage = &values [8]) + // return Dlfcn.CachePointer (Libraries.XYZ.Handle, "...", storage); + // } + // + // has the following IL sequence: + // + // IL_0000: ldsfld System.IntPtr[] ::values + // IL_0005: ldc.i4.0 + // IL_0006: ldelema System.IntPtr + // IL_000b: stloc.1 + // IL_000c: ldloc.1 + // IL_000d: conv.u + // IL_000e: stloc.0 + // IL_000f: ldsfld System.IntPtr ObjCRuntime.Libraries/::Handle + // IL_0014: ldstr "FIELDNAME" + // IL_0019: ldloc.0 + // IL_001a: call System.IntPtr ObjCRuntime.Dlfcn::CachePointer(System.IntPtr,System.String,System.IntPtr*) + // IL_0020: stloc.2 + // IL_0021: br.s IL_0023 + // IL_0023: ldloc.2 + // IL_001f: ret + // + // (the indented code can happen for debug builds) + // + if (!method.HasBody) { + failureMessage = "Method has no body"; + return false; + } + var body = method.Body; + if (body.Instructions.Count == 0) { + failureMessage = "Method has no instructions"; + return false; + } + + var instr = body.Instructions.First (); + var isLast = false; + + bool AssertOpCode ([NotNullWhen (false)] out string? failureMessage, params OpCode [] expected) + { + failureMessage = null; + + while (instr.OpCode == OpCodes.Nop && instr.Next is not null) + instr = instr.Next; + + if (!expected.Any (v => v == instr.OpCode)) { + failureMessage = $"Expected any of '{string.Join (", ", expected.Select (v => v.ToString ()))}' as instruction at offset IL{instr.Offset:X4}, got: {instr}"; + return false; + } + + if (instr.Next is null) { + if (isLast) + return true; + failureMessage = $"Expected more instructions after {instr}."; + return false; + } + + if (isLast) { + failureMessage = $"Got more instructions than expected after {instr}."; + return false; + } + + instr = instr.Next; + + return true; + } + + if (!AssertOpCode (out failureMessage, OpCodes.Ldsfld)) + return false; + + var ldcOpcodes = new OpCode [] { OpCodes.Ldc_I4_0, OpCodes.Ldc_I4_1, OpCodes.Ldc_I4_2, OpCodes.Ldc_I4_3, OpCodes.Ldc_I4_4, OpCodes.Ldc_I4_5, OpCodes.Ldc_I4_6, OpCodes.Ldc_I4_7, OpCodes.Ldc_I4_8, OpCodes.Ldc_I4, OpCodes.Ldc_I4_S }; + if (!AssertOpCode (out failureMessage, ldcOpcodes)) + return false; + + if (!AssertOpCode (out failureMessage, OpCodes.Ldelema)) + return false; + + var stlocOpcodes = new OpCode [] { OpCodes.Stloc_0, OpCodes.Stloc_1, OpCodes.Stloc_2, OpCodes.Stloc_3, OpCodes.Stloc, OpCodes.Stloc_S }; + if (!AssertOpCode (out failureMessage, stlocOpcodes)) + return false; + + var ldlocOpcodes = new OpCode [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3, OpCodes.Ldloc, OpCodes.Ldloc_S }; + if (!AssertOpCode (out failureMessage, ldlocOpcodes)) + return false; + + if (!AssertOpCode (out failureMessage, OpCodes.Conv_U)) + return false; + + if (!AssertOpCode (out failureMessage, stlocOpcodes)) + return false; + + if (!AssertOpCode (out failureMessage, OpCodes.Ldsfld)) + return false; + + if (!AssertOpCode (out failureMessage, OpCodes.Ldstr)) + return false; + fieldName = (string) instr.Previous.Operand; + + if (!AssertOpCode (out failureMessage, ldlocOpcodes)) + return false; + + if (!AssertOpCode (out failureMessage, OpCodes.Call)) + return false; + + if (stlocOpcodes.Any (v => v == instr.OpCode)) { + if (!AssertOpCode (out failureMessage, stlocOpcodes)) + return false; + + var branchOpcodes = new OpCode [] { OpCodes.Br, OpCodes.Br_S }; + if (!AssertOpCode (out failureMessage, branchOpcodes)) + return false; + + if (!AssertOpCode (out failureMessage, ldlocOpcodes)) + return false; + } + + isLast = true; + return AssertOpCode (out failureMessage, OpCodes.Ret); + } + + static string FormatMethod (MethodReference method) + { + var rv = method.FullName; + var idx = rv.IndexOf (' '); + if (idx > 0) + rv = rv.Substring (idx + 1); + return rv; + } + + static bool IsNSObjectSubclass (TypeReference type) + { + var resolved = type.Resolve (); + while (resolved is not null) { + if (resolved.FullName == "Foundation.NSObject") + return true; + if (resolved.BaseType is null) + break; + resolved = resolved.BaseType.Resolve (); + } + return false; + } +} diff --git a/tools/dotnet-linker/Steps/ManagedRegistrarLookupTablesStep.cs b/tools/dotnet-linker/Steps/ManagedRegistrarLookupTablesStep.cs index a0d764222e29..68bbe468e009 100644 --- a/tools/dotnet-linker/Steps/ManagedRegistrarLookupTablesStep.cs +++ b/tools/dotnet-linker/Steps/ManagedRegistrarLookupTablesStep.cs @@ -330,7 +330,7 @@ void GenerateConstructNSObject (TypeDefinition registrarType) foreach (var type in types) { var ctorRef = FindNSObjectConstructor (type); if (ctorRef is null) { - Driver.Log (9, $"Cannot include {type.FullName} in ConstructNSObject because it doesn't have a suitable constructor"); + App.Log (9, $"Cannot include {type.FullName} in ConstructNSObject because it doesn't have a suitable constructor"); continue; } @@ -652,7 +652,7 @@ void GenerateLookupUnmanagedFunction (TypeDefinition registrar_type, IList 0) { // All the methods in a given assembly will have consecutive IDs (but might not start at 0). if (trampolineInfos.First ().Id + trampolineInfos.Count - 1 != trampolineInfos.Last ().Id) diff --git a/tools/dotnet-linker/Steps/ManagedRegistrarStep.cs b/tools/dotnet-linker/Steps/ManagedRegistrarStep.cs index cfc23620e1d7..70c4cc72a7bf 100644 --- a/tools/dotnet-linker/Steps/ManagedRegistrarStep.cs +++ b/tools/dotnet-linker/Steps/ManagedRegistrarStep.cs @@ -1315,7 +1315,7 @@ void GenerateConversionToNative (MethodDefinition method, ILProcessor il, TypeRe } else if (underlyingNativeType.Is ("Foundation", "NSString")) { if (!StaticRegistrar.IsSmartEnum (underlyingManagedType, out var getConstantMethod, out var getValueMethod)) { // method linked away!? this should already be verified - ErrorHelper.Show (ErrorHelper.CreateError (99, Errors.MX0099, $"the smart enum {underlyingManagedType.FullName} doesn't seem to be a smart enum after all")); + ErrorHelper.Show (App, ErrorHelper.CreateError (99, Errors.MX0099, $"the smart enum {underlyingManagedType.FullName} doesn't seem to be a smart enum after all")); return; } diff --git a/tools/dotnet-linker/Steps/PreserveBlockCodeStep.cs b/tools/dotnet-linker/Steps/PreserveBlockCodeStep.cs index 6b22aaade307..5a25a54ca27d 100644 --- a/tools/dotnet-linker/Steps/PreserveBlockCodeStep.cs +++ b/tools/dotnet-linker/Steps/PreserveBlockCodeStep.cs @@ -33,12 +33,16 @@ protected override bool IsActiveFor (AssemblyDefinition assembly) protected override bool ProcessType (TypeDefinition type) { - if (!GetMembersToPreserve (type, out var field, out var method)) - return false; - var modified = false; - modified |= abr.AddDynamicDependencyAttributeToStaticConstructor (type, field); - modified |= abr.AddDynamicDependencyAttributeToStaticConstructor (type, method); + + if (GetMembersToPreserve (type, out var field, out var method)) { + modified |= abr.AddDynamicDependencyAttributeToStaticConstructor (type, field); + modified |= abr.AddDynamicDependencyAttributeToStaticConstructor (type, method); + } + + if (GetNewStyleMethodToPreserve (type, out var invokeMethod)) + modified |= abr.AddDynamicDependencyAttributeToStaticConstructor (type, invokeMethod); + return modified; } @@ -103,5 +107,71 @@ static internal void Invoke (IntPtr block, int magic_number) // The type was used, so preserve the method and field return true; } + + // New-style block proxy types use [UnmanagedCallersOnly] on the Invoke method + // and don't have a Handler field. They are generated when the bgen tool emits + // function pointer-based block trampolines. We need to preserve the Invoke method + // because the runtime looks it up via reflection in Blocks.GetBlockForDelegate. + public static bool GetNewStyleMethodToPreserve (TypeDefinition type, [NotNullWhen (true)] out MethodDefinition? method) + { + method = null; + + /* For the following class: + + static internal class SDRegistrarTestBlock { + [UnmanagedCallersOnly] + [UserDelegateType (typeof (RegistrarTestBlock))] + internal static unsafe uint Invoke (IntPtr block, uint magic) + { + } + internal static unsafe BlockLiteral CreateBlock (RegistrarTestBlock callback) + { + delegate* unmanaged trampoline = &Invoke; + return new BlockLiteral (trampoline, callback, typeof (SDRegistrarTestBlock), nameof (Invoke)); + } + } + + * We need to make sure the linker doesn't remove the Invoke method. + */ + + // The type must be abstract, sealed (static class) and nested + if (!type.IsAbstract || !type.IsSealed || !type.IsNested) + return false; + + // The type must not have fields (old-style types have a Handler field and are handled by GetMembersToPreserve) + if (type.HasFields) + return false; + + // The type is nested inside ObjCRuntime.Trampolines class + var nestingType = type.DeclaringType; + if (!nestingType.Is ("ObjCRuntime", "Trampolines")) + return false; + + if (!type.HasMethods) + return false; + + // The class has an 'Invoke' method with [UnmanagedCallersOnly] and [UserDelegateType] attributes + method = type.Methods.SingleOrDefault (v => { + if (v.Name != "Invoke") + return false; + if (!v.HasParameters) + return false; + if (!v.HasCustomAttributes) + return false; + var hasUnmanagedCallersOnly = false; + var hasUserDelegateType = false; + foreach (var attr in v.CustomAttributes) { + if (attr.AttributeType.Name == "UnmanagedCallersOnlyAttribute") + hasUnmanagedCallersOnly = true; + else if (attr.AttributeType.Name == "UserDelegateTypeAttribute") + hasUserDelegateType = true; + if (hasUnmanagedCallersOnly && hasUserDelegateType) + break; + } + return hasUnmanagedCallersOnly && hasUserDelegateType; + }); + + return method is not null; + } } } diff --git a/tools/dotnet-linker/dotnet-linker.csproj b/tools/dotnet-linker/dotnet-linker.csproj index 5b8b4c66d39e..c3ff1f126681 100644 --- a/tools/dotnet-linker/dotnet-linker.csproj +++ b/tools/dotnet-linker/dotnet-linker.csproj @@ -4,9 +4,7 @@ dotnet_linker $(DefineConstants);BUNDLER true - true false - enable true $(NoWarn);CS1591 @@ -73,6 +71,9 @@ external/tools/common/FileUtils.cs + + external/tools/common/IToolLog.cs + external/tools/common/LinkMode.cs diff --git a/tools/linker/CoreOptimizeGeneratedCode.cs b/tools/linker/CoreOptimizeGeneratedCode.cs index 85cf938052a0..c33d231aeb66 100644 --- a/tools/linker/CoreOptimizeGeneratedCode.cs +++ b/tools/linker/CoreOptimizeGeneratedCode.cs @@ -67,28 +67,33 @@ static protected void Nop (Instruction ins) ins.Operand = null; } - internal static bool ValidateInstruction (MethodDefinition caller, Instruction ins, string operation, Code expected) + internal static bool ValidateInstruction (OptimizeGeneratedCodeData data, MethodDefinition caller, Instruction ins, string operation, Code expected) + { + return ValidateInstruction (data.App, caller, ins, operation, expected); + } + + internal static bool ValidateInstruction (IToolLog log, MethodDefinition caller, Instruction ins, string operation, Code expected) { if (ins.OpCode.Code != expected) { - Driver.Log (1, "Could not {0} in {1} at offset {2}, expected {3} got {4}", operation, caller, ins.Offset, expected, ins); + log.Log (1, "Could not {0} in {1} at offset {2}, expected {3} got {4}", operation, caller, ins.Offset, expected, ins); return false; } return true; } - internal static bool ValidateInstruction (MethodDefinition caller, Instruction ins, string operation, params Code [] expected) + internal static bool ValidateInstruction (OptimizeGeneratedCodeData data, MethodDefinition caller, Instruction ins, string operation, params Code [] expected) { foreach (var code in expected) { if (ins.OpCode.Code == code) return true; } - Driver.Log (1, "Could not {0} in {1} at offset {2}, expected any of [{3}] got {4}", operation, caller, ins.Offset, string.Join (", ", expected), ins); + data.App.Log (1, "Could not {0} in {1} at offset {2}, expected any of [{3}] got {4}", operation, caller, ins.Offset, string.Join (", ", expected), ins); return false; } - static int? GetConstantValue (Instruction? ins) + static int? GetConstantValue (OptimizeGeneratedCodeData data, Instruction? ins) { if (ins is null) return null; @@ -159,13 +164,13 @@ internal static bool ValidateInstruction (MethodDefinition caller, Instruction i #endif default: #if DEBUG - Driver.Log (9, "Unknown conditional instruction: {0}", ins); + data.App.Log (9, "Unknown conditional instruction: {0}", ins); #endif return null; } } - static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic.Collection instructions, bool [] reachable, int start, int end) + static bool MarkInstructions (OptimizeGeneratedCodeData data, MethodDefinition method, Mono.Collections.Generic.Collection instructions, bool [] reachable, int start, int end) { if (reachable [start]) return true; // We've already marked this section of code @@ -178,7 +183,7 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. case FlowControl.Branch: // Unconditional branch, we continue marking from the instruction that we branch to. var br_target = (Instruction) ins.Operand; - return MarkInstructions (method, instructions, reachable, instructions.IndexOf (br_target), instructions.Count); + return MarkInstructions (data, method, instructions, reachable, instructions.IndexOf (br_target), instructions.Count); case FlowControl.Cond_Branch: // Conditional instruction, we need to check if we can calculate a constant value for the condition var cond_target = ins.Operand as Instruction; @@ -190,26 +195,26 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. // FIXME: calculate the potential constant branch (currently there are no optimizable methods where the switch condition is constant, so this is not needed for now) var targets = ins.Operand as Instruction []; if (targets is null) { - Driver.Log (4, "Can't optimize {0} because of unknown target of branch instruction {1} {2}", method, ins, ins.Operand); + data.App.Log (4, "Can't optimize {0} because of unknown target of branch instruction {1} {2}", method, ins, ins.Operand); return false; } foreach (var target in targets) { // not constant, continue marking both this code sequence and the branched sequence - if (!MarkInstructions (method, instructions, reachable, instructions.IndexOf (target), end)) + if (!MarkInstructions (data, method, instructions, reachable, instructions.IndexOf (target), end)) return false; } - return MarkInstructions (method, instructions, reachable, instructions.IndexOf (ins.Next), end); + return MarkInstructions (data, method, instructions, reachable, instructions.IndexOf (ins.Next), end); } if (cond_target is null) { - Driver.Log (4, "Can't optimize {0} because of unknown target of branch instruction {1} {2}", method, ins, ins.Operand); + data.App.Log (4, "Can't optimize {0} because of unknown target of branch instruction {1} {2}", method, ins, ins.Operand); return false; } switch (ins.OpCode.Code) { case Code.Brtrue: case Code.Brtrue_S: { - var v = GetConstantValue (ins.Previous); + var v = GetConstantValue (data, ins.Previous); if (v.HasValue) branch = v.Value != 0; cond_instruction_count = 2; @@ -217,7 +222,7 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. } case Code.Brfalse: case Code.Brfalse_S: { - var v = GetConstantValue (ins.Previous); + var v = GetConstantValue (data, ins.Previous); if (v.HasValue) branch = v.Value == 0; cond_instruction_count = 2; @@ -225,8 +230,8 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. } case Code.Beq: case Code.Beq_S: { - var x1 = GetConstantValue (ins.Previous?.Previous); - var x2 = GetConstantValue (ins.Previous); + var x1 = GetConstantValue (data, ins.Previous?.Previous); + var x2 = GetConstantValue (data, ins.Previous); if (x1.HasValue && x2.HasValue) branch = x1.Value == x2.Value; cond_instruction_count = 3; @@ -234,8 +239,8 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. } case Code.Bne_Un: case Code.Bne_Un_S: { - var x1 = GetConstantValue (ins.Previous?.Previous); - var x2 = GetConstantValue (ins.Previous); + var x1 = GetConstantValue (data, ins.Previous?.Previous); + var x2 = GetConstantValue (data, ins.Previous); if (x1.HasValue && x2.HasValue) branch = x1.Value != x2.Value; cond_instruction_count = 3; @@ -245,8 +250,8 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. case Code.Ble_S: case Code.Ble_Un: case Code.Ble_Un_S: { - var x1 = GetConstantValue (ins.Previous?.Previous); - var x2 = GetConstantValue (ins.Previous); + var x1 = GetConstantValue (data, ins.Previous?.Previous); + var x2 = GetConstantValue (data, ins.Previous); if (x1.HasValue && x2.HasValue) branch = x1.Value <= x2.Value; cond_instruction_count = 3; @@ -256,8 +261,8 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. case Code.Blt_S: case Code.Blt_Un: case Code.Blt_Un_S: { - var x1 = GetConstantValue (ins.Previous?.Previous); - var x2 = GetConstantValue (ins.Previous); + var x1 = GetConstantValue (data, ins.Previous?.Previous); + var x2 = GetConstantValue (data, ins.Previous); if (x1.HasValue && x2.HasValue) branch = x1.Value < x2.Value; cond_instruction_count = 3; @@ -267,8 +272,8 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. case Code.Bge_S: case Code.Bge_Un: case Code.Bge_Un_S: { - var x1 = GetConstantValue (ins.Previous?.Previous); - var x2 = GetConstantValue (ins.Previous); + var x1 = GetConstantValue (data, ins.Previous?.Previous); + var x2 = GetConstantValue (data, ins.Previous); if (x1.HasValue && x2.HasValue) branch = x1.Value >= x2.Value; cond_instruction_count = 3; @@ -278,15 +283,15 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. case Code.Bgt_S: case Code.Bgt_Un: case Code.Bgt_Un_S: { - var x1 = GetConstantValue (ins.Previous?.Previous); - var x2 = GetConstantValue (ins.Previous); + var x1 = GetConstantValue (data, ins.Previous?.Previous); + var x2 = GetConstantValue (data, ins.Previous); if (x1.HasValue && x2.HasValue) branch = x1.Value > x2.Value; cond_instruction_count = 3; break; } default: - Driver.Log ("Can't optimize {0} because of unknown branch instruction: {1}", method, ins); + data.App.Log ("Can't optimize {0} because of unknown branch instruction: {1}", method, ins); break; } @@ -294,13 +299,13 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. // Make sure nothing else in the method branches into the middle of our supposedly constant condition, // bypassing our constant calculation. Note that it's not a bad to branch to the _first_ instruction in // the sequence (thus the +2 here), just into the middle of it. - if (AnyBranchTo (instructions, instructions [i - cond_instruction_count + 2], ins)) + if (AnyBranchTo (data, instructions, instructions [i - cond_instruction_count + 2], ins)) branch = null; } if (!branch.HasValue) { // not constant, continue marking both this code sequence and the branched sequence - if (!MarkInstructions (method, instructions, reachable, instructions.IndexOf (cond_target), end)) + if (!MarkInstructions (data, method, instructions, reachable, instructions.IndexOf (cond_target), end)) return false; } else { // we can remove the branch (and the code that loads the condition), so we mark those instructions as dead. @@ -310,7 +315,7 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. // Now continue marking according to whether we branched or not if (branch.Value) { // branch always taken - return MarkInstructions (method, instructions, reachable, instructions.IndexOf (cond_target), end); + return MarkInstructions (data, method, instructions, reachable, instructions.IndexOf (cond_target), end); } else { // branch never taken // continue looping @@ -329,7 +334,7 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. case FlowControl.Meta: case FlowControl.Phi: default: - Driver.Log (4, "Can't optimize {0} because of unknown flow control for: {1}", method, ins); + data.App.Log (4, "Can't optimize {0} because of unknown flow control for: {1}", method, ins); return false; } } @@ -338,10 +343,10 @@ static bool MarkInstructions (MethodDefinition method, Mono.Collections.Generic. } // Check if there are any branches in the instructions that branch to anywhere between 'first' and 'last' instructions (both inclusive). - static bool AnyBranchTo (Mono.Collections.Generic.Collection instructions, Instruction first, Instruction last) + static bool AnyBranchTo (OptimizeGeneratedCodeData data, Mono.Collections.Generic.Collection instructions, Instruction first, Instruction last) { if (first.Offset > last.Offset) { - Driver.Log ($"Broken assumption: {first} is after {last}"); + data.App.Log ($"Broken assumption: {first} is after {last}"); return true; // This is the safe thing to do, since it will prevent inlining } @@ -373,7 +378,7 @@ static bool EliminateDeadCode (OptimizeGeneratedCodeData data, MethodDefinition // marking all reachable instructions. Any non-reachable instructions at the end // can be removed. - if (!MarkInstructions (caller, instructions, reachable, 0, instructions.Count)) + if (!MarkInstructions (data, caller, instructions, reachable, 0, instructions.Count)) return modified; // Handle exception handlers specially, they do not follow normal code flow. @@ -407,19 +412,19 @@ static bool EliminateDeadCode (OptimizeGeneratedCodeData data, MethodDefinition } } if (!allNops) { - if (!MarkInstructions (caller, instructions, reachable, instructions.IndexOf (eh.HandlerStart), instructions.IndexOf (eh.HandlerEnd))) + if (!MarkInstructions (data, caller, instructions, reachable, instructions.IndexOf (eh.HandlerStart), instructions.IndexOf (eh.HandlerEnd))) return modified; } break; case ExceptionHandlerType.Finally: // finally clauses are always executed, even if the protected region is empty - if (!MarkInstructions (caller, instructions, reachable, instructions.IndexOf (eh.HandlerStart), instructions.IndexOf (eh.HandlerEnd))) + if (!MarkInstructions (data, caller, instructions, reachable, instructions.IndexOf (eh.HandlerStart), instructions.IndexOf (eh.HandlerEnd))) return modified; break; case ExceptionHandlerType.Fault: case ExceptionHandlerType.Filter: // FIXME: and until fixed, exit gracefully without doing anything - Driver.Log (4, "Unhandled exception handler: {0}, skipping dead code elimination for {1}", eh.HandlerType, caller); + data.App.Log (4, "Unhandled exception handler: {0}, skipping dead code elimination for {1}", eh.HandlerType, caller); return modified; } } @@ -475,7 +480,7 @@ static bool EliminateDeadCode (OptimizeGeneratedCodeData data, MethodDefinition case FlowControl.Cond_Branch: var target = (Instruction) ins.Operand; if (target.Offset > last_reachable_offset) { - Driver.Log (4, "Can't optimize {0} because of branching beyond last instruction alive: {1}", caller, ins); + data.App.Log (4, "Can't optimize {0} because of branching beyond last instruction alive: {1}", caller, ins); return modified; } break; @@ -483,13 +488,13 @@ static bool EliminateDeadCode (OptimizeGeneratedCodeData data, MethodDefinition } } #if false - Console.WriteLine ($"{caller.FullName}:"); + data.App.Log ($"{caller.FullName}:"); for (int i = 0; i < reachable.Length; i++) { - Console.WriteLine ($"{(reachable [i] ? " " : "- ")} {instructions [i]}"); + data.App.Log ($"{(reachable [i] ? " " : "- ")} {instructions [i]}"); if (!reachable [i]) Nop (instructions [i]); } - Console.WriteLine (); + data.App.Log (""); #endif // Exterminate, exterminate, exterminate @@ -648,7 +653,7 @@ static bool ProcessEnsureUIThread (OptimizeGeneratedCodeData data, MethodDefinit // Verify a few assumptions before doing anything const string operation = "remove calls to [NS|UI]Application::EnsureUIThread"; - if (!ValidateInstruction (caller, ins, operation, Code.Call)) + if (!ValidateInstruction (data, caller, ins, operation, Code.Call)) return false; // This is simple: just remove the call @@ -680,10 +685,10 @@ static bool ProcessIsDirectBinding (OptimizeGeneratedCodeData data, MethodDefini return false; // Verify a few assumptions before doing anything - if (!ValidateInstruction (caller, ins.Previous, operation, Code.Ldarg_0)) + if (!ValidateInstruction (data, caller, ins.Previous, operation, Code.Ldarg_0)) return false; - if (!ValidateInstruction (caller, ins, operation, Code.Call)) + if (!ValidateInstruction (data, caller, ins, operation, Code.Call)) return false; // Clearing the branch succeeded, so clear the condition too @@ -742,10 +747,10 @@ static bool ProcessSetupBlock (OptimizeGeneratedCodeData data, MethodDefinition prev = prev.Previous; // Skip any nops. if (prev.OpCode.StackBehaviourPush != StackBehaviour.Push1) { //todo: localize mmp error 2106 - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106, caller, ins.Offset, mr.Name, prev)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106, caller, ins.Offset, mr.Name, prev)); return false; } else if (prev.OpCode.StackBehaviourPop != StackBehaviour.Pop0) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106, caller, ins.Offset, mr.Name, prev)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106, caller, ins.Offset, mr.Name, prev)); return false; } @@ -756,22 +761,22 @@ static bool ProcessSetupBlock (OptimizeGeneratedCodeData data, MethodDefinition // Then find the type of the previous instruction (the first argument to SetupBlock[Unsafe]) var trampolineDelegateType = GetPushedType (caller, loadTrampolineInstruction); if (trampolineDelegateType is null) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106_A, caller, ins.Offset, mr.Name, loadTrampolineInstruction)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106_A, caller, ins.Offset, mr.Name, loadTrampolineInstruction)); return false; } if (trampolineDelegateType.Is ("System", "Delegate") || trampolineDelegateType.Is ("System", "MulticastDelegate")) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106_B, caller, trampolineDelegateType.FullName, mr.Name)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106_B, caller, trampolineDelegateType.FullName, mr.Name)); return false; } if (!data.LinkContext.App.StaticRegistrar.TryComputeBlockSignature (caller, trampolineDelegateType, out var exception, out signature)) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, exception, caller, ins, Errors.MM2106_D, caller, ins.Offset, exception.Message)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, exception, caller, ins, Errors.MM2106_D, caller, ins.Offset, exception.Message)); return false; } } catch (Exception e) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, e, caller, ins, Errors.MM2106_D, caller, ins.Offset, e.Message)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, e, caller, ins, Errors.MM2106_D, caller, ins.Offset, e.Message)); return false; } @@ -854,34 +859,34 @@ static bool ProcessBlockLiteralConstructor (OptimizeGeneratedCodeData data, Meth // Verify 'ldstr ...' var loadString = GetPreviousSkippingNops (ins); if (loadString.OpCode != OpCodes.Ldstr) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the previous instruction was unexpected ({3}) */, caller, ins.Offset, mr.Name, loadString)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the previous instruction was unexpected ({3}) */, caller, ins.Offset, mr.Name, loadString)); return false; } // Verify 'call System.Type System.Type::GetTypeFromHandle(System.RuntimeTypeHandle)' var callGetTypeFromHandle = GetPreviousSkippingNops (loadString); if (callGetTypeFromHandle.OpCode != OpCodes.Call || !(callGetTypeFromHandle.Operand is MethodReference methodOperand) || methodOperand.Name != "GetTypeFromHandle" || !methodOperand.DeclaringType.Is ("System", "Type")) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the previous instruction was unexpected ({3}) */, caller, ins.Offset, mr.Name, callGetTypeFromHandle)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the previous instruction was unexpected ({3}) */, caller, ins.Offset, mr.Name, callGetTypeFromHandle)); return false; } // Verify 'ldtoken ...' var loadType = GetPreviousSkippingNops (callGetTypeFromHandle); if (loadType.OpCode != OpCodes.Ldtoken) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the previous instruction was unexpected ({3}) */, caller, ins.Offset, mr.Name, loadType)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the previous instruction was unexpected ({3}) */, caller, ins.Offset, mr.Name, loadType)); return false; } // Then find the type of the previous instruction var trampolineContainerTypeReference = loadType.Operand as TypeReference; if (trampolineContainerTypeReference is null) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the previous instruction was unexpected ({3}) */, caller, ins.Offset, mr.Name, loadType.Operand)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the previous instruction was unexpected ({3}) */, caller, ins.Offset, mr.Name, loadType.Operand)); return false; } var trampolineContainerType = trampolineContainerTypeReference.Resolve (); if (trampolineContainerType is null) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the previous instruction was unexpected ({3}) */, caller, ins.Offset, mr.Name, trampolineContainerTypeReference)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the previous instruction was unexpected ({3}) */, caller, ins.Offset, mr.Name, trampolineContainerTypeReference)); return false; } @@ -889,15 +894,15 @@ static bool ProcessBlockLiteralConstructor (OptimizeGeneratedCodeData data, Meth var trampolineMethodName = (string) loadString.Operand; var trampolineMethods = trampolineContainerType.Methods.Where (v => v.Name == trampolineMethodName).ToArray (); if (!trampolineMethods.Any ()) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MX2106_E1 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because no method named '{3}' was found in the type '{4}'. */, caller, ins.Offset, mr.Name, trampolineMethodName, trampolineContainerType.FullName)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MX2106_E1 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because no method named '{3}' was found in the type '{4}'. */, caller, ins.Offset, mr.Name, trampolineMethodName, trampolineContainerType.FullName)); return false; } else if (trampolineMethods.Count () > 1) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MX2106_E2 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because more than one method named '{3}' was found in the type '{4}'. */, caller, ins.Offset, mr.Name, trampolineMethodName, trampolineContainerType.FullName)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MX2106_E2 /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because more than one method named '{3}' was found in the type '{4}'. */, caller, ins.Offset, mr.Name, trampolineMethodName, trampolineContainerType.FullName)); return false; } var trampolineMethod = trampolineMethods [0]; if (!trampolineMethod.HasParameters || trampolineMethod.Parameters.Count < 1) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MX2106_F /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the method '{3}' must have at least one parameter. */, caller, ins.Offset, mr.Name, trampolineContainerType.FullName + "::" + trampolineMethodName)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MX2106_F /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the method '{3}' must have at least one parameter. */, caller, ins.Offset, mr.Name, trampolineContainerType.FullName + "::" + trampolineMethodName)); return false; } @@ -908,18 +913,18 @@ static bool ProcessBlockLiteralConstructor (OptimizeGeneratedCodeData data, Meth } else if (firstParameterType is PointerType ptrType) { var ptrTargetType = ptrType.ElementType; if (!(ptrTargetType.Is ("System", "Void") || ptrTargetType.Is ("ObjCRuntime", "BlockLiteral"))) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MX2106_G /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the first parameter in the method '{3}' isn't 'System.IntPtr', 'void*' or 'ObjCRuntime.BlockLiteral*' (it's '{4}') */, caller, ins.Offset, mr.Name, trampolineContainerType.FullName + "::" + trampolineMethodName, firstParameterType.FullName)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MX2106_G /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the first parameter in the method '{3}' isn't 'System.IntPtr', 'void*' or 'ObjCRuntime.BlockLiteral*' (it's '{4}') */, caller, ins.Offset, mr.Name, trampolineContainerType.FullName + "::" + trampolineMethodName, firstParameterType.FullName)); return false; } // ok } else { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MX2106_G /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the first parameter in the method '{3}' isn't 'System.IntPtr', 'void*' or 'ObjCRuntime.BlockLiteral*' (it's '{4}') */, caller, ins.Offset, mr.Name, trampolineContainerType.FullName + "::" + trampolineMethodName, firstParameterType.FullName)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MX2106_G /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the first parameter in the method '{3}' isn't 'System.IntPtr', 'void*' or 'ObjCRuntime.BlockLiteral*' (it's '{4}') */, caller, ins.Offset, mr.Name, trampolineContainerType.FullName + "::" + trampolineMethodName, firstParameterType.FullName)); return false; } // Check that the method has [UnmanagedCallersOnly] if (!trampolineMethod.HasCustomAttributes || !trampolineMethod.CustomAttributes.Any (v => v.AttributeType.Is ("System.Runtime.InteropServices", "UnmanagedCallersOnlyAttribute"))) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MX2106_H /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the method '{3}' does not have an [UnmanagedCallersOnly] attribute. */, caller, ins.Offset, mr.Name, trampolineContainerType.FullName + "::" + trampolineMethodName)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MX2106_H /* Could not optimize the call to BlockLiteral.{2} in {0} at offset {1} because the method '{3}' does not have an [UnmanagedCallersOnly] attribute. */, caller, ins.Offset, mr.Name, trampolineContainerType.FullName + "::" + trampolineMethodName)); return false; } @@ -933,7 +938,7 @@ static bool ProcessBlockLiteralConstructor (OptimizeGeneratedCodeData data, Meth } if (userMethod is null) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106_D, caller, ins.Offset, "Could not find delegate invoke method")); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, caller, ins, Errors.MM2106_D, caller, ins.Offset, "Could not find delegate invoke method")); return false; } @@ -945,7 +950,7 @@ static bool ProcessBlockLiteralConstructor (OptimizeGeneratedCodeData data, Meth sequenceStart = loadType; } catch (Exception e) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2106, e, caller, ins, Errors.MM2106_D, caller, ins.Offset, e.Message)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2106, e, caller, ins, Errors.MM2106_D, caller, ins.Offset, e.Message)); return false; } @@ -963,7 +968,7 @@ static bool ProcessBlockLiteralConstructor (OptimizeGeneratedCodeData data, Meth // Change the call to call the ctor with the string signature parameter instead ins.Operand = GetBlockLiteralConstructor (data, caller, ins); - Driver.Log (4, "Optimized call to BlockLiteral..ctor in {0} at offset {1} with signature {2}", caller, ins.Offset, signature); + data.App.Log (4, "Optimized call to BlockLiteral..ctor in {0} at offset {1} with signature {2}", caller, ins.Offset, signature); instructionsAddedOrRemoved = instructionDiff; return true; } @@ -1004,7 +1009,7 @@ static bool ProcessIsARM64CallingConvention (OptimizeGeneratedCodeData data, Met if (fr is null || !fr.DeclaringType.Is (Namespaces.ObjCRuntime, "Runtime")) return false; - if (!ValidateInstruction (caller, ins, operation, Code.Ldsfld)) + if (!ValidateInstruction (data, caller, ins, operation, Code.Ldsfld)) return false; // We're fine, inline the Runtime.IsARM64CallingConvention value @@ -1027,7 +1032,7 @@ static bool ProcessRuntimeArch (OptimizeGeneratedCodeData data, MethodDefinition return false; // Verify a few assumptions before doing anything - if (!ValidateInstruction (caller, ins, operation, Code.Ldsfld)) + if (!ValidateInstruction (data, caller, ins, operation, Code.Ldsfld)) return false; // We're fine, inline the Runtime.Arch condition @@ -1153,52 +1158,52 @@ static bool ProcessProtocolInterfaceStaticConstructor (OptimizeGeneratedCodeData return false; if (data.Optimizations.RegisterProtocols != true) { - Driver.Log (4, "Did not optimize static constructor in the protocol interface {0}: the 'register-protocols' optimization is disabled.", method.DeclaringType.FullName); + data.App.Log (4, "Did not optimize static constructor in the protocol interface {0}: the 'register-protocols' optimization is disabled.", method.DeclaringType.FullName); return false; } if (!method.DeclaringType.HasCustomAttributes || !method.DeclaringType.CustomAttributes.Any (v => v.AttributeType.Is ("Foundation", "ProtocolAttribute"))) { - Driver.Log (4, "Did not optimize static constructor in the protocol interface {0}: no Protocol attribute found.", method.DeclaringType.FullName); + data.App.Log (4, "Did not optimize static constructor in the protocol interface {0}: no Protocol attribute found.", method.DeclaringType.FullName); return false; } var ins = SkipNops (method.Body.Instructions.First ()); if (ins is null) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_A /* Could not optimize the static constructor in the interface {0} because it did not have the expected instruction sequence (found end of method too soon). */, method.DeclaringType.FullName)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_A /* Could not optimize the static constructor in the interface {0} because it did not have the expected instruction sequence (found end of method too soon). */, method.DeclaringType.FullName)); return false; } else if (ins.OpCode != OpCodes.Ldnull) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_B /* Could not optimize the static constructor in the interface {0} because it had an unexpected instruction {1} at offset {2}. */, method.DeclaringType.FullName, ins.OpCode, ins.Offset)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_B /* Could not optimize the static constructor in the interface {0} because it had an unexpected instruction {1} at offset {2}. */, method.DeclaringType.FullName, ins.OpCode, ins.Offset)); return false; } ins = SkipNops (ins.Next); if (ins is null) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_A /* Could not optimize the static constructor in the interface {0} because it did not have the expected instruction sequence (found end of method too soon). */, method.DeclaringType.FullName)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_A /* Could not optimize the static constructor in the interface {0} because it did not have the expected instruction sequence (found end of method too soon). */, method.DeclaringType.FullName)); return false; } var callGCKeepAlive = ins; if (callGCKeepAlive.OpCode != OpCodes.Call || !(callGCKeepAlive.Operand is MethodReference methodOperand) || methodOperand.Name != "KeepAlive" || !methodOperand.DeclaringType.Is ("System", "GC")) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_B /* Could not optimize the static constructor in the interface {0} because it had an unexpected instruction {1} at offset {2}. */, method.DeclaringType.FullName, ins.OpCode, ins.Offset)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_B /* Could not optimize the static constructor in the interface {0} because it had an unexpected instruction {1} at offset {2}. */, method.DeclaringType.FullName, ins.OpCode, ins.Offset)); return false; } ins = SkipNops (ins.Next); if (ins is null) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_A /* Could not optimize the static constructor in the interface {0} because it did not have the expected instruction sequence (found end of method too soon). */, method.DeclaringType.FullName)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_A /* Could not optimize the static constructor in the interface {0} because it did not have the expected instruction sequence (found end of method too soon). */, method.DeclaringType.FullName)); return false; } else if (ins.OpCode != OpCodes.Ret) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_B /* Could not optimize the static constructor in the interface {0} because it had an unexpected instruction {1} at offset {2}. */, method.DeclaringType.FullName, ins.OpCode, ins.Offset)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_B /* Could not optimize the static constructor in the interface {0} because it had an unexpected instruction {1} at offset {2}. */, method.DeclaringType.FullName, ins.OpCode, ins.Offset)); return false; } ins = SkipNops (ins.Next); if (ins is not null) { - ErrorHelper.Show (ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_B /* Could not optimize the static constructor in the interface {0} because it had an unexpected instruction {1} at offset {2}. */, method.DeclaringType.FullName, ins.OpCode, ins.Offset)); + ErrorHelper.Show (data.App, ErrorHelper.CreateWarning (data.LinkContext.App, 2112, method, ins, Errors.MX2112_B /* Could not optimize the static constructor in the interface {0} because it had an unexpected instruction {1} at offset {2}. */, method.DeclaringType.FullName, ins.OpCode, ins.Offset)); return false; } // We can just remove the entire method, however that confuses the linker later on, so just empty it out and remove all the attributes. - Driver.Log (4, "Optimized static constructor in the protocol interface {0} (static constructor was cleared and custom attributes removed)", method.DeclaringType.FullName); + data.App.Log (4, "Optimized static constructor in the protocol interface {0} (static constructor was cleared and custom attributes removed)", method.DeclaringType.FullName); method.Body.Instructions.Clear (); method.Body.Instructions.Add (Instruction.Create (OpCodes.Ret)); @@ -1234,6 +1239,8 @@ public class OptimizeGeneratedCodeData { public MethodDefinition? SetupBlockImplDefinition; public MethodDefinition? BlockCtorDefinition; public bool? InlineIsArm64CallingConvention; + + public Application App => LinkContext.App; } } diff --git a/tools/linker/MonoTouch.Tuner/ListExportedSymbols.cs b/tools/linker/MonoTouch.Tuner/ListExportedSymbols.cs index e014c12bc41c..bb2193ab35ad 100644 --- a/tools/linker/MonoTouch.Tuner/ListExportedSymbols.cs +++ b/tools/linker/MonoTouch.Tuner/ListExportedSymbols.cs @@ -18,7 +18,6 @@ namespace Xamarin.Linker.Steps { public class ListExportedSymbols : BaseStep { PInvokeWrapperGenerator? state; - bool is_product_assembly; PInvokeWrapperGenerator? State { get { @@ -80,8 +79,6 @@ protected override void ProcessAssembly (AssemblyDefinition assembly) if (!hasSymbols) return; - is_product_assembly = Configuration.Profile.IsProductAssembly (assembly); - var modified = false; foreach (var type in assembly.MainModule.Types) modified |= ProcessType (type); @@ -114,40 +111,41 @@ bool ProcessType (TypeDefinition type) void AddRequiredObjectiveCType (TypeDefinition type) { + if (TryGetRequiredObjectiveCType (DerivedLinkContext, type, out var exportedName)) + DerivedLinkContext.RequiredSymbols.AddObjectiveCClass (exportedName).AddMember (type); + } + + // Returns true if the specified type represents an Objective-C class that should be referenced as a required symbol, so that the native linker doesn't link it away. + public static bool TryGetRequiredObjectiveCType (DerivedLinkContext derivedLinkContext, TypeDefinition type, [NotNullWhen (true)] out string? exportedName) + { + exportedName = null; + // The product assembly only has one type we may need to keep: XamarinSwiftFunctions - if (is_product_assembly) { + if (derivedLinkContext.LinkerConfiguration.Profile.IsProductAssembly (type.Module.Assembly)) { switch (type.Name) { case "XamarinSwiftFunctions": break; default: - return; + return false; } } - var staticRegistrar = DerivedLinkContext.StaticRegistrar; + var staticRegistrar = derivedLinkContext.StaticRegistrar; if (staticRegistrar is null) - return; + return false; - var registerAttribute = staticRegistrar.GetRegisterAttribute (type); - if (registerAttribute is null) - return; - - if (!registerAttribute.IsWrapper) - return; + if (!staticRegistrar.TryGetExportedTypeName (type, out exportedName)) + return false; - if (staticRegistrar.HasProtocolAttribute (type)) - return; - - if (DerivedLinkContext.App.RequireLinkWithAttributeForObjectiveCClassSearch) { + if (derivedLinkContext.App.RequireLinkWithAttributeForObjectiveCClassSearch) { var has_linkwith_attributes = false; - if (DerivedLinkContext.App.Assemblies.TryGetValue (type.Module.Assembly, out var asm)) + if (derivedLinkContext.App.Assemblies.TryGetValue (type.Module.Assembly, out var asm)) has_linkwith_attributes = asm.HasLinkWithAttributes; if (!has_linkwith_attributes) - return; + return false; } - var exportedName = staticRegistrar.GetExportedTypeName (type, registerAttribute); - DerivedLinkContext.RequiredSymbols.AddObjectiveCClass (exportedName).AddMember (type); + return true; } bool ProcessMethod (MethodDefinition method) @@ -191,18 +189,30 @@ bool ProcessMethod (MethodDefinition method) switch (pinfo.Module.Name) { case "__Internal": - Driver.Log (4, "Adding native reference to {0} in {1} because it's referenced by {2} in {3}.", pinfo.EntryPoint, pinfo.Module.Name, method.FullName, method.Module.Name); + if (Configuration.Application.XamarinRuntime == XamarinRuntime.NativeAOT) { + // For NativeAOT builds, don't add inlined dlfcn P/Invoke wrappers as + // required symbols: only the surviving ones will have native code generated, + // so force-referencing all of them causes linker errors for symbols that + // NativeAOT trimmed away. For non-NativeAOT builds, the wrappers are resolved + // via dlsym and need the -u flags to be exported from the binary. + if (Configuration.InlineDlfcnMethodsEnabled && pinfo.EntryPoint.StartsWith (InlineDlfcnMethodsStep.PInvokePrefix, StringComparison.Ordinal)) + break; + // Same goes for inlined Class.GetHandle calls. + if (Configuration.InlineClassGetHandle != InlineClassGetHandleMode.Disabled && pinfo.EntryPoint.StartsWith (InlineClassGetHandleStep.PInvokePrefix, StringComparison.Ordinal)) + break; + } + DerivedLinkContext.App.Log (4, "Adding native reference to {0} in {1} because it's referenced by {2} in {3}.", pinfo.EntryPoint, pinfo.Module.Name, method.FullName, method.Module.Name); DerivedLinkContext.RequiredSymbols.AddFunction (pinfo.EntryPoint).AddMember (method); break; default: if (!addPInvokeSymbol) - Driver.Log (4, "Did not add native reference to {0} in {1} referenced by {2} in {3}.", pinfo.EntryPoint, pinfo.Module.Name, method.FullName, method.Module.Name); + DerivedLinkContext.App.Log (4, "Did not add native reference to {0} in {1} referenced by {2} in {3}.", pinfo.EntryPoint, pinfo.Module.Name, method.FullName, method.Module.Name); break; } if (addPInvokeSymbol) { - Driver.Log (4, "Adding native reference to {0} in {1} because it's referenced by {2} in {3}.", pinfo.EntryPoint, pinfo.Module.Name, method.FullName, method.Module.Name); + DerivedLinkContext.App.Log (4, "Adding native reference to {0} in {1} because it's referenced by {2} in {3}.", pinfo.EntryPoint, pinfo.Module.Name, method.FullName, method.Module.Name); DerivedLinkContext.RequireMonoNative = true; if (DerivedLinkContext.App.Platform != ApplePlatform.MacOSX && DerivedLinkContext.App.LibMonoNativeLinkMode == AssemblyBuildTarget.StaticObject) { @@ -211,7 +221,7 @@ bool ProcessMethod (MethodDefinition method) } } - if (method.IsPropertyMethod ()) { + if (method.IsPropertyMethod () && !Configuration.InlineDlfcnMethodsEnabled) { var property = method.GetProperty (); // The Field attribute may have been linked away, but we've stored it in an annotation. if (property is not null && Annotations.GetCustomAnnotations ("ExportedFields").TryGetValue (property, out var symbol) && symbol is string symbolStr) { diff --git a/tools/linker/MonoTouch.Tuner/ProcessExportedFields.cs b/tools/linker/MonoTouch.Tuner/ProcessExportedFields.cs index 8e4a61ed2578..53787784589f 100644 --- a/tools/linker/MonoTouch.Tuner/ProcessExportedFields.cs +++ b/tools/linker/MonoTouch.Tuner/ProcessExportedFields.cs @@ -23,6 +23,8 @@ namespace MonoTouch.Tuner { // Then at the end of the linker process (ListExportedSymbols step) // we lookup that annotation. // + // See docs/code/native-symbols.md for an overview of native symbol handling. + // public class ProcessExportedFields : BaseStep { protected override void ProcessAssembly (AssemblyDefinition assembly) @@ -55,6 +57,15 @@ void ProcessProperty (PropertyDefinition property) if (!property.HasCustomAttributes) return; + var config = LinkerConfiguration.GetInstance (Context); + + // Collect all [Field] symbol names for InlineDlfcnMethodsStep's compatibility mode. + if (config.InlineDlfcnMethodsEnabled) { + var allSymbol = GetFieldSymbolName (property); + if (allSymbol is not null) + config.FieldSymbols.Add (allSymbol); + } + var symbol = GetFieldSymbol (property); if (symbol is null) return; @@ -62,6 +73,28 @@ void ProcessProperty (PropertyDefinition property) Annotations.GetCustomAnnotations ("ExportedFields").Add (property, symbol); } + // Returns the symbol name from a [Field] attribute, regardless of library. + internal static string? GetFieldSymbolName (PropertyDefinition property) + { + if (!property.HasCustomAttributes) + return null; + + foreach (var attrib in property.CustomAttributes) { + var declaringType = attrib.Constructor.DeclaringType.Resolve (); + + if (!declaringType.Is (Namespaces.Foundation, "FieldAttribute")) + continue; + + if (attrib.ConstructorArguments.Count < 1) + continue; + + return (string) attrib.ConstructorArguments [0].Value; + } + + return null; + } + + // Returns the symbol name only for __Internal fields. internal static string? GetFieldSymbol (PropertyDefinition property) { if (!property.HasCustomAttributes) diff --git a/tools/linker/RegistrarRemovalTrackingStep.cs b/tools/linker/RegistrarRemovalTrackingStep.cs index f88452f3ccd0..b2cd10bc170c 100644 --- a/tools/linker/RegistrarRemovalTrackingStep.cs +++ b/tools/linker/RegistrarRemovalTrackingStep.cs @@ -153,7 +153,7 @@ bool RequiresDynamicRegistrar (AssemblyDefinition assembly, bool warnIfRequired) void Warn (AssemblyDefinition assembly, MemberReference mr) { - ErrorHelper.Warning (WarnCode, Errors.MM2107, assembly.Name.Name, mr.DeclaringType.FullName, mr.Name, string.Join (", ", ((MethodReference) mr).Parameters.Select ((v) => v.ParameterType.FullName))); + ErrorHelper.Warning (App, WarnCode, Errors.MM2107, assembly.Name.Name, mr.DeclaringType.FullName, mr.Name, string.Join (", ", ((MethodReference) mr).Parameters.Select ((v) => v.ParameterType.FullName))); } protected override void TryEndProcess () @@ -164,7 +164,7 @@ protected override void TryEndProcess () Optimizations.RemoveDynamicRegistrar = !dynamic_registration_support_required; } - Driver.Log (4, "Optimization dynamic registrar removal: {0}", Optimizations.RemoveDynamicRegistrar.Value ? "enabled" : "disabled"); + App.Log (4, "Optimization dynamic registrar removal: {0}", Optimizations.RemoveDynamicRegistrar.Value ? "enabled" : "disabled"); if (Optimizations.RemoveDynamicRegistrar.Value) { // ILLink will optimize `Runtime.Initialize` based on `DynamicRegistrationSupported` returning a constant (`true`) diff --git a/tools/mtouch/AssemblyResolver.cs b/tools/mtouch/AssemblyResolver.cs index f63d6ebebbe7..e5386afd5df5 100644 --- a/tools/mtouch/AssemblyResolver.cs +++ b/tools/mtouch/AssemblyResolver.cs @@ -22,10 +22,6 @@ #nullable enable namespace MonoTouch.Tuner { - - public partial class MonoTouchManifestResolver : MonoTouchResolver { - } - // recent cecil removed some overloads - https://github.com/mono/cecil/commit/42db79cc16f1cbe8dbab558904e188352dba2b41 public static class AssemblyResolverRocks { @@ -41,6 +37,12 @@ public static AssemblyDefinition Resolve (this IAssemblyResolver self, string fu } public class MonoTouchResolver : CoreResolver { + Application app; + + public MonoTouchResolver (Application app) + { + this.app = app; + } public IEnumerable GetAssemblies () { @@ -63,29 +65,29 @@ public void Add (AssemblyDefinition assembly) if (FrameworkDirectory is not null) { var facadeDir = Path.Combine (FrameworkDirectory, "Facades"); - assembly = SearchDirectory (aname, facadeDir); + assembly = SearchDirectory (app, aname, facadeDir); if (assembly is not null) return assembly; } if (ArchDirectory is not null) { - assembly = SearchDirectory (aname, ArchDirectory); + assembly = SearchDirectory (app, aname, ArchDirectory); if (assembly is not null) return assembly; } if (FrameworkDirectory is not null) { - assembly = SearchDirectory (aname, FrameworkDirectory); + assembly = SearchDirectory (app, aname, FrameworkDirectory); if (assembly is not null) return assembly; } if (RootDirectory is not null) { - assembly = SearchDirectory (aname, RootDirectory); + assembly = SearchDirectory (app, aname, RootDirectory); if (assembly is not null) return assembly; - assembly = SearchDirectory (aname, RootDirectory, ".exe"); + assembly = SearchDirectory (app, aname, RootDirectory, ".exe"); if (assembly is not null) return assembly; } diff --git a/tools/mtouch/Errors.designer.cs b/tools/mtouch/Errors.designer.cs index e2f24503e42d..7c3f1861b4ab 100644 --- a/tools/mtouch/Errors.designer.cs +++ b/tools/mtouch/Errors.designer.cs @@ -3524,6 +3524,87 @@ public static string MX2112_B { } } + /// + /// Looks up a localized string similar to Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new. + /// + public static string MX2254 { + get { + return ResourceManager.GetString("MX2254", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. + /// + public static string MX2255 { + get { + return ResourceManager.GetString("MX2255", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new. + /// + public static string MX2256 { + get { + return ResourceManager.GetString("MX2256", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new. + /// + public static string MX2257 { + get { + return ResourceManager.GetString("MX2257", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new. + /// + public static string MX2258 { + get { + return ResourceManager.GetString("MX2258", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new. + /// + public static string MX2259 { + get { + return ResourceManager.GetString("MX2259", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new. + /// + public static string MX2260 { + get { + return ResourceManager.GetString("MX2260", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new. + /// + public static string MX2261 { + get { + return ResourceManager.GetString("MX2261", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar.. + /// + public static string MX2262 { + get { + return ResourceManager.GetString("MX2262", resourceCulture); + } + } + /// /// Looks up a localized string similar to Could not {0} the assembly '{1}'. /// diff --git a/tools/mtouch/Errors.resx b/tools/mtouch/Errors.resx index 83c238026906..cc89125d1ff1 100644 --- a/tools/mtouch/Errors.resx +++ b/tools/mtouch/Errors.resx @@ -1097,6 +1097,46 @@ + + + + Unsupported primitive field type '{0}' for symbol '{1}' in method '{2}'. Sub-optimal but functional code will be generated. Please file an issue at https://github.com/dotnet/macios/issues/new + + + + Unknown or unsupported Dlfcn pattern: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + + The field type '{0}' for symbol '{1}' in method '{2}' is not an NSObject subclass. Please file an issue at https://github.com/dotnet/macios/issues/new + + + + Unknown IL sequence for method with call to Dlfcn.CachePointer: '{0}' in method '{1}'. The call will not be inlined. Please file an issue at https://github.com/dotnet/macios/issues/new + + + + '{0}' is marked with a malformed simulator availability attribute: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + + '{0}' is marked with a simulator availability attribute with an invalid version: {1}. Please file an issue at https://github.com/dotnet/macios/issues/new + + + + '{0}' has conflicting simulator availability attributes for the '{1}' platform (both SupportedSimulator and UnsupportedSimulator). Please file an issue at https://github.com/dotnet/macios/issues/new + + + + '{0}' has multiple SupportedSimulator attributes for the '{1}' platform. Please file an issue at https://github.com/dotnet/macios/issues/new + + + + The 'InlineClassGetHandle' option is set to 'Strict', but we're using the dynamic registrar. This is not a supported configuration, because 'Strict' mode requires exported Objective-C classes to be available at compile time, but the dynamic registrar will create them at runtime. Please either change the 'InlineClassGetHandle' option to 'Disabled' or 'Compat', or switch to using the static registrar. + + + + diff --git a/tools/mtouch/Makefile b/tools/mtouch/Makefile index 40fab8c5dd39..d48cc4bd1eaf 100644 --- a/tools/mtouch/Makefile +++ b/tools/mtouch/Makefile @@ -35,18 +35,21 @@ $(abspath Constants.cs): Constants.cs.in Makefile $(TOP)/Make.config.inc # define RunRegistrar .libs/Microsoft.$(9).registrar.$(10)%m .libs/Microsoft.$(9).registrar.$(10)%h: $(TOP)/src/build/dotnet/$(1)/$(3)/Microsoft.$(9).dll $(LOCAL_MTOUCH) | .libs - $$(Q_GEN) $$(LOCAL_MTOUCH_COMMAND) $$(MTOUCH_VERBOSITY) --runregistrar:$$(abspath $$(basename $$@).m) --sdkroot $$(XCODE_DEVELOPER_ROOT) --sdk $(4) $$< --target-framework .NETCoreApp,Version=$(subst net,,$(DOTNET_TFM)),Profile=$(1) --abi $(2) --reference:$(DOTNET_BCL_DIR)/System.Runtime.dll --reference:$(DOTNET_BCL_DIR)/System.Runtime.InteropServices.dll --rid $(10) + $$(Q_GEN) $$(LOCAL_MTOUCH_COMMAND) $$(MTOUCH_VERBOSITY) --runregistrar:$$(abspath $$(basename $$@).m) --xcode-version $$(XCODE_VERSION) --sdk $(4) $$< --target-framework .NETCoreApp,Version=$(subst net,,$(DOTNET_TFM)),Profile=$(1) --abi $(2) --reference:$(DOTNET_BCL_DIR)/System.Runtime.dll --reference:$(DOTNET_BCL_DIR)/System.Runtime.InteropServices.dll --rid $(10) $$(Q) touch $$(basename $$@).m $$(basename $$@).h .libs/Microsoft.$(9).registrar.$(10).a: .libs/Microsoft.$(9).registrar.$(10).m .libs/Microsoft.$(9).registrar.$(10).h | .libs $$(Q_CC) $$(CLANG) -DDEBUG -g -gdwarf-2 $(6) -stdlib=libc++ -std=c++14 -x objective-c++ -o $$@ -c $$< -Wall -Wno-unguarded-availability-new -I$(TOP)/runtime .libs/Microsoft.$(9).registrar.coreclr.$(10)%m .libs/Microsoft.$(9).registrar.coreclr.$(10)%h: $(TOP)/src/build/dotnet/$(1)/$(3)/Microsoft.$(9).dll $(LOCAL_MTOUCH) | .libs - $$(Q_GEN) $$(LOCAL_MTOUCH_COMMAND) $$(MTOUCH_VERBOSITY) --runregistrar:$$(abspath $$(basename $$@).m) --sdkroot $$(XCODE_DEVELOPER_ROOT) --sdk $(4) $$< --target-framework .NETCoreApp,Version=$(subst net,,$(DOTNET_TFM)),Profile=$(1) --abi $(2) --reference:$(DOTNET_BCL_DIR)/System.Runtime.dll --reference:$(DOTNET_BCL_DIR)/System.Runtime.InteropServices.dll --rid $(10) --xamarin-runtime CoreCLR + $$(Q_GEN) $$(LOCAL_MTOUCH_COMMAND) $$(MTOUCH_VERBOSITY) --runregistrar:$$(abspath $$(basename $$@).m) --xcode-version $$(XCODE_VERSION) --sdk $(4) $$< --target-framework .NETCoreApp,Version=$(subst net,,$(DOTNET_TFM)),Profile=$(1) --abi $(2) --reference:$(DOTNET_BCL_DIR)/System.Runtime.dll --reference:$(DOTNET_BCL_DIR)/System.Runtime.InteropServices.dll --rid $(10) --xamarin-runtime CoreCLR $$(Q) touch $$(basename $$@).m $$(basename $$@).h .libs/Microsoft.$(9).registrar.coreclr.$(10).a: .libs/Microsoft.$(9).registrar.coreclr.$(10).m .libs/Microsoft.$(9).registrar.$(10).h | .libs $$(Q_CC) $$(CLANG) -DDEBUG -g -gdwarf-2 $(6) -stdlib=libc++ -std=c++14 -x objective-c++ -o $$@ -c $$< -Wall -Wno-unguarded-availability-new -I$(TOP)/runtime + +no-xcode-build:: .libs/Microsoft.$(9).registrar.$(10).m .libs/Microsoft.$(9).registrar.$(10).h +no-xcode-build:: .libs/Microsoft.$(9).registrar.coreclr.$(10).m .libs/Microsoft.$(9).registrar.$(10).h endef $(eval $(call RunRegistrar,ios,x86_64,64,$(IOS_SDK_VERSION),iOS,$(iossimulator-x64_CFLAGS),,,iOS,iossimulator-x64)) $(eval $(call RunRegistrar,ios,arm64,64,$(IOS_SDK_VERSION),iOS,$(iossimulator-arm64_CFLAGS),,,iOS,iossimulator-arm64)) @@ -86,12 +89,15 @@ endef $(foreach platform,$(DOTNET_PLATFORMS_MTOUCH),$(foreach rid,$(DOTNET_$(platform)_RUNTIME_IDENTIFIERS),$(eval $(call InstallRegistrar,$(platform),$(rid))))) -ifndef IS_LINUX +ifdef NO_XCODE +dotnet:: no-xcode-build +else dotnet: $(TARGETS_DOTNET) -install-local:: $(TARGETS_DOTNET) -all-local:: $(TARGETS_DOTNET) endif +install-local:: dotnet +all-local:: dotnet + clean-local:: rm -Rf bin obj diff --git a/tools/mtouch/mtouch.cs b/tools/mtouch/mtouch.cs index 21349adc0aaf..42ae6901f1a0 100644 --- a/tools/mtouch/mtouch.cs +++ b/tools/mtouch/mtouch.cs @@ -22,8 +22,6 @@ static int Main2 (string [] args) var os = new OptionSet (); ParseOptions (app, os, args); - ValidateXcode (app, false, false); - app.InitializeCommon (); app.RunRegistrar (); diff --git a/tools/mtouch/mtouch.csproj b/tools/mtouch/mtouch.csproj index ca0541e4ea60..d9ba0a1ea76e 100644 --- a/tools/mtouch/mtouch.csproj +++ b/tools/mtouch/mtouch.csproj @@ -3,8 +3,6 @@ Exe net$(BundledNETCoreAppTargetFrameworkVersion) - latest - enable false false false @@ -12,7 +10,6 @@ false LEGACY_TOOLS true - true @@ -174,6 +171,9 @@ external/tools/common/XamarinRuntime.cs + + external/tools/common/IToolLog.cs + diff --git a/tools/nunit3-console-3.10.0 b/tools/nunit3-console-3.10.0 deleted file mode 100755 index 8ddf8c438192..000000000000 --- a/tools/nunit3-console-3.10.0 +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -eu - -# This makes it so that stack traces have source code location -if test -z "${MONO_ENV_OPTIONS:-}"; then - export MONO_ENV_OPTIONS=--debug -fi - -TOP="$(cd "$(dirname "$0")/.." && pwd)" - -exec mono --debug "$TOP"/packages/nunit.consolerunner/3.10.0/tools/nunit3-console.exe "$@" diff --git a/tools/nunit3-console-3.11.1 b/tools/nunit3-console-3.11.1 deleted file mode 100755 index 9c9a4238b79c..000000000000 --- a/tools/nunit3-console-3.11.1 +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -eu - -# This makes it so that stack traces have source code location -if test -z "${MONO_ENV_OPTIONS:-}"; then - export MONO_ENV_OPTIONS=--debug -fi - -TOP="$(cd "$(dirname "$0")/.." && pwd)" - -exec mono --debug "$TOP"/packages/nunit.consolerunner/3.11.1/tools/nunit3-console.exe "$@" diff --git a/tools/nunit3-console-3.12.0 b/tools/nunit3-console-3.12.0 deleted file mode 100755 index 70cee8a5e84f..000000000000 --- a/tools/nunit3-console-3.12.0 +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -eu - -# This makes it so that stack traces have source code location -if test -z "${MONO_ENV_OPTIONS:-}"; then - export MONO_ENV_OPTIONS=--debug -fi - -TOP="$(cd "$(dirname "$0")/.." && pwd)" - -exec mono --debug "$TOP"/packages/nunit.consolerunner/3.12.0/tools/nunit3-console.exe "$@" diff --git a/tools/nunit3-console-3.9.0 b/tools/nunit3-console-3.9.0 deleted file mode 100755 index 627c4900965a..000000000000 --- a/tools/nunit3-console-3.9.0 +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -eu - -# This makes it so that stack traces have source code location -if test -z "${MONO_ENV_OPTIONS:-}"; then - export MONO_ENV_OPTIONS=--debug -fi - -TOP="$(cd "$(dirname "$0")/.." && pwd)" - -exec mono --debug "$TOP"/packages/nunit.consolerunner/3.9.0/tools/nunit3-console.exe "$@" diff --git a/tools/sharpie/Makefile b/tools/sharpie/Makefile index 56e53de56372..a2c79f4e8727 100644 --- a/tools/sharpie/Makefile +++ b/tools/sharpie/Makefile @@ -21,7 +21,7 @@ SHARPIE_BIND_TOOL_NUPKG_NAME=Sharpie.Bind.Tool.$(SHARPIE_BIND_TOOL_NUGET_VERSION SHARPIE_BIND_TOOL_NUPKG=Sharpie.Bind.Tool/bin/Release/$(SHARPIE_BIND_TOOL_NUPKG_NAME) pack: $(SHARPIE_BIND_TOOL_NUPKG) -$(SHARPIE_BIND_TOOL_NUPKG): $(Sharpie.Bind_dependencies) +$(SHARPIE_BIND_TOOL_NUPKG): $(Sharpie.Bind_dependencies) | $(SHARPIE_BIND_TOOL_DEBUG) $(Q_BUILD) $(DOTNET) pack Sharpie.Bind.Tool/Sharpie.Bind.Tool.csproj "/p:Version=$(SHARPIE_VERSION)" "/p:CurrentBranch=$(CURRENT_BRANCH)" "/p:CurrentHash=$(CURRENT_HASH_LONG)" $(DOTNET_PACK_VERBOSITY) -bl:$@.binlog all-local:: $(DOTNET_NUPKG_DIR)/$(SHARPIE_BIND_TOOL_NUPKG_NAME) diff --git a/tools/sharpie/Sharpie.Bind.Tool/DotnetToolSettings.osx-x64.xml b/tools/sharpie/Sharpie.Bind.Tool/DotnetToolSettings.osx-x64.xml new file mode 100644 index 000000000000..b37c41f8921d --- /dev/null +++ b/tools/sharpie/Sharpie.Bind.Tool/DotnetToolSettings.osx-x64.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/tools/sharpie/Sharpie.Bind.Tool/Sharpie.Bind.Tool.csproj b/tools/sharpie/Sharpie.Bind.Tool/Sharpie.Bind.Tool.csproj index c58024873200..47aecdf36349 100644 --- a/tools/sharpie/Sharpie.Bind.Tool/Sharpie.Bind.Tool.csproj +++ b/tools/sharpie/Sharpie.Bind.Tool/Sharpie.Bind.Tool.csproj @@ -2,14 +2,13 @@ net$(BundledNETCoreAppTargetFrameworkVersion) - latest enable - enable Exe false - + + osx-arm64 true sharpie @@ -33,6 +32,9 @@ Icon.png https://github.com/dotnet/macios true + + + NU5123;$(NoWarn) @@ -50,4 +52,10 @@ + + + + + + diff --git a/tools/sharpie/Sharpie.Bind.Tool/sharpie-x64-shim b/tools/sharpie/Sharpie.Bind.Tool/sharpie-x64-shim new file mode 100755 index 000000000000..1862762a5b68 --- /dev/null +++ b/tools/sharpie/Sharpie.Bind.Tool/sharpie-x64-shim @@ -0,0 +1,3 @@ +#!/bin/bash +echo "error: error: sharpie is not supported on x64. Please use an Apple Silicon (arm64) Mac." >&2 +exit 1 diff --git a/tools/sharpie/Sharpie.Bind/Sharpie.Bind.csproj b/tools/sharpie/Sharpie.Bind/Sharpie.Bind.csproj index d46f1e8c80ce..a6c3b23b957c 100644 --- a/tools/sharpie/Sharpie.Bind/Sharpie.Bind.csproj +++ b/tools/sharpie/Sharpie.Bind/Sharpie.Bind.csproj @@ -3,8 +3,6 @@ net$(BundledNETCoreAppTargetFrameworkVersion) Library - latest - enable $(NETCoreSdkRuntimeIdentifier)