[Bug] Unit tests: macro fails when 'this' is passed as target_relation ('str' object has no attribute 'database')
- Dominant language
- Rust
- Stars
- 13.8k
- Forks
- 2.6k
- Avg merge
- 21h 31m
- Merged PRs (30d)
- 56
Description
### Is this a new bug in dbt-core?
- [x] I believe this is a new bug in dbt-core
- [x] I have searched the existing issues, and I could not find an existing issue for this bug
### Current Behavior
When running dbt unit tests, a macro that works correctly during dbt run fails during unit test execution.
The failure happens when the macro receives `this` as an argument. In unit test context, this does not behave like a proper Relation object and does not expose attributes such as database, schema, or identifier.
As a result, macros that rely on Relation attributes fail with the error:
`'str' object has no attribute 'database'`
### Expected Behavior
Unit tests should behave consistently with runtime execution (dbt run).
Specifically, one of the following should be true:
this resolves to a proper Relation object in unit tests, or
there is a documented and supported way to safely access Relation metadata in unit test context, or
macros can reliably detect unit test context and avoid breaking when accessing Relation attributes.
### Steps To Reproduce
1.Create a model that calls a macro and passes this as an argument:
```
{{ detect_changes(
target_relation = this,
source_table = ref('test_macro_detect_changes_input'),
compare_columns = ['external_id', 'updated_at', 'username', 'email', 'user_status']
) }}
```
2. Inside the macro, access Relation attributes, for example:
`target_relation.database`
3. Define a unit test for the model and use this as one of the test inputs:
`- input: this`
4. Run the unit test:
`dbt test --select test_first_run_detect_changes`
5. Observe the compilation error:
`'str' object has no attribute 'database'`
### Relevant log output
```shell
07:05:06 Failure in unit_test test_first_run_detect_changes_braze (tests\unit\fixtures\test_detect_changes.yml)
07:05:06 Compilation Error in unit_test test_first_run_detect_changes (tests\unit\fixtures\test_detect_changes.yml)
'str object' has no attribute 'database'
> in macro detect_changes (macros\detect_changes.sql)
> called by unit_test test_first_run_detect_changes (tests\unit\fixtures\test_detect_changes.yml)
```
### Environment
```markdown
- OS: Windows 11
- Python: 3.12.0
- dbt: 1.10.11
```
### Which database adapter are you using with dbt?
bigquery
### Additional Context
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.