Repository: celery/celery

Issue:
task_default_exchange&task_default_exchange_type config not work
<!--
Please fill this template entirely and do not erase parts of it.
We reserve the right to close without a response
bug reports which are incomplete.
-->
# Checklist
<!--
To check an item on the list replace [ ] with [x].
-->

- [x] I have read the relevant section in the
  [contribution guide](http://docs.celeryproject.org/en/latest/contributing.html#other-bugs)
  on reporting bugs.
- [x] I have checked the [issues list](https://github.com/celery/celery/issues?q=is%3Aissue+label%3A%22Issue+Type%3A+Bug+Report%22+-label%3A%22Category%3A+Documentation%22)
  for similar or identical bug reports.
- [x] I have checked the [pull requests list](https://github.com/celery/celery/pulls?q=is%3Apr+label%3A%22PR+Type%3A+Bugfix%22+-label%3A%22Category%3A+Documentation%22)
  for existing proposed fixes.
- [x] I have checked the [commit log](https://github.com/celery/celery/commits/master)
  to find out if the bug was already fixed in the master branch.
- [x] I have included all related issues and possible duplicate issues
  in this issue (If there are none, check this box anyway).

## Mandatory Debugging Information

- [x] I have included the output of ``celery -A proj report`` in the issue.
    (if you are not able to do this, then at least specify the Celery
     version affected).
- [x] I have verified that the issue exists against the `master` branch of Celery.
- [ ] I have included the contents of ``pip freeze`` in the issue.
- [ ] I have included all the versions of all the external dependencies required
  to reproduce this bug.

## Optional Debugging Information
<!--
Try some of the below if you think they are relevant.
It will help us figure out the scope of the bug and how many users it affects.
-->
- [x] I have tried reproducing the issue on more than one Python version
  and/or implementation.
- [ ] I have tried reproducing the issue on more than one message broker and/or
  result backend.
- [ ] I have tried reproducing the issue on more than one version of the message
  broker and/or result backend.
- [ ] I have tried reproducing the issue on more than one operating system.
- [x] I have tried reproducing the issue on more than one workers pool.
- [ ] I have tried reproducing the issue with autoscaling, retries,
  ETA/Countdown & rate limits disabled.
- [ ] I have tried reproducing the issue after downgrading
  and/or upgrading Celery and its dependencies.

## Related Issues and Possible Duplicates
<!--
Please make sure to search and mention any related issues
or possible duplicates to this issue as requested by the checklist above.

This may or may not include issues in other repositories that the Celery project
maintains or other repositories that are dependencies of Celery.

If you don't know how to mention issues, please refer to Github's documentation
on the subject: https://help.github.com/en/articles/autolinked-references-and-urls#issues-and-pull-requests
-->

#### Related Issues

- #3926 

#### Possible Duplicates

- None

## Environment & Settings
<!-- Include the contents of celery --version below -->
**Celery version**: 4.3.0
<!-- Include the output of celery -A proj report below -->
<details>
<summary><b><code>celery report</code> Output:</b></summary>
<p>

```
software -> celery:4.3.0 (rhubarb) kombu:4.6.4 py:3.6.0
            billiard:3.6.1.0 librabbitmq:2.0.0
platform -> system:Linux arch:64bit, ELF
            kernel version:4.19.71-1-lts imp:CPython
loader   -> celery.loaders.default.Loader
settings -> transport:librabbitmq results:disabled
```

</p>
</details>

# Steps to Reproduce

## Required Dependencies
<!-- Please fill the required dependencies to reproduce this issue -->
* **Minimal Python Version**: 3.6.0
* **Minimal Celery Version**: 4.3.0
* **Minimal Kombu Version**: 4.6.4
* **Minimal Broker Version**: RabbitMQ 3.7.15
* **Minimal Result Backend Version**: N/A or Unknown
* **Minimal OS and/or Kernel Version**: Linux 4.19.71-1-lts
* **Minimal Broker Client Version**: N/A or Unknown
* **Minimal Result Backend Client Version**: N/A or Unknown

### Python Packages
<!-- Please fill the contents of pip freeze below -->
<details>
<summary><b><code>pip freeze</code> Output:</b></summary>
<p>

```
amqp==2.5.1
asn1crypto==0.24.0
atomicwrites==1.3.0
attrs==19.1.0
Automat==0.7.0
backcall==0.1.0
billiard==3.6.1.0
case==1.5.3
celery==4.3.0
cffi==1.12.3
constantly==15.1.0
cryptography==2.7
cssselect==1.1.0
decorator==4.4.0
hyperlink==19.0.0
idna==2.8
importlib-metadata==0.23
incremental==17.5.0
ipython==7.8.0
ipython-genutils==0.2.0
jedi==0.15.1
kombu==4.6.4
librabbitmq==2.0.0
linecache2==1.0.0
lxml==4.4.1
mock==3.0.5
more-itertools==7.2.0
mysqlclient==1.4.4
nose==1.3.7
packaging==19.2
parsel==1.5.2
parso==0.5.1
pexpect==4.7.0
pickleshare==0.7.5
pluggy==0.13.0
prompt-toolkit==2.0.9
ptyprocess==0.6.0
py==1.8.0
pyasn1==0.4.7
pyasn1-modules==0.2.6
pycparser==2.19
PyDispatcher==2.0.5
Pygments==2.4.2
PyHamcrest==1.9.0
pyOpenSSL==19.0.0
pyparsing==2.4.2
pytest==5.2.1
pytz==2019.2
queuelib==1.5.0
Scrapy==1.7.3
scrapy-selenium==0.0.7
selenium==3.141.0
service-identity==18.1.0
six==1.12.0
SQLAlchemy==1.3.8
traceback2==1.4.0
traitlets==4.3.2
Twisted==19.7.0
unittest2==1.1.0
urllib3==1.25.6
vine==1.3.0
w3lib==1.21.0
wcwidth==0.1.7
zipp==0.6.0
zope.interface==4.6.0
```

</p>
</details>

### Other Dependencies
<!--
Please provide system dependencies, configuration files
and other dependency information if applicable
-->
<details>
<p>
N/A
</p>
</details>

## Minimally Reproducible Test Case
<!--
Please provide a reproducible test case.
Refer to the Reporting Bugs section in our contribution guide.

We prefer submitting test cases in the form of a PR to our integration test suite.
If you can provide one, please mention the PR number below.
If not, please attach the most minimal code example required to reproduce the issue below.
If the test case is too large, please include a link to a gist or a repository below.
-->

<details>
<p>
celeryconfig.py:

```python
broker_url = 'amqp://guest:guest@localhost:5672//'

task_default_queue = 'default'
task_default_exchange = 'tasks'
task_default_exchange_type = 'topic'
task_default_routing_key = 'tasks.default'
task_queues = (
    Queue('default',   routing_key='tasks.#'),
    Queue('test', routing_key='test.#'),
)
```
</p>

<p>
celery.py:

```python
app = Celery('scan_worker')
app.conf.task_default_exchange = 'tasks'
app.conf.task_default_exchange_type = 'topic'
app.config_from_object('test_celery.celeryconfig', force=True)
```
</p>
</details>

# Expected Behavior
<!-- Describe in detail what you expect to happen -->
According to the [document](http://docs.celeryproject.org/en/latest/userguide/routing.html#manual-routing):

> If you don't set the exchange or exchange type values for a key, these will be taken from the task_default_exchange and task_default_exchange_type settings

The worker should automatically create queues that binding to the exchange with `task_default_exchange` and `task_default_exchange_type`

# Actual Behavior
<!--
Describe in detail what actually happened.
Please include a backtrace and surround it with triple backticks (```).
In addition, include the Celery daemon logs, the broker logs,
the result backend logs and system logs below if they will help us debug
the issue.
-->
The output of the command `celery worker -A test_celery -l info`:

```
 -------------- celery@arch v4.3.0 (rhubarb)
---- **** ----- 
--- * ***  * -- Linux-4.19.71-1-lts-x86_64-with-arch 2019-10-10 20:13:55
-- * - **** --- 
- ** ---------- [config]
- ** ---------- .> app:         scan_worker:0x7efdc5430a58
- ** ---------- .> transport:   amqp://guest:**@localhost:5672//
- ** ---------- .> results:     disabled://
- *** --- * --- .> concurrency: 9 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** ----- 
 -------------- [queues]
                .> default          exchange=(direct) key=tasks.#
                .> test             exchange=(direct) key=test.#
```

the queues are bound to the exchange that not match `task_default_exchange` and `task_default_exchange_type`


Discussion:

Resolving patch:
diff --git a/celery/app/amqp.py b/celery/app/amqp.py
--- a/celery/app/amqp.py
+++ b/celery/app/amqp.py
@@ -130,9 +130,9 @@ def add_compat(self, name, **options):
         return self._add(Queue.from_dict(name, **options))
 
     def _add(self, queue):
+        if queue.exchange is None or queue.exchange.name == '':
+            queue.exchange = self.default_exchange
         if not queue.routing_key:
-            if queue.exchange is None or queue.exchange.name == '':
-                queue.exchange = self.default_exchange
             queue.routing_key = self.default_routing_key
         if self.ha_policy:
             if queue.queue_arguments is None:


Test patch:
diff --git a/t/unit/app/test_amqp.py b/t/unit/app/test_amqp.py
--- a/t/unit/app/test_amqp.py
+++ b/t/unit/app/test_amqp.py
@@ -188,6 +188,35 @@ def test_setting_default_queue(self, name, exchange, rkey):
         assert queue.routing_key == rkey or name
 
 
+class test_default_exchange:
+
+    @pytest.mark.parametrize('name,exchange,rkey', [
+        ('default', 'foo', None),
+        ('default', 'foo', 'routing_key'),
+    ])
+    def test_setting_default_exchange(self, name, exchange, rkey):
+        q = Queue(name, routing_key=rkey)
+        self.app.conf.task_queues = {q}
+        self.app.conf.task_default_exchange = exchange
+        queues = dict(self.app.amqp.queues)
+        queue = queues[name]
+        assert queue.exchange.name == exchange
+
+    @pytest.mark.parametrize('name,extype,rkey', [
+        ('default', 'direct', None),
+        ('default', 'direct', 'routing_key'),
+        ('default', 'topic', None),
+        ('default', 'topic', 'routing_key'),
+    ])
+    def test_setting_default_exchange_type(self, name, extype, rkey):
+        q = Queue(name, routing_key=rkey)
+        self.app.conf.task_queues = {q}
+        self.app.conf.task_default_exchange_type = extype
+        queues = dict(self.app.amqp.queues)
+        queue = queues[name]
+        assert queue.exchange.type == extype
+
+
 class test_AMQP_proto1:
 
     def test_kwargs_must_be_mapping(self):